Module: Hermes::Builders

Included in:
IntegrationCase
Defined in:
lib/hermes/builders.rb

Constant Summary collapse

ATTRIBUTES_REGEX =
/valid_(.*?)_attributes$/
BUILDER_REGEX =
/(create|new)_(.*?)(!)?$/
@@builders =
ActiveSupport::OrderedHash.new

Class Method Summary collapse

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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



137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/hermes/builders.rb', line 137

def method_missing(method, *args, &block)
  case method.to_s
  when BUILDER_REGEX
    return super unless Builders.has_builder?($2)
    klass, hash = Builders.retrieve(self, $2, method, args.first)
    object = klass.new
    object.assign_attributes hash, :without_protection => true
    object.send("save#{$3}") if $1 == "create"
    object
  when ATTRIBUTES_REGEX
    return super unless Builders.has_builder?($1)
    Builders.retrieve(self, $1, method, args.first)[1]
  else
    super
  end
end

Class Method Details

.build(name, options = {}, &block) ⇒ Object



88
89
90
91
92
93
94
95
96
97
98
# File 'lib/hermes/builders.rb', line 88

def build(name, options={}, &block)
  klass = options[:class] || name.to_s.classify.constantize

  builder = if options[:like]
    load_attributes_from_fixture(name.to_s.pluralize, options[:like], block)
  else
    block
  end

  @@builders[name] = [klass, builder]
end

.has_builder?(name) ⇒ Boolean

Returns:

  • (Boolean)


100
101
102
# File 'lib/hermes/builders.rb', line 100

def has_builder?(name)
  @@builders.key?(name.to_sym)
end

.retrieve(scope, name, method, options) ⇒ Object



104
105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/hermes/builders.rb', line 104

def retrieve(scope, name, method, options)
  if builder = @@builders[name.to_sym]
    klass, block = builder

    hash = block ? block.bind(scope).call : {}
    hash.symbolize_keys!
    hash.merge!(options || {})
    hash.delete(:id)

    [klass, hash]
  else
    raise NoMethodError, "No builder #{name.inspect} for `#{method}'"
  end
end

Instance Method Details

#respond_to?(method) ⇒ Boolean

Returns:

  • (Boolean)


126
127
128
129
130
131
132
133
134
135
# File 'lib/hermes/builders.rb', line 126

def respond_to?(method)
  case method.to_s
  when BUILDER_REGEX
    Builders.has_builder?($2)
  when ATTRIBUTES_REGEX
    Builders.has_builder?($1)
  else
    super
  end
end