Class: RegApi2::SymHash

Inherits:
Hash
  • Object
show all
Defined in:
lib/reg_api2/sym_hash.rb

Overview

Hash with indifferent access to its elements. Also have no difference between String ans Symbol keys.

See Also:

Class Method Summary collapse

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(key, *args, &block) ⇒ Object

Sets or gets field in the hash.



52
53
54
55
56
57
58
59
60
61
62
# File 'lib/reg_api2/sym_hash.rb', line 52

def method_missing(key, *args, &block)
  if key.to_s =~ /\A(.+)=\z/
    self[$1] = args.first
    return args.first
  end
  if key.to_s =~ /\A(.+)\?\z/
    return !!self[$1]
  end
  return self[key]  if has_key?(key)
  nil
end

Class Method Details

.from(source) ⇒ Object

Forms data with indifferent access from specified source.

Returns:

  • (Object)

    Data with indifferent access



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/reg_api2/sym_hash.rb', line 9

def self.from(source)
  case source
  when Hash
    res = SymHash.new
    source.each_pair do |key, value|
      res[key] = self.from(value)
    end
    res
  when Array
    source.map do |el|
      self.from(el)
    end
  else
    source
  end
end

Instance Method Details

#[](key) ⇒ Object

Element Reference — Retrieves the value object corresponding to the key object. If not found, returns the default value (see Hash::new for details).



37
38
39
# File 'lib/reg_api2/sym_hash.rb', line 37

def [](key)
  key.kind_of?(Symbol) ? self[key.to_s] : super(key)
end

#[]=(key, new_value) ⇒ Object

Element Assignment — Associates the value given by value with the key given by key. key should not have its value changed while it is in use as a key (a String passed as a key will be duplicated and frozen).



42
43
44
# File 'lib/reg_api2/sym_hash.rb', line 42

def []=(key, new_value)
  key.kind_of?(Symbol) ? self[key.to_s]=new_value : super(key, new_value)
end

#has_key?(key) ⇒ Boolean

Returns true if the given key is present in hsh.

Returns:

  • (Boolean)


27
28
29
# File 'lib/reg_api2/sym_hash.rb', line 27

def has_key?(key)
  key.kind_of?(Symbol) ? self.has_key?(key.to_s) : super(key)
end

#include?(key) ⇒ Boolean

Returns true if the given key is present in hsh.

Returns:

  • (Boolean)


32
33
34
# File 'lib/reg_api2/sym_hash.rb', line 32

def include?(key)
  has_key?(key)
end

#respond_to?(key) ⇒ Boolean

Always true

Returns:

  • (Boolean)


47
48
49
# File 'lib/reg_api2/sym_hash.rb', line 47

def respond_to?(key)
  true
end