Module: SubstAttr::Substitute

Extended by:
Substitute
Included in:
Substitute
Defined in:
lib/subst_attr/substitute.rb,
lib/subst_attr/substitute/null_object.rb

Defined Under Namespace

Modules: Defaults

Constant Summary collapse

NullObject =
Class.new(null_object_class)

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.null_object_classObject



3
4
5
6
7
8
9
10
11
12
# File 'lib/subst_attr/substitute/null_object.rb', line 3

def self.null_object_class
  Mimic::Build.(Object, record: false) do
    def self.build
      new
    end

    def method_missing(*)
    end
  end
end

Instance Method Details

#build(interface = nil, record = nil) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/subst_attr/substitute.rb', line 5

def build(interface=nil, record=nil)
  if record.nil?
    record = Defaults.record
  end

  if interface.nil?
    return NullObject.build
  end

  substitute_module = substitute_module(interface)

  if substitute_module.nil?
    return mimic(interface, record)
  end

  if substitute_module.respond_to?(:build)
    return substitute_module.send(:build)
  end

  mimic = mimic(interface, record)
  mimic.extend(substitute_module)

  mimic
end

#call(attr_name, receiver) ⇒ Object



38
39
40
41
42
43
# File 'lib/subst_attr/substitute.rb', line 38

def call(attr_name, receiver)
  interface = receiver.send(attr_name).class
  substitute = build(interface)
  receiver.send :"#{attr_name}=", substitute
  substitute
end

#mimic(interface, record) ⇒ Object



34
35
36
# File 'lib/subst_attr/substitute.rb', line 34

def mimic(interface, record)
  Mimic.(interface, record: record)
end

#null_objectObject



30
31
32
# File 'lib/subst_attr/substitute.rb', line 30

def null_object
  NullObject.build
end

#substitute_module(interface) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/subst_attr/substitute.rb', line 45

def substitute_module(interface)
  constant_name = :Substitute

  reflection = Reflect.(interface, constant_name, strict: false, ancestors: true)

  if reflection.nil?
    return nil
  end

  mod = reflection.constant

  # Special case:
  # Including Substitute puts SubstAttr::Substitute
  # in the constant lookup class
  if mod.equal?(self)
    return nil
  end

  mod
end