module Import1
def import1(file)
spreadsheet = Roo::Spreadsheet.open(file.path)
header = spreadsheet.row(1)
(2..spreadsheet.last_row).each do |i|
row = Hash[[header, spreadsheet.row(i)].transpose]
puts row.to_hash
product = find_by(id: row["id"]) || new
product.attributes = row.to_hash
product.save!
end
end
def search(search_scope,compare)
if search_scope == "All"
all.order(:id)
elsif compare == "Bihar vs District"
where("Districts = ? OR Districts = ?", search_scope, "Bihar")
else
where(Districts: search_scope)
end
end
end
app
models
app/model_modules
app/shared_model_modules
import_1.rb
class ProductionProductivity7 < ApplicationRecord
extend Import1
end
BaseService
class BaseService
attr_accessor :args
class << self
def call(args=nil)
new(args).call
end
end # Class Methods
#=======================================================================
# Instance Methods
#=======================================================================
def initialize(args)
@args = args || {}
assign_args
end
private
def assign_args
args.each do |k,v|
class_eval do
attr_accessor k
end
send("#{k}=",v)
end
end
end
class ImportFileService < BaseService
def call
spreadsheet = Roo::Spreadsheet.open(file.path)
header = spreadsheet.row(1)
(2..spreadsheet.last_row).each do |i|
row = Hash[[header, spreadsheet.row(i)].transpose]
puts row.to_hash
product = klass.find_or_initialize_by(id: row["id"])
product.attributes = row.to_hash
product.save!
end
end
end
ImportFileService.call(file: file, klass: ProductionProductivity7)