Sha256: 0f40d70dbeb3d4603be5a1269b83a1f0c5dbc183455942bb49a31d11c2c293d0

Contents?: true

Size: 1.73 KB

Versions: 2

Compression:

Stored size: 1.73 KB

Contents

module StaticRecord
  # This is the base class of StaticRecord.
  class Base
    include StaticRecord::ActiveRecord

    class << self
      include StaticRecord::LoaderFile
      include StaticRecord::GatewayModel

      attr_accessor :file_path

      def file_path
        @file_path ||= File.join(Rails.root, 'db', 'static')
      end
    end

    def initialize(hash = {}, load = true)
      self.class.init if load

      raise StaticRecord::StaticRecordModelInitializeError,
            "Unpermited attributes #{hash.inspect},
            it should be a hash" unless hash.is_a?(Hash)

      self.attributes = hash
    end

    def attributes=(hash)
      hash.each { |k, v| set_attribute(k, v) }
    end

    def attributes
      @attributes ||= {}
    end

    def attributes_keys
      attributes.keys.collect(&:to_sym)
    end

    def attribute?(attribute)
      attributes_keys.include?(attribute)
    end

    def to_s
      "<#{self.class} 0x#{object_id.to_s 16}> #{@attributes.inspect}"
    end

    private

    def set_attribute(name, value)
      attributes[name.to_sym] = value
    end

    def get_attribute(name)
      attributes[name.to_sym]
    end

    # Metaprogramming for read and set attributes through dynamic methods.

    def method_missing(meth, *params, &block)
      attribute = meth.to_s.gsub(/=$/, '')

      if attribute? attribute.to_sym
        # The method missing is a setter method.
        return set_attribute attribute, params.first if meth.to_s =~ /=$/

        # The method missing is a getter method.
        return get_attribute attribute
      end

      super
    end

    def respond_to_missing?(meth, *args)
      attribute = meth.to_s.gsub(/=$/, '')

      attribute?(attribute.to_sym) || super
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
rails_static_record-0.1.1 lib/static_record/base.rb
rails_static_record-0.1.0 lib/static_record/base.rb