Module: LightRecord::RecordAttributes

Defined in:
lib/light_record.rb

Overview

ActiveRecord extension for class methods Defines klass.define_fields Overrides klass.column_names and klass.define_attribute_methods

Instance Method Summary collapse

Instance Method Details

#column_namesObject

Active record keep it as strings, but I keep it as symbols



175
176
177
# File 'lib/light_record.rb', line 175

def column_names
  @column_names ||= @fields.map(&:to_s)
end

#define_attribute_methodsObject

used in Record#respond_to?



171
172
# File 'lib/light_record.rb', line 171

def define_attribute_methods
end

#define_fields(fields) ⇒ Object



146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# File 'lib/light_record.rb', line 146

def define_fields(fields)
  @fields ||= []

  fields.each do |field|
    field = field.to_sym
    @fields << field
    define_method(field) do
      @attributes[field]
    end

    # to avoid errors when try saving data
    define_method("#{field}=") do |value|
      @attributes[field] = value
    end
  end

  # ActiveRecord make method :id refers to primary key, even there is no column "id"
  if !@fields.include?(:id) && primary_key.present?
    define_method(:id) do
      @attributes[self.class.primary_key.to_sym]
    end
  end
end