Class: LazyXmlModel::ObjectProxy

Inherits:
Object
  • Object
show all
Defined in:
lib/lazy_xml_model/object_proxy.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(association_name, xml_document, xml_parent_element, options = {}) ⇒ ObjectProxy

Returns a new instance of ObjectProxy.



5
6
7
8
9
10
# File 'lib/lazy_xml_model/object_proxy.rb', line 5

def initialize(association_name, xml_document, xml_parent_element, options = {})
  @association_name = association_name
  @xml_document = xml_document
  @xml_parent_element = xml_parent_element
  @options = options
end

Instance Attribute Details

#association_nameObject (readonly)

Returns the value of attribute association_name.



3
4
5
# File 'lib/lazy_xml_model/object_proxy.rb', line 3

def association_name
  @association_name
end

#optionsObject (readonly)

Returns the value of attribute options.



3
4
5
# File 'lib/lazy_xml_model/object_proxy.rb', line 3

def options
  @options
end

#xml_documentObject (readonly)

Returns the value of attribute xml_document.



3
4
5
# File 'lib/lazy_xml_model/object_proxy.rb', line 3

def xml_document
  @xml_document
end

#xml_parent_elementObject (readonly)

Returns the value of attribute xml_parent_element.



3
4
5
# File 'lib/lazy_xml_model/object_proxy.rb', line 3

def xml_parent_element
  @xml_parent_element
end

Instance Method Details

#attributes=(attributes) ⇒ Object



50
51
52
53
54
55
56
# File 'lib/lazy_xml_model/object_proxy.rb', line 50

def attributes=(attributes)
  if object.present?
    object.assign_attributes(attributes) # Update the object
  else
    build_object(attributes) # Build the object
  end
end

#build_object(params = {}) ⇒ Object

Builder Method



38
39
40
41
42
43
44
45
46
47
48
# File 'lib/lazy_xml_model/object_proxy.rb', line 38

def build_object(params = {})
  new_object =
    begin
      klass.new(params)
    # Incase the class does not include ActiveModel::AttributeAssignment
    rescue ArgumentError
      klass.new
    end

  self.object = new_object
end

#objectObject

Getter Method



13
14
15
16
17
18
19
20
21
22
23
# File 'lib/lazy_xml_model/object_proxy.rb', line 13

def object
  element = xml_parent_element.elements.find { |element| element.name == association_name }
  return unless element.present?

  @object ||= begin
    new_object = klass.new
    new_object.xml_parent_element = xml_parent_element
    new_object.xml_element = element
    new_object
  end
end

#object=(new_object) ⇒ Object

Setter Method



26
27
28
29
30
31
32
33
34
35
# File 'lib/lazy_xml_model/object_proxy.rb', line 26

def object=(new_object)
  @object.delete if @object.present?

  @object = new_object

  xml_parent_element.add_child(
    new_object.xml_element
  )
  new_object.xml_parent_element = xml_parent_element
end