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)
  @options = options || {}
  @connection = connection
  klass = @options.delete(:klass) || "Mautic::#{endpoint.classify}"
  @target = klass.safe_constantize || Mautic.const_set(endpoint.classify, Class.new(Mautic::Model))
  @endpoint = endpoint
end

Instance Method Details

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



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/mautic/proxy.rb', line 24

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

#build_instance(data) ⇒ Object



20
21
22
# File 'lib/mautic/proxy.rb', line 20

def build_instance(data)
  @target.new(@connection, data)
end

#countObject



67
68
69
70
71
72
# File 'lib/mautic/proxy.rb', line 67

def count
  return @count if defined? @count

  json = @connection.request(:get, "api/#{@endpoint}", { limit: 1 })
  @count = json["total"].to_i
end

#data_nameObject



16
17
18
# File 'lib/mautic/proxy.rb', line 16

def data_name
  @endpoint.split("/").last
end

#find(id) ⇒ Object



61
62
63
64
65
# File 'lib/mautic/proxy.rb', line 61

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

#firstObject



57
58
59
# File 'lib/mautic/proxy.rb', line 57

def first
  where(limit: 1).first
end

#new(attributes = {}) ⇒ Object



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

def new(attributes = {})
  build_instance attributes
end

#where(params = {}) ⇒ Object



47
48
49
50
51
52
53
54
55
# File 'lib/mautic/proxy.rb', line 47

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