Sha256: ea8bbcf237792b0ed1e27cafe8fd3fc814c3edc643db7eb5c9d6e77a83564a6b

Contents?: true

Size: 1.25 KB

Versions: 3

Compression:

Stored size: 1.25 KB

Contents

# frozen_string_literal: true

module ActiveCampaign
  class Model # :nodoc:
    include ActiveModel::Model
    include ActiveModel::Dirty

    include ActiveCampaign::ApiHttp
    include ActiveCampaign::Attributes

    class << self
      def all
        get endpoint
      end

      def filter(args = {})
        query = args.map { |k, v| "filters[#{k}]=#{v}" }.join "&"

        get "#{endpoint}?#{query}"
      end

      def find_by(args = {})
        filter(args).last
      end

      def find(id)
        get "#{endpoint}/#{id}", { _root: root_element }
      end

      def save(**args)
        new(args).save
      end

      def create(**args)
        new(args).create
      end
    end

    def save
      return update if defined?(id) && id.present?

      create
    end

    def update
      return nil unless changed?

      result = self.class.put "#{self.class.endpoint}/#{id}", only_changes_to_params

      assign_attributes result.to_params.first.last

      changes_applied

      self
    end

    def create
      result = self.class.post self.class.endpoint, to_params

      assign_attributes result.to_params.first.last

      changes_applied

      self
    end

    def destroy
      self.class.delete "#{self.class.endpoint}/#{id}"
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
ractive_campaign-0.1.3 lib/active_campaign/models/model.rb
ractive_campaign-0.1.2 lib/active_campaign/models/model.rb
ractive_campaign-0.1.1 lib/active_campaign/models/model.rb