シンプルなERBのヘルパー ERBh を作った

シンプルなERBのヘルパー ERBh を作った…というか、先日作ったrspec-match_fuzzyから分離・独立させた。

github.com

以下のように、1メソッドで変数の定義とEBBの評価が行える。

require 'erbh'
include ERBh

erbh('<%= @foo %>, <%= @bar %>', foo: 100, bar: 'zoo')
#=> "100, zoo"

trim modeも使える。

erbh(<<-EOS, {foo: 1..3}, trim_mode: '-')
<%- @foo.each do |i| -%>
<%= i %>
<%- end -%>
EOS
#=> "1\n2\n3\n"

Hashのエントリの順序を操作するhash_order_helperを作った

Hashのエントリの順序を破壊的に更新したいということが希によくあるので、エントリの順序をArrayのように操作できるメソッドを追加するhash_order_helperを作った。

github.com

以下のような感じで、Hashのエントリの順序を操作できる。

require 'hash_order_helper'

hash = {b: 200, a: 100, c: 150}

hash.sort_pair
#=> {:a=>100, :b=>200, :c=>150}

hash.unshift(d: 300)
#=> {:d=>300, :b=>200, :a=>100, :c=>150}

追加されるメソッドは以下の通り。

  • sort_pair -> Hash
  • sort_pair! -> Hash
  • sort_pair_by {|key, value| ... } -> Hash
  • sort_pair_by! {|key, value| ... } -> Hash
  • at(nth) -> Array
  • insert(nth, hash) -> Hash
  • last -> Array
  • last(n) -> Array
  • pop -> Array
  • pop(n) -> Array
  • push(key, hash) -> Hash
  • unshift(key, hash) -> Hash