Sha256: 31aef7b6b659e591c5d2c5fbcec24ad82aafa20bc6a0d7b18193078513be0938

Contents?: true

Size: 1.69 KB

Versions: 19

Compression:

Stored size: 1.69 KB

Contents

module PollEverywhere
  module CoreExt #:nodoc:

    # A hash with indifferent access and magic predicates.
    #
    #   hash = Thor::CoreExt::HashWithIndifferentAccess.new 'foo' => 'bar', 'baz' => 'bee', 'force' => true
    #
    #   hash[:foo]  #=> 'bar'
    #   hash['foo'] #=> 'bar'
    #   hash.foo?   #=> true
    #
    class HashWithIndifferentAccess < ::Hash #:nodoc:
      def initialize(hash={})
        super()
        hash.each do |key, value|
          self[convert_key(key)] = value
        end
      end

      def [](key)
        super(convert_key(key))
      end

      def []=(key, value)
        super(convert_key(key), value)
      end

      def delete(key)
        super(convert_key(key))
      end

      def values_at(*indices)
        indices.collect { |key| self[convert_key(key)] }
      end

      def merge(other)
        dup.merge!(other)
      end

      def merge!(other)
        other.each do |key, value|
          self[convert_key(key)] = value
        end
        self
      end

      protected

        def convert_key(key)
          key.is_a?(Symbol) ? key.to_s : key
        end

        # Magic predicates. For instance:
        #
        #   options.force?                  # => !!options['force']
        #   options.shebang                 # => "/usr/lib/local/ruby"
        #   options.test_framework?(:rspec) # => options[:test_framework] == :rspec
        #
        def method_missing(method, *args, &block)
          method = method.to_s
          if method =~ /^(\w+)\?$/
            if args.empty?
              !!self[$1]
            else
              self[$1] == args.first
            end
          else
            self[method]
          end
        end

    end
  end
end

Version data entries

19 entries across 19 versions & 1 rubygems

Version Path
polleverywhere-0.0.21 lib/polleverywhere/core_ext.rb
polleverywhere-0.0.20 lib/polleverywhere/core_ext.rb
polleverywhere-0.0.19 lib/polleverywhere/core_ext.rb
polleverywhere-0.0.18 lib/polleverywhere/core_ext.rb
polleverywhere-0.0.17 lib/polleverywhere/core_ext.rb
polleverywhere-0.0.16 lib/polleverywhere/core_ext.rb
polleverywhere-0.0.15 lib/polleverywhere/core_ext.rb
polleverywhere-0.0.14 lib/polleverywhere/core_ext.rb
polleverywhere-0.0.13 lib/polleverywhere/core_ext.rb
polleverywhere-0.0.12 lib/polleverywhere/core_ext.rb
polleverywhere-0.0.11 lib/polleverywhere/core_ext.rb
polleverywhere-0.0.10 lib/polleverywhere/core_ext.rb
polleverywhere-0.0.9 lib/polleverywhere/core_ext.rb
polleverywhere-0.0.8 lib/polleverywhere/core_ext.rb
polleverywhere-0.0.7 lib/polleverywhere/core_ext.rb
polleverywhere-0.0.6 lib/polleverywhere/core_ext.rb
polleverywhere-0.0.5 lib/polleverywhere/core_ext.rb
polleverywhere-0.0.4 lib/polleverywhere/core_ext.rb
polleverywhere-0.0.2 lib/polleverywhere/core_ext.rb