Class: ChefAPI::Proxy

Inherits:
BasicObject
Defined in:
lib/chef-api/proxy.rb

Overview

Create a proxy object, which delegates all methods to the class given in the initializer. This is used by the client object to filter the first parameter of any singleton methods to pass in the given client as the first argument. It’s dirty, but it allows developers to write pretty code, which is more what I care about.

Examples:

Without a proxy object

client = ChefAPI::Client.new('...')
repo = ChefAPI::Resource::Repository.new(client, name: '...')

With a proxy object

client = ChefAPI::Client.new('...')
repo = client.repositories.new(name: '...')

Instance Method Summary collapse

Constructor Details

#initialize(client, klass) ⇒ Proxy

Create a new proxy object.

Parameters:

  • client (ChefAPI::Client)

    the client object to use for the proxy

  • klass (Class)

    the class to proxy to



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/chef-api/proxy.rb', line 39

def initialize(client, klass)
  @client = client
  @klass  = klass

  klass.singleton_methods.each do |name|
    instance_eval <<-EOH, __FILE__, __LINE__ + 1
      def #{name}(*args)
        if args.last.is_a?(::Hash)
          args.last[:client] = @client
        else
          args << { client: @client }
        end

        @klass.send(:#{name}, *args)
      end
    EOH
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(m, *args, &block) ⇒ Object



59
60
61
62
63
64
65
# File 'lib/chef-api/proxy.rb', line 59

def method_missing(m, *args, &block)
  if @klass.respond_to?(m)
    @klass.send(m, *args, &block)
  else
    super
  end
end

Instance Method Details

#respond_to_missing?(m, include_private = false) ⇒ Boolean

Returns:



68
69
70
# File 'lib/chef-api/proxy.rb', line 68

def respond_to_missing?(m, include_private = false)
  @klass.respond_to?(m) || super
end