Sha256: e5ff9c3d895ca1e0a9e67e31031ad7d68b6e9e15616d183f68df17db9d7cf928

Contents?: true

Size: 1.08 KB

Versions: 11

Compression:

Stored size: 1.08 KB

Contents

module Hashie
  # @author Jamie Winsor <jamie@vialstudios.com>
  class Mash < Hashie::Hash
    alias_method :old_setter, :[]=
    alias_method :old_dup, :dup

    attr_writer :coercions

    # @return [Hash]
    def coercions
      @coercions ||= HashWithIndifferentAccess.new
    end

    def coercion(key)
      self.coercions[key]
    end

    def set_coercion(key, fun)
      self.coercions[key] = fun
    end

    # Override setter to coerce the given value if a coercion is defined
    def []=(key, value)
      coerced_value = coercion(key).present? ? coercion(key).call(value) : value
      old_setter(key, coerced_value)
    end

    # Return the containing Hashie::Mash of the given dotted path
    #
    # @param [String] path
    #
    # @return [Hashie::Mash, nil]
    def container(path)
      parts = path.split('.', 2)
      match = (self[parts[0].to_s] || self[parts[0].to_sym])
      if !parts[1] or match.nil?
        self
      else
        match.container(parts[1])
      end
    end

    def dup
      mash = old_dup
      mash.coercions = self.coercions
      mash
    end
  end
end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
chozo-0.6.1 lib/chozo/hashie_ext/mash.rb
chozo-0.6.0 lib/chozo/hashie_ext/mash.rb
chozo-0.5.0 lib/chozo/hashie_ext/mash.rb
chozo-0.4.2 lib/chozo/hashie_ext/mash.rb
chozo-0.4.1 lib/chozo/hashie_ext/mash.rb
chozo-0.4.0 lib/chozo/hashie_ext/mash.rb
chozo-0.3.0 lib/chozo/hashie_ext/mash.rb
chozo-0.2.3 lib/chozo/hashie_ext/mash.rb
chozo-0.2.2 lib/chozo/hashie_ext/mash.rb
chozo-0.2.1 lib/chozo/hashie_ext/mash.rb
chozo-0.2.0 lib/chozo/hashie_ext/mash.rb