Ruby on rails specify environment in rake task - ruby-on-rails

I want to create a custom db/seeds file and pass it to a specific environment
desc "Select for bonus"
task :bonus => :environment do
puts "Bonus for: #{pick(User).name}"
end
Is is possible in the task section of my rake task to specify say only the test environment without having to run RAILS_ENV=test rake in my command line?

If all you are doing is seeding the database with this specific task, you just need to establish connection with the right database as part of the task.
desc "Select for bonus"
task :bonus => :environment do
puts "Bonus for: #{pick(User).name}"
ActiveRecord::Base.establish_connection('test')
....
end
ActiveRecord::Base.establish_connection('test') above connects to the test database before running the rest of the steps on that database.
If you are doing lot more complicated things as part of the task, that is possible too. See How do I force RAILS_ENV in a rake task? for some tips.

Related

Run Rake task programmatically with specified environment

I'm setting up a second database with my Ruby on Rails (3) application, so I want to create a rake task to create the second development database. I'm trying to overwrite the rake db:create task such that it does all the database creation that I need. However, it seems I can't find a suitable way to perform this task. I've tried a few approaches - establishing a connection to the database from the URL:
# remove db:create from the list of rake tasks in order to override it
db_create = Rake.application.instance_variable_get('#tasks').delete('db:create')
namespace :db do
task :create do
if Rails.env == "development"
# database.yml contains an entry for secondary_development, this works, as confirmed from rails console
ActiveRecord::Base.establish_connection "postgresql://localhost/secondary_development"
Rake::Task["db:create"].invoke # this does nothing
end
# invoke original db_create task - this works
db_create.invoke
end
end
Another approach was to do:
# remove db:create from the list of rake tasks in order to override it
db_create = Rake.application.instance_variable_get('#tasks').delete('db:create')
namespace :db do
task :create do
if Rails.env == "development"
Rails.env = "secondary_development"
Rake::Task["db:create"].invoke
end
# invoke original db_create task - this doesn't work like this
db_create.invoke
end
end
This time only the secondary_development db:create works and the database is created as desired, but the development database is no longer created using this approach.
From one answer I found elsewhere, I thought that reenabling the task would be necessary, but that didn't change anything here and appears not to be the issue.
Finally, an approach that has worked is:
# remove db:create from the list of rake tasks in order to override it
db_create = Rake.application.instance_variable_get('#tasks').delete('db:create')
namespace :db do
task :create do
if Rails.env == "development"
system("rake db:create RAILS_ENV=secondary_development")
end
db_create.invoke
end
end
The only issue here is that because the rake task is being run via system, the Rails application has to load before being executed, so I'm essentially loading the application twice fully just to run the task - this will be 3 times when I add a test database into the mix.
So, the actual question(s):
Is it possible to run Rake::Task["..."] programmatically with a specified environment?
Why doesn't ActiveRecord::Base.establish_connection work in this way when creating the database? I had success when running this from Rails console.
I managed to find a solution to this. I believe the reason is that .invoke will not always invoke the task, but it will first determine whether it is necessary. Given that rake db:create is run on several occasions within the same task, .invoke deems the subsequent invocations as unnecessary and therefore does not run them. For the desired behaviour, .execute should be used instead.
# remove db:create from the list of rake tasks in order to override it
db_create = Rake.application.instance_variable_get('#tasks').delete('db:create')
namespace :db do
task :create do
if Rails.env == "development"
Rails.env = "secondary_development"
Rake::Task["db:create"].execute # execute rather than invoke
end
# Reset the Rails env to 'development', otherwise it remains as 'secondary_development', which is not what we want (or move this above the if)
Rails.env = "development"
db_create.execute
end
end

enhancing the global environment task rails

On the application I am upgrading from Rails 3.2.22.4 to Rails 4.0.13, the following block of code for enhancing the global environment task has become a road-block by not working on the target Rails version:
Rails.application.class.rake_tasks do
Rake::Task["environment"].enhance do
...
end
end
This works fine on 3.2, but fails with Don't know how to build task 'environment' error message in 4.0.
In 3.2, Rails.application.class.rake_tasks returns a Proc object ( [#<Proc:0x007f978602a470#.../lib/rails/application.rb:301>] ) pointing to this line in the rails codebase. On 4.0, it returns an empty array.
The line referred to in the above Proc object seems to be removed in this commit.
What would the preferred way to enhance the environment rake task be in Rails 4.x?
The above piece of code is in the lib/subdomain/rake.rb file, and it is include with the following code in lib/subdomain/engine.rb:
module Subdomain
class Engine < Rails::Engine
...
rake_tasks do |_app|
require 'subdomain/rake'
end
...
end
end
Rake tasks can't be executed as the command fails with this error. rails server|console commands work ok.
Option 1
If I'm understanding the question properly, something like this should work by placing these tasks in a standard location like lib/tasks/environment.rake. Note: None of this is particularly Rails-specific.
# Re-opening the task gives the ability to extend the task
task :environment do
puts "One way to prepend behavior on the :environment rake task..."
end
task custom: :environment do
puts "This is a custom task that depends on :environment..."
end
task :environment_extension do
puts "This is another way to prepend behavior on the :environment rake task..."
end
# You can "enhance" the rake task directly too
Rake::Task[:environment].enhance [:environment_extension]
The output of this would be:
$ rake custom
This is another way to prepend behavior on the :environment rake task...
One way to prepend behavior on the :environment rake task...
This is a custom task that depends on :environment...
Option 2
However, the question remains as to why :environment needed to be extended. If it's to trigger something before, say, a db:migrate, you might be better off just re-opening the task in question and adding another dependency to that particular task. For example:
task custom: :environment do
puts "This is a custom task that depends on :environment..."
end
task :custom_extension do
puts "This is a new dependency..."
end
# Re-opening the task in question allows you to added dependencies
task custom: :custom_extension
The result of this is:
$ rake custom
This is a new dependency on :custom
This is a custom task that depends on :environment...
C-C-C-Combo Breaker!!
Combining everything, the output would look like this:
$ rake custom
This is another way to prepend behavior on the :environment rake task...
One way to prepend behavior on the :environment rake task...
This is a new dependency on :custom
This is a custom task that depends on :environment...

How to run schema:load on the initial capistrano 3 deploy of my rails app

I would like to run db:schema:load in place of db:migrate on the initial deploy of my rails app.
This used to be fairly trivial, as seen in this stack overflow question, but in Capistrano 3, they have deprecated the deploy:cold task. The initial deploy isn't any different than all subsequent deploys.
Any suggestions? Thanks!
I, too, am new to Capistrano, and trying to use it for the first time to deploy a Rails app to production servers I configured with Puppet.
I finally had to dig into the Capistrano source (and capistrano/bundler, and capistrano/rails, and even sshkit and net-ssh to debug auth problems) to determine exactly how everything works before I felt confidant deciding for myself what changes I wanted to make. I just finished making those changes, and I'm pleased with the results:
# lib/capistrano/tasks/cold.rake
namespace :deploy do
desc "deploy app for the first time (expects pre-created but empty DB)"
task :cold do
before 'deploy:migrate', 'deploy:initdb'
invoke 'deploy'
end
desc "initialize a brand-new database (db:schema:load, db:seed)"
task :initdb do
on primary :web do |host|
within release_path do
if test(:psql, 'portal_production -c "SELECT table_name FROM information_schema.tables WHERE table_schema=\'public\' AND table_type=\'BASE TABLE\';"|grep schema_migrations')
puts '*** THE PRODUCTION DATABASE IS ALREADY INITIALIZED, YOU IDIOT! ***'
else
execute :rake, 'db:schema:load'
execute :rake, 'db:seed'
end
end
end
end
end
The deploy:cold task merely hooks my custom deploy:inidb task to run before deploy:migrate. That way the schema and seeds get loaded, and the deploy:migrate step that follows does nothing (safely) because there are no new migrations to run. As a safety, I test to see if the schema_migrations table already exists before loading the schema in case you run deploy:cold again.
Note: I choose to create the DB using Puppet so I can avoid having to grant the CREATEDB privilege to my production postgresql user, but if you want Capistrano to do it, just add "execute :rake, 'db:create'" before the db:schema:load, or replace all three lines with 'db:setup'.
You'll have to define deploy:cold as basically a duplicate of the normal deploy task but with deploy:db_load_schema instead of deploy:migrations. For example:
desc 'Deploy app for first time'
task :cold do
invoke 'deploy:starting'
invoke 'deploy:started'
invoke 'deploy:updating'
invoke 'bundler:install'
invoke 'deploy:db_load_schema' # This replaces deploy:migrations
invoke 'deploy:compile_assets'
invoke 'deploy:normalize_assets'
invoke 'deploy:publishing'
invoke 'deploy:published'
invoke 'deploy:finishing'
invoke 'deploy:finished'
end
desc 'Setup database'
task :db_load_schema do
on roles(:db) do
within release_path do
with rails_env: (fetch(:rails_env) || fetch(:stage)) do
execute :rake, 'db:schema:load'
end
end
end
end
It might even be better to run the deploy:db_schema_load task independently, as the tasks included in the default deploy might change over time.
I actually using db:setup for fresh deploys because it seeds the database after creating tables:
desc 'Setup database'
task :db_setup do
...
execute :rake, 'db:setup'
...
end

How can I create a rake task that will always run when any Rake task is ran?

From what I remember, in the documentation is specified that in the test environment, the database is always cleared even when you run rake ( with no arguments ). I'd like to achieve such a thing, so that it doesn't matter if I run a task or not, when I run rake, there's always a Rake task being executed. Is this possible? Is this where the default task kicks in?
Create a file called rakefile in the directory you want to run the task from.
This code will make it so that if you just type "rake" my_default_task will run:
task :default => 'my_default_task'
task :my_default_task do
puts "Now I am doing the task that Tempus wants done when he/she types 'rake' in the console."
end
task :my_not_default_task do
puts "This isn't the default task."
end
However, if you typed rake my_not_default_task, then my_default_task would NOT run. If you want it to run regardless here is one thing you can do:
task :default => 'my_default_task'
task :my_default_task do
puts "This is the default task"
end
task :my_not_default_task do
puts "This isn't the default task."
end
Rake::Task['my_default_task'].invoke
The last line in this code ensures that my_default_task runs even when you call some other task, so if you typed rake my_not_default_task the my_default_task'would also run.
EDIT:
When you're working with rails you can put the tasks above in a file in the lib/tasks folder with an extension of .rake and rails will automagically run them when you do rake
Jason Seifer has a real nice tutorial on rake.

Log SQL queries during rake tasks

Similar to 'rails server' that prints every SQL query executed I would like to do the same for rake tasks.
What is the best way to achieve that?
Proper answer is to put this at the beginning of rake task:
ActiveRecord::Base.logger = Logger.new STDOUT
Depending on your environment, Rake will log sql queries just like any Rails process will & in the same logfile. So on your dev box, check your log/development.log file - it will contain your Rake task's queries. If you want queries logged in production, set the log level in your Rake task to DEBUG, and make sure the rake task depends on :environment.
desc "Task with SQL logging"
task :test_log => :environment do
Rails.logger.level = Logger::DEBUG
Your code here...
end
rake db:migrate --trace
The --trace will show details
echo '' > log/development.log
rake db:migrate:redo VERSION=20141017153933
cat log/development.log
I tried the above and couldn't get it to work. Syntax was fine, no errors, but no sql came to stdout (or the log). I'm using rails 3.2. I'm also running in a production environment.
To see the sql queries generated by my rake tasks, I used the technique found at http://eewang.github.io/blog/2013/07/29/how-to-use-rake-tasks-to-generate-migration-sql/
In particular, I just inserted this block in my task before the find() statements that generated the SQL queries I was intersted in:
ActiveRecord::Base.connection.class.class_eval do
# alias the adapter's execute for later use
alias :old_execute :execute
# define our own execute
def execute(sql, name = nil)
print "===== #{sql}\n"
old_execute sql, name
end
end
Then I could see the SQL on stdout. This is not my code - Eugene Wang came up with this technique.
You can create the following task (lib/tasks/db.rake):
task :show_sql do
ActiveRecord::Base.logger = Logger.new STDOUT
end
And use it like so:
$ bin/rake show_sql db:migrate

Resources