Class: XMLStruct

Inherits:
Object
  • Object
show all
Extended by:
CanParse
Includes:
CanParse
Defined in:
lib/fmylife/xmlstruct.rb

Overview

Generic XML Structure

Class Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from CanParse

xml_attribute, xml_content, xml_doc, xpath

Constructor Details

#initialize(opts = {}) ⇒ XMLStruct

Returns a new instance of XMLStruct.



82
83
84
85
86
87
88
89
90
91
92
# File 'lib/fmylife/xmlstruct.rb', line 82

def initialize(opts = {})
  if opts[:xml]
    parse_xml opts[:xml]
  else
    opts.each do |key, value|
      instance_variable_set("@#{key}".to_sym, value)
    end
  end
  post_initialize
  self
end

Class Attribute Details

.fieldsObject

Returns the value of attribute fields.



66
67
68
# File 'lib/fmylife/xmlstruct.rb', line 66

def fields
  @fields
end

Class Method Details

.field(name, type, getter, path = "") ⇒ Object



68
69
70
71
72
73
74
75
76
77
# File 'lib/fmylife/xmlstruct.rb', line 68

def field(name, type, getter, path="")
  @fields ||= {}
  if type == :attribute
    @fields[name.to_sym] = {:type => type, :getter => getter, :path => path}
  else
    @fields[name.to_sym] = {:type => type, :getter => getter}
  end
  attr_accessor name
  
end

Instance Method Details

#parse_xml(entry) ⇒ Object



94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/fmylife/xmlstruct.rb', line 94

def parse_xml(entry)
  myfields = self.class.fields
  myfields.each do |k,v|
    if v[:getter].is_a?(String) || v[:getter].is_a?(Symbol)
      if v[:type] == :attribute
        instance_variable_set("@#{k}".to_sym, xml_attribute(xpath(entry,v[:path]).first, v[:getter].to_s))
      elsif v[:type] == :node
        node = xpath(entry, v[:getter].to_s).first
        if node
          instance_variable_set "@#{k}".to_sym, xml_content(node)
        end
      end
    elsif v[:getter].is_a?(Proc)
      instance_variable_set "@#{k}".to_sym, v[:getter].call(entry)
    end
  end
end

#post_initializeObject



80
# File 'lib/fmylife/xmlstruct.rb', line 80

def post_initialize; end