Method: Attributor::Hash.example_contents

Defined in:
lib/attributor/types/hash.rb

.example_contents(context, parent, **values) ⇒ Object



189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
# File 'lib/attributor/types/hash.rb', line 189

def self.example_contents(context, parent, **values)
  hash = ::Hash.new
  example_depth = context.size
  # Be smart about what attributes to use for the example: i.e. have into account complex requirements
  # that might have been defined in the hash like at_most(1).of ..., exactly(2).of ...etc.
  # But play it safe and default to the previous behavior in case there is any error processing them
  # ( that is until the SmartAttributeSelector class isn't fully tested and ready for prime time)
  begin
    stack = SmartAttributeSelector.new( requirements.map(&:describe), keys.keys , values)
    selected = stack.process
  rescue => e
    selected = keys.keys
  end

  keys.select{|n,attr| selected.include? n}.each do |sub_attribute_name, sub_attribute|
    if sub_attribute.attributes
      # TODO: add option to raise an exception in this case?
      next if example_depth > MAX_EXAMPLE_DEPTH
    end

    sub_context = generate_subcontext(context, sub_attribute_name)
    block = proc do
      value = values.fetch(sub_attribute_name) do
        sub_attribute.example(sub_context, parent: parent)
      end
      sub_attribute.load(value, sub_context)
    end

    hash[sub_attribute_name] = block
  end

  hash
end