Sha256: b1fcb9ba73cdedcb72462a5ea257d9511e69bf52195416f040f47837876bccb3

Contents?: true

Size: 1.78 KB

Versions: 9

Compression:

Stored size: 1.78 KB

Contents

require "render/extensions/symbolizable_hash"
require "render/extensions/symbolizable_array"

module Render
  module Extensions
    class DottableHash < SymbolizableHash
      class << self
        def new(element_to_hash = {})
          symbolize_hash = SymbolizableHash.new.merge!(element_to_hash)
          symbolize_hash.symbolize_keys!
          hash = super().merge!(symbolize_hash)

          hash.each do |key, value|
            hash[key] = initialize_element(value)
          end

          hash
        end

        def initialize_element(value)
          case value
          when Hash
            new(value)
          when Array
            values = value.collect do |v|
              initialize_element(v)
            end
            SymbolizableArray.new(values)
          else
            value
          end
        end
      end

      def []=(key, value)
        key = key.to_sym
        value = self.class.initialize_element(value)
        super
      end

      def [](key)
        key = key.to_sym
        super
      end

      def delete(key)
        key = key.to_sym
        super
      end

      def has_key?(key)
        super(key.to_sym)
      end

      def merge!(other_hash)
        other_hash = SymbolizableHash.new().merge!(other_hash)
        super(other_hash.recursively_symbolize_keys!)
      end

      def merge(other_hash)
        other_hash = SymbolizableHash.new().merge!(other_hash)
        super(other_hash.recursively_symbolize_keys!)
      end

      def method_missing(method, *arguments)
        if method.match(/\=$/)
          self[method.to_s.chop] = arguments.first
        elsif has_key?(method)
          self[method]
        else
          super
        end
      end

      def fetch(key, *args)
        key = key.to_sym
        super
      end

    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
render-0.1.3 lib/render/extensions/dottable_hash.rb
render-0.1.2 lib/render/extensions/dottable_hash.rb
render-0.1.1 lib/render/extensions/dottable_hash.rb
render-0.1.0 lib/render/extensions/dottable_hash.rb
render-0.0.9 lib/render/extensions/dottable_hash.rb
render-0.0.8 lib/render/extensions/dottable_hash.rb
render-0.0.7 lib/render/extensions/dottable_hash.rb
render-0.0.6 lib/render/extensions/dottable_hash.rb
render-0.0.5 lib/render/extensions/dottable_hash.rb