Hash and Objects
It’s a common task to simulate objects from hashes, but one has to remember using hash access format in order to access it. Hashi helps you by allowing direct access to its content:
hash = { :team => {:players => [{:name=>"guilherme silveira"},{:name=>"jose donizetti"}]}}
object = Hashi.to_object(hash)
puts object.team.players[0].name
Why would I use Hashi?
The reality without Hashi
hash = { :team => {:players => [{:name=>"guilherme silveira"},{:name=>"jose donizetti"}]}}
puts hash[:team][:players][0][:name] # his name
Although the Ruby language provides an easy way to access hashes, it becomes easier if you use Rails and has created an ActiveRecord for your representation:
The reality without Hashi, within Rails
class Team < ActiveRecord::Base
has_many :players
end
class Player < ActiveRecord::Base
# create a migration with field name:string
end
hash = { :team => {:players => [{:name=>"guilherme silveira"},{:name=>"jose donizetti"}]}}
puts hash[:player][0][:name] # his name
How does it compare to Hashie?
Hashi actually does not create your attributes, instead it deals with method_missing invocations to simulate those properties, never creating a copy of your hash.
More info
You can access the original hash (updated if you have made any changes) by one of those two ways:
hash = { :team => {:players => [{:name=>"guilherme silveira"},{:name=>"jose donizetti"}]}}
object = Hashi.to_object(hash)
object.team.players[0].name = 'jose donizetti'
# the original hash was modified!
puts hash
# you can extract the original hash if you wish
puts object.hash
Installing
Ruby
gem install gemcutter gem tumble gem install hashi
Rails
Just add in your environment.rb the following line:
config.gem "hashi", :source => "http://gemcutter.org"
And then execute:
rake gems:install
or, if you prefer to install it as a plugin:
script/plugin install git://github.com/caelum/hashi.git
Help
If you are looking for or want to help, let us know at the mailing list:
http://groups.google.com/group/hashi-ruby
Team
Hashi was created and is maintained within Caelum:http://www.caelum.com.br by
Projetct Founder
- Guilherme Silveira – twitter:http://www.twitter.com/guilhermecaelum http://guilhermesilveira.wordpress.com
Active Commiters
- Guilherme Silveira
- Jose Donizetti
Sources
You can see its source code at: github
License
/*
- Copyright © 2009 Caelum – www.caelum.com.br/opensource
- All rights reserved. *
- Licensed under the Apache License, Version 2.0 (the “License”);
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at *
- http://www.apache.org/licenses/LICENSE-2.0 *
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an “AS IS” BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License. */