Class: Hanko::Resource
- Inherits:
-
Object
- Object
- Hanko::Resource
- Defined in:
- lib/hanko/resource.rb
Overview
Lightweight wrapper around a Hash that provides dot-notation access.
Nested hashes are automatically wrapped in their own Resource instances.
Class Method Summary collapse
-
.from_array(array) ⇒ Array<Resource>
Builds an array of Resource instances from an array of hashes.
Instance Method Summary collapse
-
#[](key) ⇒ Object?
Retrieves an attribute by key (string or symbol).
-
#initialize(attributes = {}) ⇒ Resource
constructor
Creates a new Resource from a hash of attributes.
-
#inspect ⇒ String
Returns a human-readable representation of the resource.
-
#respond_to_missing?(_method_name, _include_private = false) ⇒ Boolean
Returns true for all method names, enabling dynamic attribute access.
-
#to_h ⇒ Hash
Converts the resource (and any nested resources) to a plain Hash.
Constructor Details
#initialize(attributes = {}) ⇒ Resource
Creates a new Resource from a hash of attributes.
16 17 18 |
# File 'lib/hanko/resource.rb', line 16 def initialize(attributes = {}) @attributes = normalize(attributes) end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(method_name, *args) ⇒ Object (private)
63 64 65 66 67 68 69 |
# File 'lib/hanko/resource.rb', line 63 def method_missing(method_name, *args) if args.empty? && !block_given? self[method_name] else super end end |
Class Method Details
.from_array(array) ⇒ Array<Resource>
Builds an array of Resource instances from an array of hashes.
48 49 50 |
# File 'lib/hanko/resource.rb', line 48 def self.from_array(array) array.map { |attrs| new(attrs) } end |
Instance Method Details
#[](key) ⇒ Object?
Retrieves an attribute by key (string or symbol).
24 25 26 |
# File 'lib/hanko/resource.rb', line 24 def [](key) @attributes[key.to_s] end |
#inspect ⇒ String
Returns a human-readable representation of the resource.
40 41 42 |
# File 'lib/hanko/resource.rb', line 40 def inspect "#<#{self.class} #{@attributes.inspect}>" end |
#respond_to_missing?(_method_name, _include_private = false) ⇒ Boolean
Returns true for all method names, enabling dynamic attribute access.
57 58 59 |
# File 'lib/hanko/resource.rb', line 57 def respond_to_missing?(_method_name, _include_private = false) true end |
#to_h ⇒ Hash
Converts the resource (and any nested resources) to a plain Hash.
31 32 33 34 35 |
# File 'lib/hanko/resource.rb', line 31 def to_h @attributes.transform_values do |v| v.is_a?(Resource) ? v.to_h : v end end |