Module: Shaf::Yard::NestedAttributes

Defined in:
lib/shaf/yard/nested_attributes.rb

Instance Method Summary collapse

Instance Method Details

#flatten(nested, base_key) ⇒ Object



21
22
23
24
25
26
27
28
29
30
# File 'lib/shaf/yard/nested_attributes.rb', line 21

def flatten(nested, base_key)
  return {} if !nested || nested.empty?

  nested.each_with_object({}) do |(desc, nested), all|
    key = nested_key(base_key, desc)
    all[key] = desc
    next unless nested
    all.merge!(flatten(nested, key))
  end
end

#nested_attributes(descriptor) ⇒ Object



14
15
16
17
18
19
# File 'lib/shaf/yard/nested_attributes.rb', line 14

def nested_attributes(descriptor)
  attrs = Array(descriptor&.attributes)
  attrs.each_with_object({}) do |attr, nested|
    nested[attr] = nested_attributes(attr)
  end.transform_values { |v| v.empty? ? nil : v }
end

#nested_attributes_for(descriptor) ⇒ Object



6
7
8
9
10
11
12
# File 'lib/shaf/yard/nested_attributes.rb', line 6

def nested_attributes_for(descriptor)
  return {} unless descriptor

  base_key = nested_key(descriptor)
  nested_attributes(descriptor)
    .yield_self { |nested| flatten(nested, base_key) }
end

#nested_key(base_key = nil, desc) ⇒ Object



32
33
34
# File 'lib/shaf/yard/nested_attributes.rb', line 32

def nested_key(base_key = nil, desc)
  [base_key, desc.name].compact.join('.')
end