module Excon::HyperMedia::Collection

Collection

Given a `Hash`, provides dot-notation properties and other helper methods.

Attributes

collection[R]

Public Class Methods

new(collection = {}) click to toggle source
# File lib/excon/hypermedia/helpers/collection.rb, line 14
def initialize(collection = {})
  @collection ||= collection.to_h
  to_properties
end

Public Instance Methods

[](key) click to toggle source
# File lib/excon/hypermedia/helpers/collection.rb, line 31
def [](key)
  to_property(key)
end
each(&block) click to toggle source
# File lib/excon/hypermedia/helpers/collection.rb, line 19
def each(&block)
  collection.each(&block)
end
key?(key) click to toggle source
# File lib/excon/hypermedia/helpers/collection.rb, line 27
def key?(key)
  collection.key?(key.to_s)
end
keys() click to toggle source
# File lib/excon/hypermedia/helpers/collection.rb, line 23
def keys
  @collection.keys
end

Private Instance Methods

method_missing(_) click to toggle source

method_missing

Collections can be accessed using both the “dot notation” and the hash notation:

collection.hello_world
collection['hello_world']

The second notation returns `nil` on missing keys, the first should do as well.

# File lib/excon/hypermedia/helpers/collection.rb, line 48
def method_missing(_) # rubocop:disable Style/MethodMissing
  nil
end
property(value) click to toggle source
# File lib/excon/hypermedia/helpers/collection.rb, line 73
def property(value)
  value.respond_to?(:keys) ? self.class.new(value) : value
end
respond_to_missing?(_, _ = false) click to toggle source

respond_to_missing?

Checking if a key exists should be possible using `respond_to?`:

collection.respond_to?(:hello_world)
# => false
Calls superclass method
# File lib/excon/hypermedia/helpers/collection.rb, line 59
def respond_to_missing?(_, _ = false)
  super
end
to_properties() click to toggle source
# File lib/excon/hypermedia/helpers/collection.rb, line 63
def to_properties
  collection.each do |key, value|
    key = key.downcase
    next unless /[@$"]/ !~ key.to_sym.inspect

    singleton_class.class_eval { attr_reader key }
    instance_variable_set("@#{key}", property(value))
  end
end
to_property(key) click to toggle source
# File lib/excon/hypermedia/helpers/collection.rb, line 77
def to_property(key)
  key?(key) ? property(collection[key]) : nil
end
to_property!(key) click to toggle source
# File lib/excon/hypermedia/helpers/collection.rb, line 81
def to_property!(key)
  key?(key) ? to_property(key) : method_missing(key)
end