Class: WCC::API::RestClient::Builder

Inherits:
Object
  • Object
show all
Defined in:
lib/wcc/api/rest_client/builder.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(klass) ⇒ Builder

Returns a new instance of Builder.


4
5
6
# File 'lib/wcc/api/rest_client/builder.rb', line 4

def initialize(klass)
  @klass = klass
end

Instance Attribute Details

#resource_classObject


13
14
15
16
# File 'lib/wcc/api/rest_client/builder.rb', line 13

def resource_class
  @resource_class ||=
    @klass.const_get("Resource") || WCC::API::RestClient::Resource
end

Instance Method Details

#applyObject


31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/wcc/api/rest_client/builder.rb', line 31

def apply
  closed_params = (@params || []).freeze
  resources = @resources
  klass = @klass

  klass.class_exec do
    define_singleton_method :params do
      closed_params
    end

    define_singleton_method :default do
      @default ||= new
    end

    define_singleton_method :default= do |client|
      @default = client
    end

    resources.each do |(endpoint, options)|
      attr_name = options[:attribute] || endpoint.downcase
      resource_class = options[:resource_class]

      define_method attr_name do
        instance_variable_get("@#{attr_name}") ||
          instance_variable_set("@#{attr_name}", 
            resource_class.new(self, endpoint, options[:model], @options.merge(options))
          )
      end
    end
  end

  resources.each do |(endpoint, options)|
    options[:model].class_exec do
      define_singleton_method :client do
        klass.default
      end

      define_singleton_method :endpoint do
        endpoint
      end

      define_singleton_method :key do
        options[:key]
      end
    end

    options[:model].send(:include, WCC::API::ActiveRecordShim)
  end
end

#params(*params) ⇒ Object


8
9
10
# File 'lib/wcc/api/rest_client/builder.rb', line 8

def params(*params)
  @params = params.map(&:to_s)
end

#resource(endpoint, model:, **options, &block) ⇒ Object


18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/wcc/api/rest_client/builder.rb', line 18

def resource(endpoint, model:, **options, &block)
  @resources ||= {}

  resource_class = options[:resource_class] || self.resource_class
  if block_given?
    resource_class = Class.new(resource_class, &block)
  end
  @resources[endpoint] = options.merge({
    resource_class: resource_class,
    model: model,
  })
end