Class: PropertyHash
Constant Summary collapse
- KEY_DELIMITER =
"."
- VERSION =
"0.0.1"
Instance Method Summary collapse
- #[](key) ⇒ Object
- #[]=(key, value) ⇒ Object
- #each ⇒ Object
-
#initialize(hash, use_symbols = true) ⇒ PropertyHash
constructor
A new instance of PropertyHash.
- #keys ⇒ Object
- #to_h ⇒ Object (also: #to_hash)
- #values ⇒ Object
Constructor Details
#initialize(hash, use_symbols = true) ⇒ PropertyHash
9 10 11 12 13 |
# File 'lib/property_hash.rb', line 9 def initialize(hash, use_symbols = true) @hash = hash.dup @keys = keys_as_properties(@hash) @use_symbols = use_symbols || false end |
Instance Method Details
#[](key) ⇒ Object
51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
# File 'lib/property_hash.rb', line 51 def [](key) keys = property_key(key) begin # FIXME: Does not support mixed keys v = @hash.dig(*keys) return v unless v.nil? && @use_symbols keys.map!(&:to_sym) @hash.dig(*keys) rescue TypeError # From dig. Ignore, value does not exist end end |
#[]=(key, value) ⇒ Object
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/property_hash.rb', line 34 def []=(key, value) keys = property_key(key) hash_to_set = @hash keys[0..-2].each do |key| if hash_to_set.include?(key) hash_to_set = hash_to_set[key] else hash_to_set = hash_to_set[key] = {} end end @keys << key hash_to_set[keys[-1]] = value end |
#each ⇒ Object
15 16 17 18 |
# File 'lib/property_hash.rb', line 15 def each return to_enum(:each) unless block_given? @keys.each { |key| yield([key, self[key]]) } end |
#keys ⇒ Object
20 21 22 |
# File 'lib/property_hash.rb', line 20 def keys @keys.dup end |
#to_h ⇒ Object Also known as: to_hash
28 29 30 |
# File 'lib/property_hash.rb', line 28 def to_h @hash.dup end |
#values ⇒ Object
24 25 26 |
# File 'lib/property_hash.rb', line 24 def values map(&:last) end |