Class: StaticData::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/static-data/base.rb

Class Method Summary collapse

Class Method Details

.columnsObject

Override this method to control which attributes make up the data returned by the ‘rows` method.



25
26
27
# File 'lib/static-data/base.rb', line 25

def self.columns
  []
end

.installObject

Creates new records for all of the data returned by the ‘rows` method of the StaticData subclass.



38
39
40
41
42
43
44
45
# File 'lib/static-data/base.rb', line 38

def self.install
  cols = self.columns
  row_class = self.model_class
  self.rows.each do |row|
    row_class.create!(Hash[cols.zip(row)], :without_protection => true)
  end
  return {:created => self.rows.size}
end

.model_classObject

Returns the model class for this StaticData subclass (which is the class name without the “Static” prefix by default, but can be overridden via set_model_class).



13
14
15
16
# File 'lib/static-data/base.rb', line 13

def self.model_class
  model_class_name = @model_class_name || self.name.sub(/^Static/, '')
  Object.const_get(model_class_name)
end

.resetObject

Deletes all model_class records from the database.



19
20
21
# File 'lib/static-data/base.rb', line 19

def self.reset
  self.model_class.delete_all
end

.rowsObject

Override this method to return the record data that should always exist in the model class’s database table. The columns must appear in the the order specified by the ‘columns` method.



32
33
34
# File 'lib/static-data/base.rb', line 32

def self.rows
  []
end

.set_model_class(other_model_class) ⇒ Object

Overrides the default model class for this StaticData class. Use this if your StaticData class name is not “Static + ModelClass”. If you stick to the standard naming convention, you don’t need this method.



6
7
8
# File 'lib/static-data/base.rb', line 6

def self.set_model_class(other_model_class)
  @model_class_name = other_model_class
end

.updateObject

Creates new records for all of the data returned by the ‘rows` method of the StaticData subclass – unless they exist already.



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/static-data/base.rb', line 49

def self.update
  created = 0
  existing = 0
  cols = self.columns
  row_class = self.model_class
  self.rows.each do |row|
    attribs = Hash[cols.zip(row)]
    row_class.transaction do
      if row_class.exists?(attribs)
        existing += 1
      else
        row_class.create!(attribs, :without_protection => true)
        created += 1
      end
    end
  end
  return {:created => created, :existing => existing}
end