module Collapsium::IndifferentAccess

Provides indifferent access to string/symbol keys in a Hash. That is, if your hash contains a string key, you can also access it via a symbol and vice versa.

Constants

INDIFFERENT_ACCESS
METHODS

Public Class Methods

key_permutations(key) click to toggle source

Given a key, returns all indifferent permutations to try.

# File lib/collapsium/indifferent_access.rb, line 31
def key_permutations(key)
  tries = [key]
  if key.is_a? Symbol
    key_s = key.to_s
    tries << key_s
    if key_s =~ /^[0-9]/
      tries << key_s.to_i
    end
  elsif key.is_a? String
    tries << key.to_sym
    if key =~ /^[0-9]/
      tries << key.to_i
    end
  elsif key.is_a? Integer
    tries += [key.to_s, key.to_s.to_sym]
  end

  return tries
end
sorted_keys(keys, &block) click to toggle source

Sort the given keys indifferently. This will sort Integers first, Symbols second and Strings third. Everything else comes last. This is done because that's the order in which comparsion time increases.

# File lib/collapsium/indifferent_access.rb, line 63
def sorted_keys(keys, &block)
  # Sorting sucks because we can't compare Strings and Symbols. So in
  # order to get this right, we'll have to sort each type individually,
  # then concatenate the results.
  sorted = []
  [Integer, Symbol, String].each do |klass|
    sorted += keys.select { |key| key.is_a?(klass) }.sort(&block)
  end
  return sorted
end
unique_keys(keys) click to toggle source

Make the given keys unique according to the logic of this module.

# File lib/collapsium/indifferent_access.rb, line 53
def unique_keys(keys)
  # The simplest way is to stringify all keys before making them
  # unique. That works for Integer as well as Symbol.
  return keys.map(&:to_s).uniq
end

Public Instance Methods

enhance(base) click to toggle source
# File lib/collapsium/indifferent_access.rb, line 124
def enhance(base)
  # Make the capabilities of classes using IndifferentAccess viral.
  base.extend(ViralCapabilities)

  # Wrap all accessor functions to deal with paths
  METHODS.each do |method|
    wrap_method(base, method, raise_on_missing: false,
                &INDIFFERENT_ACCESS)
  end
end
extended(base) click to toggle source
# File lib/collapsium/indifferent_access.rb, line 116
def extended(base)
  enhance(base)
end
included(base) click to toggle source
# File lib/collapsium/indifferent_access.rb, line 112
def included(base)
  enhance(base)
end
prepended(base) click to toggle source
# File lib/collapsium/indifferent_access.rb, line 120
def prepended(base)
  enhance(base)
end