Sha256: 8d475a8ba1f717f21aab81e7dea906179836363666adcbf36e47380e8a38e40c

Contents?: true

Size: 955 Bytes

Versions: 1

Compression:

Stored size: 955 Bytes

Contents

require 'mash'

class ScopedHash < Mash
  DEFAULT_LEFT_BRACKET = '('
  DEFAULT_RIGHT_BRACKET = ')'

  def initialize(args = {})
    super args

    @lbracket = DEFAULT_LEFT_BRACKET
    @rbracket = DEFAULT_RIGHT_BRACKET
  end

  def scope(scope)
    mash = self.clone()
    visit_scope(mash, scope)
    return mash
  end

  def set_bracket(bracket)
    if bracket.length != 2
      raise "Bracket length should be 2"
    end
    @lbracket = bracket[0]
    @rbracket = bracket[1]
  end

  private

  def visit_scope(mash, scope)
    scope_length = scope.length + 2
    scope_keys = []

    mash.each_key do |k|
      if k.end_with? "#{@lbracket}#{scope}#{@rbracket}"
        scope_keys << k
      end
    end

    scope_keys.each do |k|
      last_index = k.length - 1 - scope_length
      key = k[0..last_index]
      mash[key] = mash[k]
    end

    mash.each_pair do |k,v|
      if v.is_a?(Mash)
        visit_scope(v, scope)
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
scoped_hash-0.1.0 lib/scoped_hash.rb