Module: Rulebook::InstanceMethods

Defined in:
lib/rulebook/instance_methods.rb

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(meth, *args, &blk) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/rulebook/instance_methods.rb', line 3

def method_missing(meth, *args, &blk)
  # Classes and instances find their rulebook differently.
  begin
    rulebook = self.class.rulebook
  rescue NoMethodError
    rulebook = metaclass.rulebook
  end

  rules = rulebook.rules_that_match_against(meth)
  unless rules.nil?
    rules.each do |rule|
      # =S Run all matched rules or run first matched rule...?
      # rule = rules.first

      captures = rule[meth].captures || []
      block = rule.block
    
      # Remove the possibility of optional arguments
      arity = block.arity == -1 ? 0 : block.arity

      # Define the method
      meta_def(meth) do |*args|
        instance_exec(*(captures + args).take(arity), &block)
      end 

      # klass = self.class
      # klass.send(:define_method, meth) do |*args|
      #   instance_exec(*(captures + args).take(arity), &block)
      # end 
    
      # Call the method and return the result
      return send(meth, *args, &block)
    end
  else
    super
  end
end