Sha256: a1f7af76cd455ec6430013ec40280237e1657a2c8eeb15d2487ddc317f8d1786

Contents?: true

Size: 1.82 KB

Versions: 1

Compression:

Stored size: 1.82 KB

Contents

module Mautic
  class Proxy

    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

    def new(attributes = {})
      build_instance attributes
    end

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

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

    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

    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

    def first
      where(limit: 1).first
    end

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

    def count
      return @count if defined? @count

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

  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
mautic-2.3.1 lib/mautic/proxy.rb