Import old database into new schema in Rails - ruby-on-rails

I want to import my old database to new schema in rails.
For that i have .rake file:
# /lib/tasks/project_name.rake:
namespace :project_name do
require Rails.root + "lib/tasks/importer"
desc "Import old database, usage: rake project_name:import['old_database_name']"
task :import, :oldDatabase, needs::environment do |t, args|
args.with_defaults(oldDatabase: "import")
oldDatabaseName = args.oldDatabse
newDatabaseName = YAML::load(IO.read(Rails.root.join("config/database.yml")))[Rails.env]["database"]
importer = Importer.new newDatabaseName, oldDatabaseName
importer.execute
end
end
but after adding that file I can't even use any rake command.
Here is some lines of trace:
no implicit conversion of pathname into string
/Users/user/Desktop/rails/dis/lib/tasks/project_name.rake:2:in `block in <top (required)>'
/Users/user/Desktop/rails/dis/lib/tasks/project_name.rake:1:in `<top (required)>'
I am doing it by looking at this tutorial:
http://www.frick-web.at/blog/import-old-database-in-new-schema-with-mysql-and-rails

try
require Rails.root.join("lib/tasks/importer").to_s

Related

Where is db:create defined in Rails?

The following command is supposed to create a new database.
rails db:create
Where is this function defined? Or is this a pre-packaged function in rails?
It's in the databases.rake file of the framework:
namespace :create do
task all: :load_config do
ActiveRecord::Tasks::DatabaseTasks.create_all
end
ActiveRecord::Tasks::DatabaseTasks.for_each do |spec_name|
desc "Create #{spec_name} database for current environment"
task spec_name => :load_config do
db_config = ActiveRecord::DatabaseConfigurations.config_for_env_and_spec(Rails.env, spec_name)
ActiveRecord::Tasks::DatabaseTasks.create(db_config.config)
end
end
end
Whenever you doubt or want to know where a task has been defined, you can use the rails -W (or rake) command, passing the task:
$ rails -W db:create
rails db:create /path/databases.rake:26:in `block in <top (required)>'
rails db:create:all /path/databases.rake:20:in `block (2 levels) in <top (required)>'
Note it was introduced in the version 0.9 of Rake. This might or might not work depending on the versions which you're working with.

Rails error Uninitialized constant importing csv

This is my first time importing a csv file to my rails app.
I have the code below in /lib/tasks/import.rake
require 'csv'
CSV.foreach("lib/articles.csv", headers: true, encoding: "ISO8859-1") do |row|
Article.new(title: row["Title"], body: row["Body"], user: User.find(1))
end
When I run rake import:articles
I get this error:
NameError: uninitialized constant Article
/Users/justinMgrant/code/hrsurvival/lib/tasks/import.rake:8:in `block in <top (required)>'
/Users/justinMgrant/code/hrsurvival/lib/tasks/import.rake:7:in `<top (required)>'
/Users/justinMgrant/.rvm/gems/ruby-2.2.1/gems/railties-4.2.2/lib/rails/engine.rb:658:in `block in run_tasks_blocks'
/Users/justinMgrant/.rvm/gems/ruby-2.2.1/gems/railties-4.2.2/lib/rails/engine.rb:658:in `each'
/Users/justinMgrant/.rvm/gems/ruby-2.2.1/gems/railties-4.2.2/lib/rails/engine.rb:658:in `run_tasks_blocks'
/Users/justinMgrant/.rvm/gems/ruby-2.2.1/gems/railties-4.2.2/lib/rails/application.rb:452:in `run_tasks_blocks'
/Users/justinMgrant/.rvm/gems/ruby-2.2.1/gems/railties-4.2.2/lib/rails/engine.rb:453:in `load_tasks'
/Users/justinMgrant/code/hrsurvival/Rakefile:6:in `<top (required)>'
(See full trace by running task with --trace)
Any idea what I’m doing wrong?
The problem is that you're not actually defining your task in your rakefile. This should work for you to be able to run rake import:articles.
namespace :import do
desc 'An optional description for what the task does'
task :articles => :environment do
# your code goes here
end
end
rake import:articles is saying to look for a task called articles within a namespace called import, which is why the namespace is necessary for what you're currently trying.
And as #max mentioned, utilizing task :articles => :environment is what tells the task to run in the context of your Rails environment, which would make your Articles model and any other model available to you in that task.

Rails populate db rake task OpenURI::HTTPError: 500 Internal Server Error

I am trying to make rake task to populate db from JSON API fixer.io,
but when i type my rake :
rake db:populate
this error occurs:
OpenURI::HTTPError: 500 Internal Server Error
/home/jakub/Documents/workspace/exch/lib/tasks/populate.rake:16:in `block (5 levels) in <top (required)>'
/home/jakub/Documents/workspace/exch/lib/tasks/populate.rake:13:in `block (4 levels) in <top (required)>'
/home/jakub/Documents/workspace/exch/lib/tasks/populate.rake:12:in `each'
/home/jakub/Documents/workspace/exch/lib/tasks/populate.rake:12:in `block (3 levels) in <top (required)>'
/home/jakub/Documents/workspace/exch/lib/tasks/populate.rake:11:in `each'
/home/jakub/Documents/workspace/exch/lib/tasks/populate.rake:11:in `block (2 levels) in <top (required)>'
Tasks: TOP => db:populate
(See full trace by running task with --trace)
This is my rake task (populate.rake) in lib/tasks:
require 'open-uri'
namespace :db do
desc "Erase and fill database"
task :populate => :environment do
require 'populator'
[ConversionRate].each(&:delete_all)
n = JSON.load(open('http://api.fixer.io/latest'))["rates"].keys.count
currencies = JSON.load(open('http://api.fixer.io/latest'))["rates"].keys
currencies.each do |curr1|
currencies.each do |curr2|
ConversionRate.populate 1 do |cr|
cr.currency1 = curr1
cr.currency2 = curr2
cr.conversion_rate = JSON.load(open('http://api.fixer.io/latest?base=' + curr1))["rates"][curr2]
end
end
end
end
end
Please help me, I have no idea what causes this problem.
the main problem is here, you are not taking keys of "rates"
currencies = JSON.load(open('http://api.fixer.io/latest')).keys
currencies = JSON.load(open('http://api.fixer.io/latest'))["rates"].keys
require 'open-uri'
namespace :db do
desc "Erase and fill database"
task :populate => :environment do
require 'populator'
[ConversionRate].each(&:delete_all)
latest_data = JSON.load(open('http://api.fixer.io/latest'))
currencies = latest_data["rates"].keys
n = currencies.count
currencies.each do |curr1|
currencies.each do |curr2|
ConversionRate.populate 1 do |cr|
#take care of any error, as we are going to call third party api here
begin
cr.currency1 = curr1
cr.currency2 = curr2
cr.conversion_rate = JSON.load(open('http://api.fixer.io/latest?base=' + curr1))["rates"][curr2]
rescue => e
puts "error #{e}"
end
end
end
#give a bit rest
sleep 2
end
end
end

Enhance assets:precompile on Heroku to add non fingerptinted filenames

In a Rails 4 app, I want precompiled assets to have copies of some assets to be available with a non fingerprinted filename. The app is deployed on Heroku.
I have the following rake task in place:
namespace :app do
task :nonfingerprint_assets => :environment do
manifests = Rails.application.config.assets[:precompile]
manifests = manifests.slice(1, manifests.length)
assets = Dir.glob(File.join(Rails.root, 'public/assets/**/*'))
regex = /(-{1}[a-z0-9]{32}*\.{1}){1}/
assets.each do |file|
next if File.directory?(file) || file !~ regex
source = file.split('/')
source.push(source.pop.gsub(regex, '.'))
non_digested = File.join(source)
if manifests.any? {|m|
if m.is_a? Regexp
m.match non_digested
else
m.ends_with?(non_digested)
end
}
puts "** copy source: #{file}"
puts "** copy destination: #{non_digested}"
FileUtils.cp(file, non_digested)
end
end
end
end
Rake::Task['assets:precompile'].enhance do
puts "Invoke nonfingerprint_assets"
Rake::Task['app:nonfingerprint_assets'].invoke
end
This rake task is working fine on my local machine even in production environment. It creates a file in public/assets/application.js which is the copy of the same file with a digest in its name.
When I deploy this code to heroku I get the following error message which I don't understand:
-----> Preparing app for Rails asset pipeline
Running: rake assets:precompile
[deprecated] I18n.enforce_available_locales will default to true in the future. If you really want to skip validation of your locale you can set I18n.enforce_available_
locales = false to avoid this message.
Invoke nonfingerprint_assets
** copy source: /tmp/build_48b86bff-83f9-4d21-8b21-712c1baef811/public/assets/application-51d1660b66655782ab137ee98c789fdd.js
** copy destination: /tmp/build_48b86bff-83f9-4d21-8b21-712c1baef811/public/assets/application.js
rake aborted!
No such file or directory - /tmp/build_48b86bff-83f9-4d21-8b21-712c1baef811/public/assets/application.js
/tmp/build_48b86bff-83f9-4d21-8b21-712c1baef811/lib/tasks/production.rake:26:in `block (3 levels) in <top (required)>'
/tmp/build_48b86bff-83f9-4d21-8b21-712c1baef811/lib/tasks/production.rake:9:in `each'
/tmp/build_48b86bff-83f9-4d21-8b21-712c1baef811/lib/tasks/production.rake:9:in `block (2 levels) in <top (required)>'
/tmp/build_48b86bff-83f9-4d21-8b21-712c1baef811/lib/tasks/production.rake:45:in `block in <top (required)>'
Tasks: TOP => app:nonfingerprint_assets
(See full trace by running task with --trace)
Please help me to understand what's going on.

rake aborted! for uninitialized constant that does exist

I have built a rake task --
# SET RAKE TASK NAMESPACE
namespace :db do
# RAKE TASK DESCRIPTION
desc "Fetch property information and insert it into the database"
# RAKE TASK NAME
task :insert_properties do
# REQUIRE LIBRARIES
require 'nokogiri'
require 'open-uri'
# OPEN THE XML FILE
mits_feed = File.open("app/assets/xml/mits.xml")
# OUTPUT THE XML DOCUMENT
doc = Nokogiri::XML(mits_feed)
# FIND PROPERTIES OWNED BY NORTHSTEPPE AND CYCLE THORUGH THEM
doc.xpath("//Property/PropertyID/Identification[#OrganizationName='northsteppe']").each do |property|
# GATHER EACH PROPERTY'S INFORMATION
information = {
"street_address" => property.xpath("/Address/AddressLine1/text()"),
"city" => property.xpath("/Address/City/text()"),
"zipcode" => property.xpath("/Address/PostalCode/text()"),
"short_description" => property.xpath("/Information/ShortDescription/text()"),
"long_description" => property.xpath("Information/LongDescription/text()"),
"rent" => property.xpath("/Information/Rents/StandardRent/text()"),
"application_fee" => property.xpath("/Fee/ApplicationFee/text()"),
"bedrooms" => property.xpath("/Floorplan/Room[#RoomType='Bedroom']/Count/text()"),
"bathrooms" => property.xpath("/Floorplan/Room[#RoomType='Bathroom']/Count/text()"),
"bathrooms" => property.xpath("/ILS_Unit/Availability/VacancyClass/text()")
}
# CREATE NEW PROPERTY WITH INFORMATION HASH CREATED ABOVE
Property.create!(information)
end # ENDS XPATH EACH LOOP
end # ENDS INSERT_PROPERTIES RAKE TASK
end # ENDS NAMESAPCE DECLARATION
when I run "rake db:insert_properties" this is the error I produce --
rake aborted!
uninitialized constant Property
/Users/stevejobs/Sites/nsrosu/lib/tasks/property_information.rake:39:in `block (3 levels) in <top (required)>'
/Library/Ruby/Gems/2.0.0/gems/nokogiri-1.6.1/lib/nokogiri/xml/node_set.rb:237:in `block in each'
/Library/Ruby/Gems/2.0.0/gems/nokogiri-1.6.1/lib/nokogiri/xml/node_set.rb:236:in `upto'
/Library/Ruby/Gems/2.0.0/gems/nokogiri-1.6.1/lib/nokogiri/xml/node_set.rb:236:in `each'
/Users/stevejobs/Sites/nsrosu/lib/tasks/property_information.rake:21:in `block (2 levels) in <top (required)>'
Tasks: TOP => db:insert_properties
(See full trace by running task with --trace)
I have a Property model with a table set up to accept all of these attributes, so why am I getting this error?
Your rake task needs to boot the Rails environment prior to running. That way you can access the classes.
To do this, you need to run the environment task. To make this happen, change your task definition to
task :insert_properties => :environment do

Resources