Class: Bindless::Model

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

Instance Method Summary collapse

Constructor Details

#initialize(bindings = []) ⇒ Model

Returns a new instance of Model.



4
5
6
# File 'lib/bindless/model.rb', line 4

def initialize(bindings = [])
  @bindings = bindings
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(m, *args) ⇒ Object

Raises:

  • (NoMethodError)


8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/bindless/model.rb', line 8

def method_missing(m, *args)
  @bindings.reverse_each do |bind|
    begin
      method = eval("method(%s)" % m.inspect, bind)
    rescue NameError
    else
      return method.call(*args)
    end
    begin
      value = eval(m.to_s, bind)
      return value
    rescue NameError
    end
  end
  raise NoMethodError, "No such variable or method: %s" % m
end

Instance Method Details

#get_bindingObject



41
42
43
# File 'lib/bindless/model.rb', line 41

def get_binding
  instance_eval { binding }
end

#pop_bindingObject



25
26
27
# File 'lib/bindless/model.rb', line 25

def pop_binding
  @bindings.pop
end

#push_binding(bind) ⇒ Object



29
30
31
# File 'lib/bindless/model.rb', line 29

def push_binding(bind)
  @bindings.push bind
end

#push_hash(vars) ⇒ Object



37
38
39
# File 'lib/bindless/model.rb', line 37

def push_hash(vars)
  push_instance Struct.new(*vars.keys).new(*vars.values)
end

#push_instance(obj) ⇒ Object



33
34
35
# File 'lib/bindless/model.rb', line 33

def push_instance(obj)
  @bindings.push obj.instance_eval { binding }
end

#push_method(name, p, obj = nil) ⇒ Object



49
50
51
52
53
54
55
56
# File 'lib/bindless/model.rb', line 49

def push_method(name, p, obj=nil)
  x = Object.new
  singleton = class << x; self; end
  singleton.send(:define_method, name, lambda { |*args|
    obj.instance_exec(*args, &p)
  })
  push_instance x
end

#run_proc(p, *args) ⇒ Object



45
46
47
# File 'lib/bindless/model.rb', line 45

def run_proc(p, *args)
  instance_exec(*args, &p)
end