Class: Mautic::Proxy

Inherits:
Object
  • Object
show all
Defined in:
lib/mautic/proxy.rb

Instance Method Summary collapse

Constructor Details

#initialize(connection, endpoint, options = nil) ⇒ Proxy

Returns a new instance of Proxy.



4
5
6
7
8
9
10
# File 'lib/mautic/proxy.rb', line 4

def initialize(connection, endpoint, options = nil)
  @connection = connection
  klass = "Mautic::#{endpoint.classify}"
  @target = klass.safe_constantize || Mautic.const_set(endpoint.classify, Class.new(Mautic::Model))
  @endpoint = endpoint
  @options = options || {}
end

Instance Method Details

#all(options = {}, &block) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/mautic/proxy.rb', line 16

def all(options = {}, &block)
  if options[:limit] == 'all'

    options.delete(:limit)

    records = results = where(options)
    total = @last_response['total'].to_i
    while records.any?
      if block_given?
        records.each &block
      end
      break if results.size >= total

      records = where(options.merge(start: records.size))
      results.concat records
    end
  else
    results = where(options)
    results.each{|i| yield i } if block_given?
  end
  results
end

#find(id) ⇒ Object



52
53
54
55
56
# File 'lib/mautic/proxy.rb', line 52

def find(id)
  json = @connection.request(:get, "api/#{@endpoint}/#{id}")
  @last_response = json
  @target.new(@connection, json[@endpoint.singularize])
end

#firstObject



48
49
50
# File 'lib/mautic/proxy.rb', line 48

def first
  where(limit: 1).first
end

#new(attributes = {}) ⇒ Object



12
13
14
# File 'lib/mautic/proxy.rb', line 12

def new(attributes = {})
  @target.new(@connection, attributes)
end

#where(params = {}) ⇒ Object



39
40
41
42
43
44
45
46
# File 'lib/mautic/proxy.rb', line 39

def where(params = {})
  q =  params.reverse_merge(@options[:default_params] || {})
  json = @connection.request(:get, "api/#{@endpoint}", {params: q })
  @last_response = json
  json[@endpoint].collect do |id, attributes|
    @target.new(@connection, attributes || id)
  end
end