Class: ObjectForge::Crucible

Inherits:
UnBasicObject show all
Defined in:
lib/object_forge/crucible.rb

Overview

Note:

This class is not intended to be used directly, but it’s not a private API.

Melting pot for the forged object’s attributes.

Since:

  • 0.1.0

Instance Method Summary collapse

Methods inherited from UnBasicObject

#class, #eql?, #freeze, #frozen?, #hash, #inspect, #is_a?, #pretty_print, #pretty_print_cycle, #respond_to?, #to_s

Constructor Details

#initialize(attributes) ⇒ Crucible

Returns a new instance of Crucible.

Since:

  • 0.1.0



20
21
22
23
24
# File 'lib/object_forge/crucible.rb', line 20

def initialize(attributes)
  super()
  @attributes = attributes
  @resolved_attributes = ::Set.new
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name) ⇒ Any (private) Also known as: []

Get the value of the attribute name.

To prevent problems with calling methods which may be defined, #[] can be used instead.

Examples:

attrs = {
  name: -> { "Name" },
  description: -> { name.downcase },
  duration: -> { rand(1000) }
}
Crucible.new(attrs).resolve!
# => { name: "Name", description: "name", duration: 123 }

using conflicting and reserved names

attrs = {
  "[]": -> { "Brackets" },
  "[]=": -> { "#{self[:[]]} are brackets" },
  "!": -> { "#{self[:[]=]}!" }
}
Crucible.new(attrs).resolve!
# => { "[]": "Brackets", "[]=": "Brackets are brackets", "!": "Brackets are brackets!" }

Since:

  • 0.1.0



68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/object_forge/crucible.rb', line 68

def method_missing(name)
  if @attributes.key?(name)
    if @resolved_attributes.include?(name) || !(::Proc === @attributes[name])
      @attributes[name]
    else
      @resolved_attributes << name
      @attributes[name] = instance_exec(&@attributes[name])
    end
  else
    super
  end
end

Instance Method Details

#resolve!Hash{Symbol => Any}

Note:

This method destructively modifies initial attributes.

Resolve all attributes by calling their Procs, using self as the evaluation context.

Attributes can freely refer to each other inside Procs through bareword names or #[]. However, make sure to avoid cyclic dependencies: they aren’t specially detected or handled, and will cause SystemStackError.

Since:

  • 0.1.0



37
38
39
40
# File 'lib/object_forge/crucible.rb', line 37

def resolve!
  @attributes.each_key { |name| method_missing(name) }
  @attributes
end