Back to Blog

Get in Touch

Hashie Gains a Chainable Hash

By Michael Bleigh March 5, 2010 in ruby, update, open-source, hashie

Missing

Hashie, Intridea’s Hash Toolkit, is today with version 0.2.0 gaining a new member: the Clash.

A Clash is a “Chainable Lazy Hash” that allows you to construct a hash using method syntax. It is meant to be used in a similar way to the way that Rails 2.x’s named_scope or Arel’s query building work. Let’s start with an example:

require 'hashie/clash'

c = Hashie::Clash.new
c.where(:abc => 'def').order(:created_at)

c == {:where => {:abc => 'def'}, :order => :created_at}

Pretty neat, right? But you can go beyond that. Clash also allows you to use bang method notation to create, dive into, and return from sub-hashes. Let me show you what I mean:

c = Hashie::Clash.new
c.where!.abc('def').ghi(123)._end!.order(:created_at)

c == {:where => {:abc => 'def', :ghi => 123}, :order => :created_at}

By using a bang method, you automatically create a subhash that is then the subject of the chain, allowing you to create more keys on that subhash. Then, if you want to jump back up to the top-level hash, you simply call the _end! method to return up one level in the stack (thanks to jQuery for that particular inspiration).

While Clash is a very simple tool, we hope that it could eventually make its way into some of the new ORMs that are cropping up around NoSQL systems (such as MongoMapper) to provide the same kind of effortless chaining that has made ActiveRecord so easy to work with.

Medium

Michael Bleigh

Michael has been with Intridea since 2007 and works to build Intridea's portfolio of products. With many years of experience working as both a designer and a developer, Michael specializes in helping to bridge the gap between the back-end development and the front-end design of a project. Michael is a prolific member of the Ruby on Rails community, having released popular open source libraries such as OmniAuth and spoken at conferences including RailsConf and RubyConf.

More from our blog

Intridea Gets a New Look

Read Now →
X

More posts by Michael Bleigh

Michael Bleigh

To the troubling idea isn't about what signal you're sending to your employee...

Michael Bleigh

Node.js has a pattern that I personally enjoy: if you require a directory, it...

Michael Bleigh

Last weekend I had the opportunity to speak at RubyConf 2012 about a topic th...