Module: Peacekeeper::ModelDelegation

Included in:
Model, Model
Defined in:
lib/peacekeeper/model_delegation.rb

Defined Under Namespace

Classes: Pass

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(mid, *args, &block) ⇒ Object



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

def method_missing(mid, *args, &block)
  if !delegate.nil? && delegate.respond_to?(mid)
    mblock = begin
               delegate.method(mid).to_proc
             rescue NameError
               proc do |*args, &block|
                 delegate.send(mid, *args, &block)
               end
             end
    define_wrapped_singleton_method(mid, mblock)
    __send__(mid, *args, &block)
  else
    super
  end
end

Instance Method Details

#def_data_method(mid, &mblock) ⇒ Object



56
57
58
59
60
# File 'lib/peacekeeper/model_delegation.rb', line 56

def def_data_method(mid, &mblock)
  define_method(mid) do |*args|
    wrap(delegate.instance_exec(*args, &mblock))
  end
end

#def_singleton_data_method(mid, &mblock) ⇒ Object



62
63
64
65
66
# File 'lib/peacekeeper/model_delegation.rb', line 62

def def_singleton_data_method(mid, &mblock)
  define_singleton_method(mid) do |*args|
    wrap(delegate.instance_exec(*args, &mblock))
  end
end

#define_wrapped_singleton_method(mid, mblock) ⇒ Object



50
51
52
53
54
# File 'lib/peacekeeper/model_delegation.rb', line 50

def define_wrapped_singleton_method(mid, mblock)
  define_singleton_method(mid) do |*args, &block|
    wrap(mblock.call(*args, &block))
  end
end

#respond_to_missing?(mid, include_private) ⇒ Boolean

Returns:

  • (Boolean)


25
26
27
28
29
30
31
32
# File 'lib/peacekeeper/model_delegation.rb', line 25

def respond_to_missing?(mid, include_private)
  ret = delegate.respond_to?(mid, include_private)
  if ret && include_private && !delegate.respond_to?(mid, false)
    # Don't delegate private methods
    return false
  end
  ret
end

#wrap(val) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/peacekeeper/model_delegation.rb', line 34

def wrap(val)
  if (self.kind_of?(Class) && val.kind_of?(delegate))
    new(val)
  elsif (self.kind_of?(Peacekeeper::Model) && val.kind_of?(delegate.class))
    self.class.new(val)
  elsif (Peacekeeper::Model.has_wrapper_for?(val.class))
    Peacekeeper::Model.wrapper_for(val.class).new(val)
  elsif (val.kind_of?(Hash))
    Hash[*val.flat_map { |k, v| [k, wrap(v)] }]
  elsif (val.kind_of?(Enumerable) || val.methods.include?(:each))
    val.map { |i| wrap(i) }
  else
    val
  end
end