Class: Seeder
- Inherits:
-
Object
- Object
- Seeder
- Defined in:
- lib/seeder.rb,
lib/seeder/version.rb
Constant Summary collapse
- VERSION =
'1.4.0'
Instance Attribute Summary collapse
-
#data ⇒ Object
readonly
Returns the value of attribute data.
-
#keys ⇒ Object
readonly
Returns the value of attribute keys.
-
#model ⇒ Object
readonly
Returns the value of attribute model.
Class Method Summary collapse
Instance Method Summary collapse
- #create ⇒ Object
- #create_new_records ⇒ Object
- #delete_outdated_records ⇒ Object
-
#initialize(data, keys, model) ⇒ Seeder
constructor
A new instance of Seeder.
- #update_existing_records ⇒ Object
Constructor Details
#initialize(data, keys, model) ⇒ Seeder
Returns a new instance of Seeder.
8 9 10 11 12 |
# File 'lib/seeder.rb', line 8 def initialize(data, keys, model) @keys = keys.map(&:to_sym) @data = data.map(&:symbolize_keys) @model = model end |
Instance Attribute Details
#data ⇒ Object (readonly)
Returns the value of attribute data.
2 3 4 |
# File 'lib/seeder.rb', line 2 def data @data end |
#keys ⇒ Object (readonly)
Returns the value of attribute keys.
2 3 4 |
# File 'lib/seeder.rb', line 2 def keys @keys end |
#model ⇒ Object (readonly)
Returns the value of attribute model.
2 3 4 |
# File 'lib/seeder.rb', line 2 def model @model end |
Class Method Details
.create(data, keys, model) ⇒ Object
4 5 6 |
# File 'lib/seeder.rb', line 4 def self.create(data, keys, model) new(data, keys, model).create end |
Instance Method Details
#create ⇒ Object
14 15 16 17 18 19 20 |
# File 'lib/seeder.rb', line 14 def create model.transaction do delete_outdated_records update_existing_records create_new_records end end |
#create_new_records ⇒ Object
37 38 39 40 41 42 43 |
# File 'lib/seeder.rb', line 37 def create_new_records new_keys = data_keys_hash.keys - existing_records_keys_hash.keys data_keys_hash.values_at(*new_keys).each do |attributes| model.create!(attributes) end end |
#delete_outdated_records ⇒ Object
22 23 24 25 |
# File 'lib/seeder.rb', line 22 def delete_outdated_records return unless records_to_delete.present? model.where(id: records_to_delete).delete_all end |
#update_existing_records ⇒ Object
27 28 29 30 31 32 33 34 35 |
# File 'lib/seeder.rb', line 27 def update_existing_records existing_records_keys_hash.each do |record_keys, record| attributes = data_keys_hash[record_keys] next unless attributes record.attributes = attributes record.save! if record.changed? end end |