Module: MiniObject::Injectable

Included in:
Box, Inline
Defined in:
lib/injectable.rb

Constant Summary collapse

NULL =
Object.new

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.getsetter_definition_for(name) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/injectable.rb', line 14

def self.getsetter_definition_for name
  lambda do |value = NULL, &block|
    if block
      if value == NULL || value == nil
        instance_variable_set("@#{name}_proc", block)
      else
        send("#{name}=", value)
      end
    else
      if value == NULL
        p = instance_variable_get("@#{name}_proc") ||
          self.class.instance_variable_get("@#{name}_default_proc") ||
          raise("No #{name} defined yet for #{inspect}")
        p.call
      else
        send("#{name}=", value)
      end
    end
  end
end

.included(klass) ⇒ Object



10
11
12
# File 'lib/injectable.rb', line 10

def self.included klass
  klass.extend self
end

.setter_definition_for(name) ⇒ Object



35
36
37
38
39
40
# File 'lib/injectable.rb', line 35

def self.setter_definition_for name
  lambda do |value|
    instance_variable_set("@#{name}_proc", lambda{ value })
    value
  end
end

Instance Method Details

#attr_injectable(name, &block) ⇒ Object



48
49
50
51
52
# File 'lib/injectable.rb', line 48

def attr_injectable name, &block
  define_method name, &Injectable.getsetter_definition_for(name)
  define_method "#{name}=", &Injectable.setter_definition_for(name)
  instance_variable_set("@#{name}_default_proc", block) if block
end

#attributes=(attrs) ⇒ Object



70
71
72
73
74
# File 'lib/injectable.rb', line 70

def attributes= attrs
  attrs.each do |k,v|
    public_send "#{k}=", v
  end
end

#cattr_injectable(name, &block) ⇒ Object



42
43
44
45
46
# File 'lib/injectable.rb', line 42

def cattr_injectable name, &block
  define_singleton_method name, &Injectable.getsetter_definition_for(name)
  define_singleton_method "#{name}=", &Injectable.setter_definition_for(name)
  send(name, &block) if block
end

#initialize(&block) ⇒ Object



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

def initialize &block
  super
  block.call self if block
end

#let(name, &block) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/injectable.rb', line 54

def let name, &block
  var_name = :"@#{name}"

  define_singleton_method "#{name}=" do |value|
    instance_variable_set var_name, value
  end

  define_singleton_method name do
    if instance_variable_defined? var_name
      instance_variable_get var_name
    else
      instance_variable_set var_name, block.call(self)
    end
  end
end