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



148
149
150
# File 'lib/light_record.rb', line 148

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

#define_attribute_methodsObject

used in Record#respond_to?



144
145
# File 'lib/light_record.rb', line 144

def define_attribute_methods
end

#define_fields(fields) ⇒ Object



119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
# File 'lib/light_record.rb', line 119

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

  fields.each do |field|
    field = field.to_sym unless field.is_a?(Symbol)
    @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) && !fields.include?("id") && primary_key.present?
    define_method(:id) do
      @attributes[self.class.primary_key.to_sym]
    end
  end
end