Class: Populator::Record

Inherits:
Object
  • Object
show all
Defined in:
lib/populator/record.rb

Overview

This is what is passed to the block when calling populate.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model_class, id) ⇒ Record

Creates a new instance of Record. Some attributes are set by default:

  • id - defaults to id passed

  • created_at - defaults to current time

  • updated_at - defaults to current time

  • created_on - defaults to current date

  • updated_on - defaults to current date

  • type - defaults to class name (for STI)



14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/populator/record.rb', line 14

def initialize(model_class, id)
  @attributes = { model_class.primary_key.to_sym => id }
  @columns = model_class.column_names
  @columns.each do |column|
    case column
    when 'created_at', 'updated_at'
      @attributes[column.to_sym] = Time.now
    when 'created_on', 'updated_on'
      @attributes[column.to_sym] = Date.today
    when model_class.inheritance_column
      @attributes[column.to_sym] = model_class.to_s
    end
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(sym, *args, &block) ⇒ Object (private)



55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/populator/record.rb', line 55

def method_missing(sym, *args, &block)
  name = sym.to_s
  if @columns.include?(name.sub('=', ''))
    if name.include? '='
      @attributes[name.sub('=', '').to_sym] = Populator.interpret_value(args.first)
    else
      @attributes[sym]
    end
  else
    super
  end
end

Instance Attribute Details

#attributesObject

Returns the value of attribute attributes.



4
5
6
# File 'lib/populator/record.rb', line 4

def attributes
  @attributes
end

Instance Method Details

#attribute_valuesObject

Return values for all columns inside an array.



40
41
42
43
44
# File 'lib/populator/record.rb', line 40

def attribute_values
  @columns.map do |column|
    @attributes[column.to_sym]
  end
end

#idObject

override id since method_missing won’t catch this column name



30
31
32
# File 'lib/populator/record.rb', line 30

def id
  @attributes[:id]
end

#typeObject

override type since method_missing won’t catch this column name



35
36
37
# File 'lib/populator/record.rb', line 35

def type
  @attributes[:type]
end