Class: Sinclair::MethodDefinition::BlockDefinition Private

Inherits:
Sinclair::MethodDefinition show all
Defined in:
lib/sinclair/method_definition/block_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 block

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, **options, &block) ⇒ BlockDefinition

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 BlockDefinition.

Parameters:

  • name (String, Symbol) —

    name of the method

  • block (Proc) —

    block with code to be added 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/block_definition.rb', line 12

def initialize(name, **options, &block)
  @block = block
  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:

Using block method with no options

class MyModel
end

instance = MyModel.new

method_definition = Sinclair::MethodDefinition::BlockDefinition.new(:sequence) do
  @x = @x.to_i ** 2 + 1
end

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

instance.instance_variable_get(:@sequence) # returns nil
instance.instance_variable_get(:@x)        # returns nil

instance.sequence               # returns 1
instance.sequence               # returns 1 (cached value)

instance.instance_variable_get(:@sequence) # returns 1
instance.instance_variable_get(:@x)        # returns 1

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/block_definition.rb', line 46

def build(klass)
  klass.send(:define_method, name, method_block)
end