Class: Kludge::Many

Inherits:
Part
  • Object
show all
Defined in:
lib/kludge/many.rb

Instance Attribute Summary

Attributes inherited from Part

#children, #errors, #name, #parent, #value

Instance Method Summary collapse

Methods inherited from Part

#dependency, #dependent?, #initialize, #many?, #one?, #valid?

Constructor Details

This class inherits a constructor from Kludge::Part

Instance Method Details

#saveObject



4
5
6
7
8
9
10
11
# File 'lib/kludge/many.rb', line 4

def save
  if parent
    parent.value.send("#{name}=", value)
  end

  value.each(&:save)
  super
end

#validateObject



13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/kludge/many.rb', line 13

def validate
  if value.any? { |v| !v.valid? }
    value.map(&:errors).each do |e|
      e.each do |attribute, errors_array|
        errors_array.each do |msg|
          errors.add(attribute, msg) unless errors.added?(attribute, msg)
        end
      end
    end
    false
  else
    true
  end
end

#value=(value) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/kludge/many.rb', line 28

def value=(value)
  @value = if value.is_a?(Hash)
    value.map do |key, value|
      @name.to_s.classify.constantize.find(value.delete(:id)).tap { |v| v.assign_attributes(value) }
    end
  else
    value.map do |val|
      if val.is_a?(Hash)
        @name.to_s.classify.constantize.new(val)
      else
        val
      end
    end
  end
end