Skip to content

Instantly share code, notes, and snippets.

@qoobaa
Created May 10, 2009 12:38
Show Gist options
  • Save qoobaa/109605 to your computer and use it in GitHub Desktop.
Save qoobaa/109605 to your computer and use it in GitHub Desktop.
# [:method_one, :method_two]
# [[:method_one, :other_method_one]]
# [[:method_one, :other_method_one, :other_method_two], :method_two]
# [{ :methodOne => :method_one, :methodTwo => :method_two }]
# [{ :methodOne => [:method_one, :other_method_one, :other_method_two], :methodTwo => :method_two }]
# [{ :methodOne => [:method_one, { :otherMethodOne => :other_method_one }], :methodTwo => :method_two }]
module ToHash
def self.eval_object(object, attributes)
if object.kind_of?(Array)
object.map { |o| eval_attributes(o, attributes) }
else
eval_attributes(object, attributes)
end
end
def self.eval_attributes(object, attributes)
result = {}
attributes = attributes.first if attributes.first.kind_of?(Hash)
case attributes
when Array
attributes.each do |attribute|
if attribute.kind_of?(Array)
result[attribute.first] = eval_object(object.send(attribute.first), attribute[1..-1])
else
result[attribute] = object.send(attribute)
end
end
when Hash
attributes.each do |key, attribute|
if attribute.kind_of?(Array)
result[key] = eval_object(object.send(attribute.first), attribute[1..-1])
else
result[key] = object.send(attribute)
end
end
end
result
end
def to_hash(*attributes)
ToHash.eval_attributes(self, attributes)
end
end
require "ostruct"
project1 = OpenStruct.new(:title => "Project 1")
project2 = OpenStruct.new(:title => "Project 2")
project3 = OpenStruct.new(:title => "Project 3")
project1.authors = []
project1.authors << OpenStruct.new(:first_name => "John", :last_name => "Doe", :projects => [project1])
project1.authors << OpenStruct.new(:first_name => "Michael", :last_name => "Smith", :projects => [project1, project2])
project1.authors << OpenStruct.new(:first_name => "Jimmy", :last_name => "Parker", :projects => [project1, project2, project3])
project1.company = OpenStruct.new(:name => "HAL")
project1.extend(ToHash)
project1.to_hash(:title, [:authors, { :firstName => :first_name, :lastName => :last_name, :assignedProjects => [:projects, :title] }], [:company, :name])
#=> {:title=>"Project 1", :authors=>[{:firstName=>"John", :lastName=>"Doe", :assignedProjects=>[{:title=>"Project 1"}]}, {:firstName=>"Michael", :lastName=>"Smith", :assignedProjects=>[{:title=>"Project 1"}, {:title=>"Project 2"}]}, {:firstName=>"Jimmy", :lastName=>"Parker", :assignedProjects=>[{:title=>"Project 1"}, {:title=>"Project 2"}, {:title=>"Project 3"}]}], :company=>{:name=>"HAL"}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment