class Mautic::Proxy

Public Class Methods

new(connection, endpoint, options = nil) click to toggle source
# 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

Public Instance Methods

all(options = {}) { |i| ... } click to toggle source
# File lib/mautic/proxy.rb, line 24
def all(options = {}, &block)
  if options[:limit] == 'all'
    options.delete(:limit)
    limit_all(options, &block)
  else
    results = where(options)
    results.each { |i| yield i } if block_given?
    results
  end
end
build_instance(data) click to toggle source
# File lib/mautic/proxy.rb, line 20
def build_instance(data)
  @target.new(@connection, data)
end
count() click to toggle source
# File lib/mautic/proxy.rb, line 57
def count
  return @count if defined? @count

  json = @connection.request(:get, "api/#{@endpoint}", { limit: 1 })
  @count = json["total"].to_i
end
data_name() click to toggle source
# File lib/mautic/proxy.rb, line 16
def data_name
  @options[:data_name] || @endpoint.split("/").last
end
find(id) click to toggle source
# File lib/mautic/proxy.rb, line 51
def find(id)
  json = @connection.request(:get, "api/#{@endpoint}/#{id}")
  @last_response = json
  build_instance json[data_name.singularize]
end
first() click to toggle source
# File lib/mautic/proxy.rb, line 47
def first
  where(limit: 1).first
end
new(attributes = {}) click to toggle source
# File lib/mautic/proxy.rb, line 12
def new(attributes = {})
  build_instance attributes
end
where(params = {}) click to toggle source

@param [Hash] params @see developer.mautic.org

# File lib/mautic/proxy.rb, line 37
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

Protected Instance Methods

limit_all(options, &block) click to toggle source

@param [Hash] options @option options (see where)

# File lib/mautic/proxy.rb, line 68
def limit_all(options, &block)
  records = results = where(options)
  total = @last_response['total'].to_i
  while records.any?
    records.each(&block) if block_given?
    break if results.size >= total

    records = where(options.merge(start: records.size))
    results.concat records
  end
  results
end