Sha256: abeeb057ca1d9313ed47ca59c8be1809ae71b142afed36afd2174534d66c3145

Contents?: true

Size: 1 KB

Versions: 2

Compression:

Stored size: 1 KB

Contents

require 'active_support/concern'
require 'active_support/dependencies/autoload'
require 'securerandom'

module MemoryModel::Base::Fieldable
  extend ConcernedInheritance
  extend ActiveSupport::Concern
  extend ActiveSupport::Autoload
  include ActiveModel::AttributeMethods

  autoload :FieldSet
  autoload :Field

  inherited do
    instance_variable_set :@fields, baseclass.fields
    field :id, readonly: true, default: -> { SecureRandom.uuid }, comparable: false
  end

  module ClassMethods
    def field(attr, options={ })
      define_attribute_method attr unless instance_method_already_implemented? attr
      fields.add(attr.to_sym, options)
      class_eval <<-RUBY, __FILE__, __LINE__ + 1
        def #{attr}
          read_attribute :#{attr}
        end

        def #{attr}=(value)
          write_attribute :#{attr}, value
        end
      RUBY
    end

    def fields
      return nil if self == MemoryModel::Base
      @fields ||= FieldSet.new
    end

  end

  def fields
    self.class.fields
  end

end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
memory_model-0.0.2 lib/memory_model/base/fieldable.rb
memory_model-0.0.1 lib/memory_model/base/fieldable.rb