lib/morph.rb in morph-0.2.7 vs lib/morph.rb in morph-0.2.8

- old
+ new

@@ -1,28 +1,68 @@ -require 'activesupport' +begin + require 'active_support/core_ext/object/blank' + require 'active_support/inflector' + require 'active_support/core_ext/string/inflections' + require 'active_support/core_ext/xml_mini' + require 'active_support/core_ext/hash/conversions' +rescue Exception => e + begin + require 'active_support' + rescue Exception => e + require 'activesupport' + end +end module Morph - VERSION = "0.2.7" + VERSION = "0.2.8" class << self def generate_migrations object, options={} options[:ignore] ||= [] options[:belongs_to_id] ||= '' migrations = [] name = object.class.name.demodulize.underscore add_migration name, object.morph_attributes, migrations, options end + def from_tsv tsv, class_name, namespace=Morph + lines = tsv.split("\n") + attributes = lines[0].split("\t") + lines = lines[1..(lines.length-1)] + objects = [] + lines.each do |line| + values = line.split("\t") + object = object_from_name class_name, namespace + attributes.each_with_index do |attribute, index| + object.morph(attribute, values[index]) + end + objects << object + end + objects + end + + def from_xml xml, namespace=Morph + hash = Hash.from_xml xml + from_hash hash, namespace + end + def from_hash hash, namespace=Morph if hash.keys.size == 1 key = hash.keys.first - object = object_from_name key, namespace + if hash[key].is_a? Hash attributes = hash[key] + object = object_from_name(key, namespace) add_to_object object, attributes, namespace + object + elsif hash[key].is_a? Array + array = hash[key] + name = key.to_s.singularize + objects_from_array(array, name, namespace) + else + raise 'hash root value must be a Hash or an Array' end - object else raise 'hash must have single key' end end @@ -40,11 +80,11 @@ attributes.to_a.sort{|a,b| a[0].to_s <=> b[0].to_s}.each do |attribute, value| case value when String attribute_name = attribute.to_s unless options[:ignore].include?(attribute_name) - type = attribute_name.ends_with?('date') ? 'date' : 'string' + type = attribute_name[/date$/] ? 'date' : 'string' attribute_def = "#{attribute}:#{type}" migration.sub!(migration, "#{migration} #{attribute_def}") end when Array options[:belongs_to_id] = " #{name}_id:integer" @@ -90,13 +130,14 @@ def add_to_object object, attributes, namespace attributes.each do |name, value| attribute = name.gsub(':',' ').underscore case value - when String, Date + when String, Date, Time, TrueClass, FalseClass, Fixnum, Float object.morph(attribute, value) when Array - object.morph(attribute.pluralize, objects_from_array(value, name, namespace)) + attribute = attribute.pluralize + object.morph(attribute, objects_from_array(value, name, namespace)) when Hash object.morph(attribute, object_from_hash(value, name, namespace)) when NilClass object.morph(attribute, nil) else