Class: Heroics::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/heroics/client.rb

Overview

An HTTP client with methods mapped to API resources.

Instance Method Summary collapse

Constructor Details

#initialize(resources, url) ⇒ Client

Instantiate an HTTP client.

Parameters:

  • resources (Hash<String,Resource>)

    A hash that maps method names to resources.

  • url (String)

    The URL used by this client.



10
11
12
13
14
# File 'lib/heroics/client.rb', line 10

def initialize(resources, url)
  # Transform resource keys via the ruby_name replacement semantics
  @resources = Hash[resources.map{ |k, v| [Heroics.ruby_name(k), v] }]
  @url = url
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name) ⇒ Resource

Find a resource.

Parameters:

  • name (String)

    The name of the resource to find.

Returns:

  • (Resource)

    The resource matching the name.

Raises:

  • (NoMethodError)

    Raised if the name doesn’t match a known resource.



21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/heroics/client.rb', line 21

def method_missing(name)
  name = name.to_s
  resource = @resources[name]
  if resource.nil?
    # Find the name using the same ruby_name replacement semantics as when
    # we set up the @resources hash
    name = Heroics.ruby_name(name)
    resource = @resources[name]
    if resource.nil?
      raise NoMethodError.new("undefined method `#{name}' for #{to_s}")
    end
  end
  resource
end

Instance Method Details

#inspectObject Also known as: to_s

Get a simple human-readable representation of this client instance.



37
38
39
40
41
42
43
# File 'lib/heroics/client.rb', line 37

def inspect
  url = URI.parse(@url)
  unless url.password.nil?
    url.password = 'REDACTED'
  end
  "#<Heroics::Client url=\"#{url.to_s}\">"
end