Class: Hanko::Resource

Inherits:
Object
  • Object
show all
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.

Examples:

resource = Hanko::Resource.new("id" => "abc", "email" => "[email protected]")
resource.id    #=> "abc"
resource[:email] #=> "[email protected]"

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes = {}) ⇒ Resource

Creates a new Resource from a hash of attributes.

Parameters:

  • attributes (Hash) (defaults to: {})

    the raw attribute hash



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.

Parameters:

  • array (Array<Hash>)

    array of attribute hashes

Returns:



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).

Parameters:

  • key (String, Symbol)

    the attribute name

Returns:

  • (Object, nil)

    the attribute value



24
25
26
# File 'lib/hanko/resource.rb', line 24

def [](key)
  @attributes[key.to_s]
end

#inspectString

Returns a human-readable representation of the resource.

Returns:

  • (String)


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.

Parameters:

  • _method_name (Symbol)
  • _include_private (Boolean) (defaults to: false)

Returns:

  • (Boolean)


57
58
59
# File 'lib/hanko/resource.rb', line 57

def respond_to_missing?(_method_name, _include_private = false)
  true
end

#to_hHash

Converts the resource (and any nested resources) to a plain Hash.

Returns:

  • (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