Rake task working on local machine, not on heroku - ruby-on-rails

Here is my simple rake task :
desc 'Create objects from csv'
task :add_missing_information_from_url, [:url] => [:environment] do |t, args|
url = args[:url]
puts "STARTED"
CSV.new(open(url), :headers => :first_row).to_enum.with_index(1).each do |line, i|
user = User.find(line['id'])
next if user.nil?
user.flag = true
user.save
puts "#{i} - #{user.firstname}"
end
end
For starters doesn't do anything smart. But for some reason this doesn't work on Heroku. This is how I execute the task (my namespace is dbs):
heroku run rake dbs:add_missing_information_from_url['http://lvh.me/file.csv']
Or on dev machine :
bundle exec rake dbs:add_missing_information_from_url['http://lvh.me/file.csv']
This is the only output I get from the console when running heroku task :
Running `rake dbs:add_missing_information_from_url[http://lvh.me/file.csv]` attached to terminal... up, run.7246
And returns to my shell after it has executed with nothing printed, nor the user objects get saved.
However when I run it on my dev machine, all works fine, starting by printing STARTED onwards.
What am I doing wrong here?

Is it me or does your log actually outputs this :
Running `rake dbs:add_missing_information_from_url[http://lvh.me/file.csv]` attached to terminal... up, run.7246
If you take a closer look at the argument in the [http://lvh.me/file.csv], it appears not to be a string. You would want your log to output ['http://lvh.me/file.csv'].
So I suggest you try running your task like this :
heroku run rake dbs:add_missing_information_from_url['"http://lvh.me/file.csv"']

Related

Rails 6 Tasks with arguments

// This is a question for Ruby on Rails
I have a Rails Tasks that should take arguments from command line.
Looks like this :
task update: :environment do
if (ARGV[1] == "DEBUG")
DEBUG = true
else
DEBUG = false
end
Now I can run the command line :
rails call:update DEBUG
and it works !
But after the task was finished I got also the message :
rails aborted!
Don't know how to build task 'DEBUG' (See the list of available tasks with `rails --tasks`)
I looking already around the community, but all what I found was quite old and seems not to be compatible with Rails 6 ! So thats the reason why I asking here.
I try with the code you shared above I got the same error of rake abort.
its Comming because they way you calling the rake task with the argument it assume the DEBUG is another task so it try to find and give this error.
Here is proper way of doing it
I did some modification in the code to get rid of the error use the following code it will work perfectly
task :update, [:value] => [:environment] do |t, args|
if (args[:value] == "DEBUG")
DEBUG = true
p "Value is True"
else
DEBUG = false
p "Value is False"
end
end
it works perfectly
You can also put this task in the namespace and then call it from there as well
namespace :debug_task do
# task code here what I mentioned above
end
and then call it to form the terminal like this
rake debug_task:update["DEBUG"]

Why doesn't it know how to build this task?

So I have the following task in rails running on jruby:
desc "Creates a new site with args: name, api_url (must be http(s)://api.something.com/v1/ - note the ending slash), api_key"
task :add_new_site, [:name, :api_url, :api_key] => :enviroment do | t, args |
if !Site.find_by_site_name(args[:name])
new_site = Site.new(site_name: args[:name], site_api_url: args[:api_url], site_api_key: args[:api_key])
if new_site.save!
puts "Created new Site: " + args[:name]
end
else
puts "This site already exists."
end
end
When I run it as such:
$ bin/rake add_new_site['sample', 'sample.com', 'addasdsd']
rake aborted!
Don't know how to build task 'add_new_site[sample,'
You can see the error.
What am I doing wrong to receive this? I have other tasks that take one argument and they seem to work fine.
Note: yes this is in a .rake and not a .rb file
Update One:
You can see from the below out put that I saw what was required of this task, and I tried it and it still failed:
$ bin/rake -T add_new_site ['sample', 'sample.com', 'addasdsd']
rake add_new_site[name,api_url,api_key] # Creates a new site with args: name, api_url (must be http(s)://api.something.com/v1/ - note the ending slash), api_key
$ bin/rake add_new_site['sample','sample.com','addasdsd']
rake aborted!
Don't know how to build task 'enviroment'
Tasks: TOP => add_new_site
(See full trace by running task with --trace)
I seem to be getting a different error?
You have a typo: enviroment instead of environment
That's why you are getting this error:
rake aborted!
Don't know how to build task 'enviroment'

Custom Rails rake task to work with database

I need to make a custom Rails 4 rake task to delete all records in database using ip:
task :delete_records, [:ip] => :environment do |t, args|
User.destroy_all(ip: args.ip)
end
I try to execute it using the following command:
bundle exec rake delete_records["127.0.0.1"] but I've the error:
no matches found: delete_records["127.0.0.1"]
How can I fix it? Thank in advance!
I'm guessing you used this answer for help - although we've done rake tasks before, we've never used one with arguments like this
--
Test
We've created custom rake tasks before - they reside in lib/tasks
I would test out yours by doing the following:
#lib/tasks/your_task.rake
desc "Remove all records for particular IP"
task :delete_records, [:id] => :environment do
args.with_defaults(:ip => "127.0.0.1")
User.destroy_all ip: args.ip
end
If this does not work, it will mean there's something wrong with the definition of your task (it's not in the correct folder or something)
The above should determine if your argument definition is the issue; if it isn't you should let me know so we can work to fix it

run rake task inside rails application

I want to run asset precompile task inside the rails application,As I had many dependencies who will change the code,in that case all the time whenever they change i need to run the script as I cant give server access to them so I am providing the GUI for them from that they alone can run the script,so,I have built UI to run the task with some parameter like
system("Template='#{params[:template]}' Theme='#{params[:theme]}' rake assets:precompile)
I am getting two values from UI(params[:template],params[:theme]).Another thing i want to run this task in another path(site path) means Admin side UI is there that task should execute in Site directory,
if(params[:theme_script] == "true")
template=Template.where(:name => params[:template]).first
if template
theme = template.themes.where(:name => params[:theme]).first
if theme
# Dir.chdir "#{THEMEPATH}"do
# `Template="#{template.name}" Theme="#{theme.name}" rake assets:precompile`
# end
# sleep 10
# system("#{Rails.root.to_s}/lib/shell_script.sh")
# RunRake.run_rake(template.name,theme.name)
# Dir.chdir "#{THEMEPATH}"do
# Rake::Task['assets:precompile'].invoke
# end
ENV["Template"] = template.name
ENV["Theme"] = theme.name
precompile_task = "bundle exec rake assets:precompile --trace 2>&1"
output = Dir.chdir(THEMEPATH) { %x[ #{precompile_task} ] }
flash[:notice] = "Asset created successfully"
else
flash[:notice] = "U have enter invalid data"
end
else
flash[:notice] = "U have enter invalid data"
end
end
This is my code am checking multiple condition and am allowing to execute the task.
I have tried this code by putting in controller and lib, but this is not working.
I have tried with shell script also.
Could please anyone can help me.
You can just setup an environment variable for rails, and then issue #invoke method from a controller. So, prepare the files:
gemfile
gem 'rake'
config/initializers/rake.rb:
Rake.load_rakefile Rails.root.join( 'Rakefile' )
app/controllers/your_controller:
ENV["Template"] = template.name
ENV["Theme"] = theme.name
Rake::Task[ 'assets:precompile' ].invoke
Issue bundle install, then run console rails c, and type:
Rake::Task.tasks.map(&:name).grep 'assets:precompile'
# => ["assets:precompile"]
As you can see, the task assets:precompile is loaded successfully. Then just issue the action for the controller.
To run the task for an other rails app you shell run also the other ruby instance, similar to as you had done:
system( "other_app_run.sh '#{template.name}' '${theme.name}'" )
other_app_run.sh:
#!/bin/bash
source "$HOME/.rvm/scripts/rvm"
cd /other/app/path
export Template="$1"
export Theme="$2"
rake assets:precompile

How do I use Rails clockwork gem to run rake tasks?

What is the syntax for calling rake tasks from clockwork? I've tried all kinds of syntax, and nothing seems to work. (I'm specifically interested in clockwork because Heroku's supporting it.)
Here's my clock.rb, using the same syntax that the whenever gem uses:
module Clockwork
puts "testing clockwork!"
every(30.seconds, 'Send Messages') {
rake 'scheduler:send_messages'
}
end
And here's my rake task in scheduler.rake:
task :send_messages => :environment do
puts "rake task run successfully!"
end
And here's what happens when I start a clockwork process:
$ clockwork lib/clock.rb
testing clockwork!
I, [2012-07-16T14:42:58.107245 #46427] INFO -- : Starting clock for 1 events: [ Send Messages ]
I, [2012-07-16T14:42:58.107364 #46427] INFO -- : Triggering 'Send Messages'
attempting to run rake task!
E, [2012-07-16T14:42:58.107437 #46427] ERROR -- : undefined method `rake' for Clockwork:Module (NoMethodError)
This runs every 30 seconds. As you can see, the clock.rb is executed successfully. But I can't for the life of me figure out the syntax to run a rake task. The clockwork readme is no help, unfortunately:
https://github.com/tomykaira/clockwork
rake is not a method, so you can't invoke it like that here.
You can either shell out and invoke it, something like
every(30.seconds, 'Send Messages') {
`rake scheduler:send_messages`
}
or rather invoke a new detached process using the heroku API. This is my preferred method right now:
Heroku::API.new.post_ps('your-app', 'rake scheduler:send_messages')
Heroku::API is available from heroku.rb: https://github.com/heroku/heroku.rb
You can add the following method to your clock.rb file:
def execute_rake(file,task)
require 'rake'
rake = Rake::Application.new
Rake.application = rake
Rake::Task.define_task(:environment)
load "#{Rails.root}/lib/tasks/#{file}"
rake[task].invoke
end
and then call
execute_rake("your_rake_file.rake","your:rake:task")
in your handler
You can pass in a block to every that executes your rake task:
every(1.day, "namespace:task") do
ApplicationName::Application.load_tasks
Rake::Task['namespace:task'].invoke
end
Invoking the task using Rake::Task['...'].invoke works well the first time, but the task need to be reenabled to be invoked again later.
ApplicationName::Application.load_tasks
module Clockwork do
every(10.minutes, "namespace:task") do
Rake::Task['namespace:task'].invoke
Rake::Task['namespace:task'].reenable
end
end
Otherwise the task will be invoked the first time, but no more after that until the clockwork process is restarted.

Resources