Skip to content

Instantly share code, notes, and snippets.

@leylaKapi
Last active October 2, 2017 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leylaKapi/811022b75e7d5bb97000faf658fb280b to your computer and use it in GitHub Desktop.
Save leylaKapi/811022b75e7d5bb97000faf658fb280b to your computer and use it in GitHub Desktop.
Import datas with Rake in Rails
# For running this rake run "rails data:datas or rails data:seed"
def open_spreadsheet_data
Roo::Spreadsheet.open("#{Rails.root.to_s}/lib/data/datas.xlsx")
end
namespace :data do
task setup: [:environment] do
raise 'Nah, You are at production' if Rails.env.production?
Rake::Task['data:kill_postgres_connections'].execute
Rake::Task['db:drop'].execute
Rake::Task['db:create'].execute
Rake::Task['db:migrate'].execute
Rake::Task['data:seed'].execute
end
desc 'seed test data'
task seed: [:environment] do
Rake::Task['db:seed'].execute
Rake::Task['data:datas'].execute
end
desc 'import data for models'
task datas: [:environment] do
sheet = open_spreadsheet_data
brands_sheet = sheet.sheet('marka')
(2..brands_sheet.last_row).each do |i|
brand_row = brands_sheet.row(i)
brand = Brand.create(id: brand_row[0], name: brand_row[3])
print brand.id
brands_sheet = sheet.sheet('brand')
end
categories_sheet = sheet.sheet('kategori')
(2..categories_sheet.last_row).each do |j|
category_row = categories_sheet.row(j)
category = Category.create!(id: category_row[0], name: category_row[2], parent_id: category_row[4])
print category.id
categories_sheet = sheet.sheet('category')
end
product_sheet = sheet.sheet('ürün')
(2..product_sheet.last_row).each do |j|
product_row = product_sheet.row(j)
product = Product.create!(id: product_row[0], heading_translations: product_row[1], body_translations: product_row[2], is_active: product_row[3], brand_id: product_row[8], array_stock: product_row[9], prices_attributes: [is_main_price: product_row[7], currency: product_row[6], price: product_row[5], unit: product_row[4]])
category_ids = product_row[10].split(",")
print category_ids
product.category_ids = category_ids
product_sheet = sheet.sheet('product')
end
news_items_sheet = sheet.sheet('haber')
(2..news_items_sheet.last_row).each do |j|
news_item_row = news_items_sheet.row(j)
news_item = NewsItem.create!(id: news_item_row[0], title: news_item_row[1], body: news_item_row[2], short_description: news_item_row[3])
print news_item.id
news_items_sheet = sheet.sheet('news')
end
end
task kill_postgres_connections: [:environment] do
db_name = "#{File.basename(Rails.root)}_#{Rails.env}"
sh = <<EOF
ps xa \
| grep postgres: \
| grep #{db_name} \
| grep -v grep \
| awk '{print $1}' \
| xargs kill
EOF
puts `#{sh}`
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment