Class: Sinclair::MethodDefinition::StringDefinition Private

Inherits:
Sinclair::MethodDefinition show all
Defined in:
lib/sinclair/method_definition/string_definition.rb

Overview

This class is part of a private API. You should avoid using this class if possible, as it may be removed or be changed in the future.

Define a method from string

Constant Summary

Constants inherited from Sinclair::MethodDefinition

DEFAULT_OPTIONS

Instance Attribute Summary

Attributes included from OptionsParser

#options

Instance Method Summary collapse

Methods inherited from Sinclair::MethodDefinition

from

Methods included from OptionsParser

#options_object

Constructor Details

#initialize(name, code = nil, **options) ⇒ StringDefinition

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns a new instance of StringDefinition.

Parameters:

  • name (String, Symbol) —

    name of the method

  • code (String) (defaults to: nil) —

    code to be evaluated as method

  • options (Hash) —

    Options of construction

Options Hash (**options):

  • cached (Boolean) —

    Flag telling to create a method with cache



12
13
14
15
# File 'lib/sinclair/method_definition/string_definition.rb', line 12

def initialize(name, code = nil, **options)
  @code = code
  super(name, **options)
end

Instance Method Details

#build(klass) ⇒ Symbol

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Adds the method to given klass

Examples:

With no options

class MyModel
end

instance = MyModel.new

method_definition = Sinclair::MethodDefinition.from(
  :sequence, '@x = @x.to_i ** 2 + 1'
)

method_definition.build(klass)      # adds instance_method :sequence to
                                    # MyModel instances

instance.instance_variable_get(:@x) # returns nil

instance.sequence                   # returns 1
instance.sequence                   # returns 2
instance.sequence                   # returns 5

instance.instance_variable_get(:@x) # returns 5

Parameters:

  • klass (Class) —

    class which will receive the new method

Returns:

  • (Symbol) —

    name of the created method

See Also:



46
47
48
# File 'lib/sinclair/method_definition/string_definition.rb', line 46

def build(klass)
  klass.module_eval(code_definition, __FILE__, __LINE__ + 1)
end