Class: DbBackupTool::Mappers::ActiveRecordMapper::Table
- Inherits:
-
Object
- Object
- DbBackupTool::Mappers::ActiveRecordMapper::Table
- Defined in:
- lib/db_backup_tool/mappers/active_record_mapper.rb
Overview
Table Proxy
Instance Method Summary collapse
-
#column_names ⇒ Object
Names of columns.
-
#each_record(batch_size = 1000) ⇒ Object
Enumerate records in the table.
-
#initialize(orm_class, table_name) ⇒ Table
constructor
Constructor.
-
#name ⇒ Object
Table name.
-
#truncate ⇒ Object
Clear the table.
-
#update(records) ⇒ Object
Update or create records.
Constructor Details
#initialize(orm_class, table_name) ⇒ Table
Constructor
29 30 31 32 33 |
# File 'lib/db_backup_tool/mappers/active_record_mapper.rb', line 29 def initialize(orm_class, table_name) @model = Class.new(orm_class) { self.table_name = table_name } end |
Instance Method Details
#column_names ⇒ Object
Names of columns
41 42 43 |
# File 'lib/db_backup_tool/mappers/active_record_mapper.rb', line 41 def column_names @model.columns.map(&:name) end |
#each_record(batch_size = 1000) ⇒ Object
Enumerate records in the table
62 63 64 65 66 67 68 69 70 |
# File 'lib/db_backup_tool/mappers/active_record_mapper.rb', line 62 def each_record(batch_size = 1000) if block_given? @model.find_each(batch_size: batch_size) do |r| yield record_hash(r) end else Enumerator.new self, :each_record end end |
#name ⇒ Object
Table name
36 37 38 |
# File 'lib/db_backup_tool/mappers/active_record_mapper.rb', line 36 def name @model.table_name end |
#truncate ⇒ Object
Clear the table
46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/db_backup_tool/mappers/active_record_mapper.rb', line 46 def truncate begin @model.connection.execute "TRUNCATE #{@model.quoted_table_name}" rescue ActiveRecord::ActiveRecordError begin @model.connection.execute "DELETE FROM #{@model.quoted_table_name}" rescue ActiveRecord::ActiveRecordError @model.connection.execute "DELETE * FROM #{@model.quoted_table_name}" end end if @model.connection.respond_to? :reset_pk_sequence! @model.connection.reset_pk_sequence! (@model.table_name) end end |
#update(records) ⇒ Object
Update or create records
73 74 75 76 77 78 79 80 81 82 83 84 |
# File 'lib/db_backup_tool/mappers/active_record_mapper.rb', line 73 def update(records) raise ArgumentError unless records.is_a?(Enumerable) @model.transaction do records.each {|attributes| id = attributes['id'] r = @model.find_or_initialize_by_id(id) r.id ||= id r.assign_attributes attributes.except('id') r.save! } end end |