Sha256: 8c006175f2e43334da865b812b0be76a72ef4fedc6bd649dc1b7dbe53cfe004d

Contents?: true

Size: 948 Bytes

Versions: 3

Compression:

Stored size: 948 Bytes

Contents

require 'delegate'

module Leadlight
  def ParamHash(hash)
    case hash
    when ParamHash then hash
    else ParamHash.new(hash)
    end
  end
  module_function :ParamHash

  class ParamHash < DelegateClass(Hash)
    def initialize(hash)
      super(transform_hash(Hash[hash], :deep => true) {|h,k,v|
              h[k] = transform_value(v)
            })
    end

    private

    def transform_hash(original, options={}, &block)
      original.inject({}){|result, (key,value)|
        value = if (options[:deep] && Hash === value)
                  transform_hash(value, options, &block)
                else
                  value
                end
        block.call(result,key,value)
        result
      }
    end

    def transform_value(value)
      case value
      when ParamHash then value
      when Hash      then self.class.new(value)
      when Array     then value.map(&:to_s)
      else value.to_s
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
leadlight-0.1.0 lib/leadlight/param_hash.rb
leadlight-0.0.7 lib/leadlight/param_hash.rb
leadlight-0.0.6 lib/leadlight/param_hash.rb