Sha256: 14f6e96cb2048819a2ea95aed1685bf7ce4977514488aa66153892e640dbc922

Contents?: true

Size: 1.85 KB

Versions: 7

Compression:

Stored size: 1.85 KB

Contents

require 'pupper/api_associations'
require 'pupper/auditable'
require 'pupper/trackable_attributes'

module Pupper
  module Model
    extend ActiveSupport::Concern

    class NoSuchBackend < NameError; end

    included do
      include ActiveModel::Model
      include ActiveModel::Serializers::JSON

      include Pupper::Auditable
      include Pupper::TrackableAttributes
      include Pupper::ApiAssociations

      delegate :backend, to: :class

      def initialize(**args)
        assocs, attrs = args.partition do |attr, value|
          attr.to_s =~ /_u?id$/ || value.is_a?(Hash) || value.is_a?(Array)
        end.map(&Hash.method(:[]))

        assocs = build_associations(assocs)

        super(**attrs, **assocs)

        changes_applied

        backend.register_model(self) unless backend == :none
      end

      def primary_key
        attributes.fetch(self.class.primary_key)
      end
    end

    class_methods do
      attr_writer :primary_key, :backend

      # @overload primary_key=(identifier)
      #   Set the identifier the including model will use by default
      #   when finding or updating (defaults to `:uid`)
      #
      #   == Parameters:
      #   identifier::
      #     A symbol refering to the identifying field in the model. e.g.
      #     `:id`.
      def primary_key
        @primary_key ||= :uid
      end

      # @overload backend=(class_or_symbol)
      #   Declare whether or not the model has a corresponding API client or not.
      #   (default: including class, plural, + client, e.g. `Form` => `FormsClient`)
      #
      #   == Parameters:
      #   class_or_symbol::
      #     `:none` if the model has no API, constant otherwise.
      def backend
        @backend ||= "#{model_name.name.pluralize}Client".constantize.new
      end
    end

    def to_json(*)
      attributes.except(*excluded_attrs).to_json
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
pupper-0.2.0 lib/pupper/model.rb
pupper-0.1.13 lib/pupper/model.rb
pupper-0.1.12 lib/pupper/model.rb
pupper-0.1.11 lib/pupper/model.rb
pupper-0.1.10 lib/pupper/model.rb
pupper-0.1.9 lib/pupper/model.rb
pupper-0.1.8 lib/pupper/model.rb