Class: TocDoc::Resource
- Inherits:
-
Object
- Object
- TocDoc::Resource
- Defined in:
- lib/toc_doc/models/resource.rb
Overview
A lightweight wrapper providing dot-notation access to response fields. Backed by a Hash, with +method_missing+ for attribute access and +#to_h+ for round-tripping back to a plain Hash.
Unlike Sawyer, TocDoc does not use hypermedia relations, so this wrapper intentionally stays minimal.
Direct Known Subclasses
Instance Method Summary collapse
-
#==(other) ⇒ Boolean
Equality comparison.
-
#[](key) ⇒ Object?
Read an attribute by name.
-
#[]=(key, value) ⇒ Object
Write an attribute by name.
-
#initialize(attrs = {}) ⇒ Resource
constructor
A new instance of Resource.
-
#method_missing(method_name, *_args) ⇒ Object
Provides dot-notation access to response fields.
-
#to_h ⇒ Hash{String => Object}
Return a plain Hash representation (shallow copy).
Constructor Details
#initialize(attrs = {}) ⇒ Resource
Returns a new instance of Resource.
18 19 20 |
# File 'lib/toc_doc/models/resource.rb', line 18 def initialize(attrs = {}) @attrs = attrs.transform_keys(&:to_s) end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(method_name, *_args) ⇒ Object
Provides dot-notation access to response fields.
Any method call whose name matches a key in the underlying attribute hash is dispatched here.
77 78 79 80 |
# File 'lib/toc_doc/models/resource.rb', line 77 def method_missing(method_name, *_args) key = method_name.to_s @attrs.key?(key) ? @attrs[key] : super end |
Instance Method Details
#==(other) ⇒ Boolean
Equality comparison.
Two TocDoc::Resource instances are equal when their attribute hashes match. A TocDoc::Resource is also equal to a plain +Hash+ with equivalent keys.
56 57 58 59 60 61 62 |
# File 'lib/toc_doc/models/resource.rb', line 56 def ==(other) case other when Resource then @attrs == other.to_h when Hash then @attrs == other.transform_keys(&:to_s) else false end end |
#[](key) ⇒ Object?
Read an attribute by name.
29 30 31 |
# File 'lib/toc_doc/models/resource.rb', line 29 def [](key) @attrs[key.to_s] end |
#[]=(key, value) ⇒ Object
Write an attribute by name.
38 39 40 |
# File 'lib/toc_doc/models/resource.rb', line 38 def []=(key, value) @attrs[key.to_s] = value end |
#to_h ⇒ Hash{String => Object}
Return a plain Hash representation (shallow copy).
45 46 47 |
# File 'lib/toc_doc/models/resource.rb', line 45 def to_h @attrs.dup end |