Sha256: 8f41c085b2694521e785669a8619a3866b61b15276387a261f9875f3d8e8a8be

Contents?: true

Size: 903 Bytes

Versions: 4

Compression:

Stored size: 903 Bytes

Contents

require 'set'

module ActiveSupport #:nodoc:
  module CoreExtensions #:nodoc:
    module Hash #:nodoc:
      # Slice a hash to include only the given keys. This is useful for
      # limiting an options hash to valid keys before passing to a method:
      #
      #   def search(criteria = {})
      #     assert_valid_keys(:mass, :velocity, :time)
      #   end
      #
      #   search(options.slice(:mass, :velocity, :time))
      module Slice
        # Returns a new hash with only the given keys.
        def slice(*keys)
          allowed = Set.new(respond_to?(:convert_key) ? keys.map { |key| convert_key(key) } : keys)
          hash = self.class.new
          allowed.each { |k| hash[k] = self[k] if has_key?(k) }
          hash
        end

        # Replaces the hash with only the given keys.
        def slice!(*keys)
          replace(slice(*keys))
        end
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 2 rubygems

Version Path
radiant-0.7.2 vendor/rails/activesupport/lib/active_support/core_ext/hash/slice.rb
activesupport-2.1.2 lib/active_support/core_ext/hash/slice.rb
radiant-0.7.0 vendor/rails/activesupport/lib/active_support/core_ext/hash/slice.rb
radiant-0.7.1 vendor/rails/activesupport/lib/active_support/core_ext/hash/slice.rb