Sha256: 75d90728c7d06db84d8a48ac53c824a13f231a25f4736df2316add8db71b3d9b

Contents?: true

Size: 1.05 KB

Versions: 1

Compression:

Stored size: 1.05 KB

Contents

require 'encore/entity/input'
require 'encore/entity/output'

module Encore
  module Entity
    extend ActiveSupport::Concern

    included do
      include Input
      include Output

      # Make `object` accessible for others
      attr_accessor :object
    end

    # Initialize a new entity, linked to an ActiveRecord object
    # If no object is passed, let's try to build a new one
    def initialize(object = nil)
      @object = object || self.class.linked_class.new
    end

    # Save the object
    def save
      run_callbacks(:save) { @object.save }
    end

    # Delegate everything to the object
    def method_missing(method, *args, &blk)
      if @object.respond_to?(method)
        @object.send(method, *args, &blk)
      else
        super
      end
    end

    module ClassMethods
      # Return the object class. If no object is present, try to
      # guess the class with our own class name (`UserEntity` would be `User`)
      def linked_class
        @object ? @object.class : self.name.split(/Entity$/).first.constantize
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
encore-0.0.3 lib/encore/entity.rb