lib/happymapper/item.rb in happymapper-0.2.4 vs lib/happymapper/item.rb in happymapper-0.2.5
- old
+ new
@@ -19,10 +19,14 @@
self.tag = o.delete(:tag) || name.to_s
self.options = o
@xml_type = self.class.to_s.split('::').last.downcase
end
+
+ def constant
+ @constant ||= constantize(type)
+ end
def from_xml_node(node, namespace)
if primitive?
find(node, namespace) do |n|
if n.respond_to?(:content)
@@ -39,17 +43,17 @@
else
value = n.to_s
end
begin
- type.send(options[:parser].to_sym, value)
+ constant.send(options[:parser].to_sym, value)
rescue
nil
end
end
else
- type.parse(node, options)
+ constant.parse(node, options)
end
end
end
def xpath(namespace = self.namespace)
@@ -60,11 +64,11 @@
# puts "xpath: #{xpath}"
xpath
end
def primitive?
- Types.include?(type)
+ Types.include?(constant)
end
def element?
@xml_type == 'element'
end
@@ -76,19 +80,19 @@
def method_name
@method_name ||= name.tr('-', '_')
end
def typecast(value)
- return value if value.kind_of?(type) || value.nil?
+ return value if value.kind_of?(constant) || value.nil?
begin
- if type == String then value.to_s
- elsif type == Float then value.to_f
- elsif type == Time then Time.parse(value.to_s)
- elsif type == Date then Date.parse(value.to_s)
- elsif type == DateTime then DateTime.parse(value.to_s)
- elsif type == Boolean then ['true', 't', '1'].include?(value.to_s.downcase)
- elsif type == Integer
+ if constant == String then value.to_s
+ elsif constant == Float then value.to_f
+ elsif constant == Time then Time.parse(value.to_s)
+ elsif constant == Date then Date.parse(value.to_s)
+ elsif constant == DateTime then DateTime.parse(value.to_s)
+ elsif constant == Boolean then ['true', 't', '1'].include?(value.to_s.downcase)
+ elsif constant == Integer
# ganked from datamapper
value_to_i = value.to_i
if value_to_i == 0 && value != '0'
value_to_s = value.to_s
begin
@@ -106,9 +110,24 @@
value
end
end
private
+ def constantize(type)
+ if type.is_a?(String)
+ names = type.split('::')
+ constant = Object
+ names.each do |name|
+ constant = constant.const_defined?(name) ?
+ constant.const_get(name) :
+ constant.const_missing(name)
+ end
+ constant
+ else
+ type
+ end
+ end
+
def find(node, namespace, &block)
# this node has a custom namespace (that is present in the doc)
if self.namespace && node.namespaces.find_by_prefix(self.namespace)
# from the class definition
namespace = self.namespace
\ No newline at end of file