Sha256: 59b10fd7b046beaac82787831a60ee170a3423aaf4eb7578bf7fcab0a50efad8

Contents?: true

Size: 1.65 KB

Versions: 1

Compression:

Stored size: 1.65 KB

Contents

require 'encore/entity/input/errors'
require 'encore/entity/input/exposed_attributes'

module Encore
  module Entity
    module Input
      extend ActiveSupport::Concern

      included do
        include Encore::Entity::Input::ExposedAttributes

        # Expose ID as a readonly attribute
        expose :id, readonly: true
      end

      # Assign specific attribute to the object
      def assign_attributes(attributes = {}, opts = nil)
        # Find the right context
        unless context = opts.try(:delete, :context)
          context = @object.persisted? ? :create : :partial_update
        end

        # Convert attribute keys to Attribute objects
        attributes = Encore::Attribute.map_attributes(self.class, attributes)

        # Loop through every passed attribute and set it
        assign_provided_attributes(attributes, context)

        # If we're doing an update, for any exposed attribute that wasn't passed, set it to nil
        reset_forgotten_attributes(attributes, context)
      end

    protected

      def assign_provided_attributes(attributes, context)
        attributes.each_pair do |attribute, value|
          if self.class.modifiable_attribute?(attribute)
            send :"#{attribute.attribute}=", value
          else
            raise Encore::Entity::Input::ProtectedAttributeError.new("The #{attribute} attribute is not exposed.")
          end
        end
      end

      def reset_forgotten_attributes(attributes, context)
        if context == :update
          (self.class.modifiable_attributes - attributes.keys).each do |attribute|
            send :"#{attribute.attribute}=", nil
          end
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
encore-0.0.2 lib/encore/entity/input.rb