Bye Bye Moore

PoCソルジャーな零細事業主が作業メモを残すブログ

hashieでHash型を便利に拡張する(その3_Clashでメソッドチェイン風にデータ入力)

Clashはメソッドチェインでハッシュを生成できるという、素敵拡張です。

Clash is a Chainable Lazy Hash that allows you to easily construct complex hashes using method notation chaining.

つかいかた

基本

c = Hashie::Clash.new

c.where( abc: :aiu, def: :eo).date(Time.now.to_s)
#=> {:where=>{:abc=>:aiu, :def=>:eo}, :date=>"2014-10-25 22:21:34 +0900"}

同名Key内に複数の要素を

同名Key内に複数の要素を突っ込みたい場合は、次のようにします。

c = Hashie::Clash.new
=> {}

c.where(abc: 'bef').where( fuga: :piyo)
#=> {:where=>{:abc=>"bef", :fuga=>:piyo}}

##または
c.where!.abc(123).fuga(:hoge).adding(:yeah!)._end!
=> {:where=>{:abc=>123, :fuga=>:hoge, :adding=>:yeah!}}

後者はちょいと妙な記法なので注意が必要です。

参考もと

-
intridea/hashie · GitHub