Class: Lich::Common::StringProc

Inherits:
Object
  • Object
show all
Defined in:
lib/common/class_exts/stringproc.rb

Overview

A class that processes strings as Ruby code.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(string) ⇒ StringProc

Initializes a new StringProc instance with the given string.

Parameters:

  • string (String)

    the string to be processed as Ruby code



11
12
13
# File 'lib/common/class_exts/stringproc.rb', line 11

def initialize(string)
  @string = string
end

Class Method Details

._load(string) ⇒ StringProc

Loads a StringProc object from a string.

Examples:

sp = StringProc._load("1 + 1")
sp.call # => 2

Parameters:

  • string (String)

    the string to load

Returns:

  • (StringProc)

    a new StringProc instance initialized with the string



75
76
77
# File 'lib/common/class_exts/stringproc.rb', line 75

def StringProc._load(string)
  StringProc.new(string)
end

Instance Method Details

#_dump(_d = nil) ⇒ String

Dumps the string representation of the object.

Parameters:

  • _d (nil) (defaults to: nil)

    optional parameter (not used)

Returns:

  • (String)

    the string representation of the object



46
47
48
# File 'lib/common/class_exts/stringproc.rb', line 46

def _dump(_d = nil)
  @string
end

#call(*_a) ⇒ Object

Calls the stored string as Ruby code.

Examples:

sp = StringProc.new("1 + 1")
sp.call # => 2

Parameters:

  • _a (Array)

    optional arguments (not used)

Returns:

  • (Object)

    the result of evaluating the string

Raises:

  • (SyntaxError)

    if the string contains invalid Ruby code



38
39
40
# File 'lib/common/class_exts/stringproc.rb', line 38

def call(*_a)
  proc { eval(@string) }.call
end

#classClass

Returns the class of the current object.

Returns:

  • (Class)

    the class of the object, which is Proc



26
27
28
# File 'lib/common/class_exts/stringproc.rb', line 26

def class
  Proc
end

#inspectString

Returns a string representation of the StringProc object.

Returns:

  • (String)

    a string describing the StringProc instance



53
54
55
# File 'lib/common/class_exts/stringproc.rb', line 53

def inspect
  "StringProc.new(#{@string.inspect})"
end

#kind_of?(type) ⇒ Boolean

Checks if the current object is of the specified type.

Parameters:

  • type (Class)

    the class to check against

Returns:

  • (Boolean)

    true if the object is of the specified type, false otherwise



19
20
21
# File 'lib/common/class_exts/stringproc.rb', line 19

def kind_of?(type)
  Proc.new {}.kind_of? type
end

#to_json(*args) ⇒ String

Converts the StringProc object to JSON format.

Examples:

sp = StringProc.new("1 + 1")
sp.to_json # => ";e \"1 + 1\""

Parameters:

  • args (Array)

    optional arguments for JSON conversion

Returns:

  • (String)

    the JSON representation of the object



64
65
66
# File 'lib/common/class_exts/stringproc.rb', line 64

def to_json(*args)
  ";e #{_dump}".to_json(args)
end