Class: MasterView::CaseInsensitiveHash
- Inherits:
-
Hash
- Object
- Hash
- MasterView::CaseInsensitiveHash
- Defined in:
- lib/masterview/case_insensitive_hash.rb
Overview
Extends Hash to allow case insensitive access to data using any case string or symbol, however it retains the original case when iterated on. When updating a value it first checks for the existence of a case indendependent key and if found uses that for storage key, thus the first form to store determines the case.
Instance Method Summary collapse
-
#[](key) ⇒ Object
uses a lowercased symbol to find original key which is then used to find value.
-
#[]=(key, value) ⇒ Object
(also: #store)
put value into map first checking if there is already an entry using lowercased symbol, if so use it (it determines key case), otherwise add new entry.
-
#get_lowercase_str_value(key) ⇒ Object
retrieves the lowercased string value for the key.
-
#initialize ⇒ CaseInsensitiveHash
constructor
A new instance of CaseInsensitiveHash.
-
#replace(hash) ⇒ Object
build hash from another hash.
Constructor Details
#initialize ⇒ CaseInsensitiveHash
Returns a new instance of CaseInsensitiveHash.
7 8 9 10 |
# File 'lib/masterview/case_insensitive_hash.rb', line 7 def initialize super init_lcks_map end |
Instance Method Details
#[](key) ⇒ Object
uses a lowercased symbol to find original key which is then used to find value
13 14 15 16 |
# File 'lib/masterview/case_insensitive_hash.rb', line 13 def [](key) original_key = @lcks_to_original_key[convert_to_lcs(key)] (original_key.nil?) ? nil : super(original_key) end |
#[]=(key, value) ⇒ Object Also known as: store
put value into map first checking if there is already an entry using lowercased symbol, if so use it (it determines key case), otherwise add new entry
20 21 22 23 24 25 26 27 28 |
# File 'lib/masterview/case_insensitive_hash.rb', line 20 def []=(key, value) lcks = convert_to_lcs(key) original_key = @lcks_to_original_key[lcks] if original_key.nil? # not found so create new original key in map @lcks_to_original_key[lcks] = key original_key = key end super(original_key, value) end |
#get_lowercase_str_value(key) ⇒ Object
retrieves the lowercased string value for the key
42 43 44 45 46 47 48 49 50 51 52 53 54 |
# File 'lib/masterview/case_insensitive_hash.rb', line 42 def get_lowercase_str_value(key) value = self[key] unless value.nil? if value.is_a? String value.downcase! elsif value.is_a? Symbol value = value.to_s.downcase else value = value.inspect.downcase end end value end |
#replace(hash) ⇒ Object
build hash from another hash
33 34 35 36 37 38 39 |
# File 'lib/masterview/case_insensitive_hash.rb', line 33 def replace(hash) super(hash) init_lcks_map hash.each do |k,v| @lcks_to_original_key[convert_to_lcs(k)] = k end end |