Sha256: 32cddf48033801948d1b96d1c9a15ca9c2b68cedcecf78dea235b87100e0f767

Contents?: true

Size: 1.45 KB

Versions: 1

Compression:

Stored size: 1.45 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
    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.3 lib/hari/entity.rb