Sha256: 1cb782871a9020c9e8f2e2172cdc2c752c3047e3d88d64cade5a7ef4edfa4e89

Contents?: true

Size: 1.61 KB

Versions: 1

Compression:

Stored size: 1.61 KB

Contents

require 'hari/entity/property'
require 'hari/entity/repository'
require 'hari/entity/serialization'

module Hari
  class Entity
    extend  ActiveModel::Naming
    extend  ActiveModel::Callbacks
    include ActiveModel::Validations

    autoload :Property,      'hari/entity/property'
    autoload :Repository,    'hari/entity/property'
    autoload :Serialization, 'hari/entity/property'

    extend  Property::Builder
    include Repository
    include Serialization

    define_model_callbacks :create, :update, :destroy, :save

    property :id
    property :created_at, type: Time
    property :updated_at, type: Time

    def initialize(attrs = {})
      return if attrs.blank?

      attrs = attrs.with_indifferent_access

      self.class.properties.each do |prop|
        send("#{prop.name}=", attrs[prop.name]) if attrs[prop.name]
      end
    end

    def attributes
      self.class.properties.inject({}) do |buffer, prop|
        buffer.merge prop.name => send(prop.name)
      end
    end

    alias :attribute :send
    alias :read_attribute :send
    alias :has_attribute? :respond_to?

    def write_attribute(name, value)
      send "#{name}=", value
    end

    def ==(other)
      other.is_a?(Hari::Entity) && id == other.id
    end

    def new?
      id.nil?
    end

    alias :new_record? :new?

    def persisted?
      not new?
    end

    def destroyed?
      @destroyed
    end

    def generate_id
      '_e' + ::Time.now.strftime('%Y%m%d%H%M%S') + SecureRandom.hex(3)
    end

    def to_s
      attrs = attributes
      attrs.delete 'id'

      "<#{self.class} id='#{id}' attributes=#{attrs}>"
    end

  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
hari-0.0.4 lib/hari/entity.rb