Class: Inquery::MethodAccessibleHash
- Inherits:
-
Hash
- Object
- Hash
- Inquery::MethodAccessibleHash
- Defined in:
- lib/inquery/method_accessible_hash.rb
Overview
A safe alternative for OpenStruct in Ruby. It behaves exactly the same, but does not define methods on-the-fly but uses method_missing instead.
Usage example:
“‘ruby default_options = { foo: :bar } options = MethodAccessibleHash.new(default_options) options = :green options.foo # => :bar options.color # => green “`
Instance Method Summary collapse
-
#initialize(hash = {}) ⇒ MethodAccessibleHash
constructor
Takes an optional hash as argument and constructs a new MethodAccessibleHash.
- #merge(**hash) ⇒ Object
- #method_missing(method, *args, &_block) ⇒ Object
- #respond_to_missing?(_method, _include_private = false) ⇒ Boolean
Constructor Details
#initialize(hash = {}) ⇒ MethodAccessibleHash
Takes an optional hash as argument and constructs a new MethodAccessibleHash.
17 18 19 20 21 22 23 |
# File 'lib/inquery/method_accessible_hash.rb', line 17 def initialize(hash = {}) super() hash.each do |key, value| self[key.to_sym] = value end end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(method, *args, &_block) ⇒ Object
31 32 33 34 35 36 37 38 |
# File 'lib/inquery/method_accessible_hash.rb', line 31 def method_missing(method, *args, &_block) if method.to_s.end_with?('=') name = method.to_s.gsub(/=$/, '') self[name.to_sym] = args.first else self[method.to_sym] end end |
Instance Method Details
#merge(**hash) ⇒ Object
26 27 28 |
# File 'lib/inquery/method_accessible_hash.rb', line 26 def merge(**hash) super(hash.symbolize_keys) end |
#respond_to_missing?(_method, _include_private = false) ⇒ Boolean
41 42 43 |
# File 'lib/inquery/method_accessible_hash.rb', line 41 def respond_to_missing?(_method, _include_private = false) true end |