Class: DynamicMethods::DynamicMethod

Inherits:
Object
  • Object
show all
Defined in:
lib/dynamic_methods.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(receiver, pattern, &definition) ⇒ DynamicMethod

Create new DynamicMethod. Excepts a RegEx pattern as first argument and the method definition as block argument.



9
10
11
# File 'lib/dynamic_methods.rb', line 9

def initialize receiver, pattern, &definition
  @receiver, @pattern, @definition = receiver, pattern, definition
end

Instance Attribute Details

#definitionObject

Returns the value of attribute definition.



5
6
7
# File 'lib/dynamic_methods.rb', line 5

def definition
  @definition
end

#patternObject

Returns the value of attribute pattern.



5
6
7
# File 'lib/dynamic_methods.rb', line 5

def pattern
  @pattern
end

#receiverObject

Returns the value of attribute receiver.



5
6
7
# File 'lib/dynamic_methods.rb', line 5

def receiver
  @receiver
end

Instance Method Details

#define(name, captures) ⇒ Object

If method hasn’t been defined, define method in receiver’s class



14
15
16
17
18
19
20
21
# File 'lib/dynamic_methods.rb', line 14

def define name, captures
  return if receiver.method_defined? name

  method_definition = @definition
  receiver.send :define_method, name do |*args|
    instance_exec *(captures + args), &method_definition
  end
end

#define_and_call(object, name, captures, *args, &block) ⇒ Object

Define and call method.



24
25
26
27
# File 'lib/dynamic_methods.rb', line 24

def define_and_call object, name, captures, *args, &block
  define name, captures
  object.send name, *args, &block
end

#match(name) ⇒ Object

Match name against this DynamicMethods pattern



30
31
32
# File 'lib/dynamic_methods.rb', line 30

def match name
  pattern.match name.to_s
end