Class: FormObj::Struct

Inherits:
Object
  • Object
show all
Defined in:
lib/form_obj/struct.rb,
lib/form_obj/struct/array.rb,
lib/form_obj/struct/attribute.rb,
lib/form_obj/struct/attributes.rb

Direct Known Subclasses

Form

Defined Under Namespace

Classes: Array, Attribute, Attributes

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ Struct

Returns a new instance of Struct.



63
64
65
66
# File 'lib/form_obj/struct.rb', line 63

def initialize(*args)
  super()
  update_attributes(*args) if args.size > 0 && args[0]
end

Class Method Details

.array_classObject



20
21
22
# File 'lib/form_obj/struct.rb', line 20

def array_class
  Array
end

.attribute(name, opts = {}, &block) ⇒ Object



32
33
34
35
36
37
38
# File 'lib/form_obj/struct.rb', line 32

def attribute(name, opts = {}, &block)
  attr = attribute_class.new(name, opts.merge(parent: self), &block)
  self._attributes = _attributes.add(attr)
  _define_attribute_getter(attr)
  _define_attribute_setter(attr)
  self
end

.attribute_classObject



28
29
30
# File 'lib/form_obj/struct.rb', line 28

def attribute_class
  Attribute
end

.attributesObject



40
41
42
# File 'lib/form_obj/struct.rb', line 40

def attributes
  _attributes.map(&:name)
end

.inspectObject



44
45
46
# File 'lib/form_obj/struct.rb', line 44

def inspect
  "#{name}#{attributes.size > 0 ? "(#{attributes.join(', ')})" : ''}"
end

.nested_classObject



24
25
26
# File 'lib/form_obj/struct.rb', line 24

def nested_class
  ::FormObj::Struct
end

Instance Method Details

#inspectObject



98
99
100
# File 'lib/form_obj/struct.rb', line 98

def inspect
  "#<#{inner_inspect}>"
end

#primary_keyObject



68
69
70
# File 'lib/form_obj/struct.rb', line 68

def primary_key
  send(self.class.primary_key)
end

#primary_key=(val) ⇒ Object



72
73
74
# File 'lib/form_obj/struct.rb', line 72

def primary_key=(val)
  send("#{self.class.primary_key}=", val)
end

#to_hashObject



94
95
96
# File 'lib/form_obj/struct.rb', line 94

def to_hash
  Hash[self.class._attributes.map { |attribute| [attribute.name, attribute.subform? ? read_attribute(attribute).to_hash : read_attribute(attribute)] }]
end

#update_attributes(attrs, raise_if_not_found: true) ⇒ Object



76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/form_obj/struct.rb', line 76

def update_attributes(attrs, raise_if_not_found: true)
  attrs = HashWithIndifferentAccess.new(attrs) unless attrs.is_a? HashWithIndifferentAccess
  attrs.each_pair do |attr_name, attr_value|
    attr = self.class._attributes.find(attr_name)
    if attr.nil?
      raise UnknownAttributeError.new(attr_name) if raise_if_not_found
    else
      if attr.subform? && !attr_value.is_a?(FormObj::Struct)
        read_attribute(attr).update_attributes(attr_value, raise_if_not_found: raise_if_not_found)
      else
        update_attribute(attr, attr_value)
      end
    end
  end

  self
end