Module: Binder

Included in:
Object
Defined in:
lib/binder/binder.rb

Instance Method Summary collapse

Instance Method Details

#bind(method_name, closure) ⇒ Object

Raises:

  • (ArgumentError)


2
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
# File 'lib/binder/binder.rb', line 2

def bind(method_name, closure)
  raise ArgumentError, "You may only pass symbols to #bind" unless closure.kind_of?(Symbol)
  
  if closure == :self
    self.class_eval do
      eval(
        "
        def #{method_name}(&block)
          if block
            block.bind_to(self).call
          end
        end
        "
      )
    end
  else
    self.class_eval do
      eval(
        "
        def #{method_name}(&block)
          if block
            # if we're suposed to bind an object returned by a method
            if self.respond_to?(:#{closure})
              block.bind_to(self.#{closure}).call
            # if self has an instance variable 
            elsif @#{closure}
              block.bind_to(@#{closure}).call
            else
              raise StandardError, \"Trying to bind to an unknown method or variable: #{closure}\"
            end
          end
        end
        "
      )
    end
  end      
end