qoobaa / to_hash
- Source
- Commits
- Network (1)
- Issues (0)
- Downloads (0)
- Wiki (1)
- Graphs
-
Branch:
master
Jakub (author)
Wed May 13 03:17:28 -0700 2009
to_hash /
| name | age | message | |
|---|---|---|---|
| |
.document | Wed May 13 03:17:06 -0700 2009 | |
| |
.gitignore | Wed May 13 03:17:06 -0700 2009 | |
| |
LICENSE | Wed May 13 03:17:06 -0700 2009 | |
| |
README.rdoc | Sun May 10 12:43:29 -0700 2009 | |
| |
Rakefile | Wed May 13 03:17:06 -0700 2009 | |
| |
VERSION | Wed May 13 03:17:06 -0700 2009 | |
| |
lib/ | Sun May 10 08:02:17 -0700 2009 | |
| |
test/ | Wed May 13 03:17:06 -0700 2009 | |
| |
to_hash.gemspec | Wed May 13 03:17:28 -0700 2009 |
README.rdoc
to_hash
Easy and powerful object to hash serialization tool. It may be used together with to_json/to_xml/to_yaml methods.
Usage
Take a look at the example below:
class Category < ActiveRecord::Base
def name
#...
end
end
class Comment < ActiveRecord::Base
def author_name
#...
end
end
class Post < ActiveRecord::Base
has_one :category
has_many :comments
include ToHash
def title
#...
end
def body
#...
end
end
# simple serialization
Post.first.to_hash(:title, :body)
#=> { :title => "Post Title", :body => "Post body" }
# serialization with key changing
Post.first.to_hash(:title => :title, :content => :body)
#=> { :title => "Post Title", :content => "Post body" }
# simple serialization of nested objects
Post.first.to_hash(:title, [:category, :name])
#=> { :title => "Post Title", :category => { :name => "Category Name" } }
# serialization of nested objects with key changing
Post.first.to_hash(:title, [:category, { :categoryName => :name }])
#=> { :title => "Post Title", :category => { :categoryName => "Category Name" } }
# serialization of nested arrays
Post.first.to_hash(:title, [:comments, { :author => :author_name }])
#=> { :title => "Post Title", :comments => [{ :author => "John Doe" }, { :author => "Jim Smith" }] }
# creating JSON
Post.first.to_hash(:t => :title, :b => :body).to_json
#=> "{\"t\": \"Post Title\", \"b\": \"Post body\"}"
- ToHash module doesn’t require the class to inherit from ActiveRecord::Base - it can be used with any other classes as well.
License
Copyright © 2009 Jakub Kuźma, released under the MIT license
