| Class | REXML::Element |
| In: |
lib/response_from.rb
|
| Parent: | Object |
Convert an Element to a class. This class has the same name as the element name. A hash of mappings can be used to specify a different class. For example:
class User
def initialize(h)
@id = h[:id]
@username = h[:username]
@name = h[:name]
end
def authorized?
true
end
end
class UnauthorizedUser < User
def authorized?
false
end
end
xml = '<user><id>12</id><username>mary</username><name>Mary Jane</name></user>'
root = REXML::Document.new(xml).root
user = root.from_xml({:user => UnauthorizedUser})
if user.authorized?
...
end
# File lib/response_from.rb, line 97
97: def from_xml(mappings = {})
98: if mappings.keys.include?(self.name.to_sym)
99: mappings[self.name.to_sym].new(argument_hash(mappings))
100: elsif (Inflector.singularize(self.name) == self.name)
101: if self.elements.empty?
102: {Inflector.underscore(self.name).to_sym => self.text}
103: else
104: Inflector.constantize(self.name.capitalize).new(argument_hash(mappings))
105: end
106: else
107: self.elements.map { |e| e.from_xml(mappings) }
108: end
109: end