qoobaa / to_hash

ToHash module for easy data serialization (using JSON, XML, etc.)

This URL has Read+Write access

name age message
file .document Wed May 13 03:17:06 -0700 2009 new gem using jeweler [Jakub]
file .gitignore Wed May 13 03:17:06 -0700 2009 new gem using jeweler [Jakub]
file LICENSE Wed May 13 03:17:06 -0700 2009 new gem using jeweler [Jakub]
file README.rdoc Sun May 10 12:43:29 -0700 2009 added more tests and more clear example [Jakub Kuźma]
file Rakefile Wed May 13 03:17:06 -0700 2009 new gem using jeweler [Jakub]
file VERSION Wed May 13 03:17:06 -0700 2009 new gem using jeweler [Jakub]
directory lib/ Sun May 10 08:02:17 -0700 2009 initial commit [Jakub Kuźma]
directory test/ Wed May 13 03:17:06 -0700 2009 new gem using jeweler [Jakub]
file to_hash.gemspec Wed May 13 03:17:28 -0700 2009 created gemspec [Jakub]
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