Rails 6 Tasks with arguments - ruby-on-rails

// 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"]

Related

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'

rake aborted! Don't know how to build task 'sandbox'

I'm trying to add the sandbox to my rails spree application and have run into this error
(using windows 8/powershell with Rails 4.1.6). I'm going by this manual: https://github.com/spree/spree/issues/411
This link Use older version of Rake
seems to have a similar issue but I am not sure how to take the necessary steps to achieve it.
When I try:
C:\Ruby193\openUpShop> bundle exec rake sandbox
I get:
rake aborted!
Don't know how to build task 'sandbox'
I'm am new to rails and am still not sure how everything works so a throughout explanation
with step by step instructions would be greatly appreciated! Thanks.
you can use a file sandbox.rb
# use example: rake task:sub_task -- --sandbox
if ARGV.any? {|arg| arg == '--sandbox' }
puts "** << USING SANDBOX!! >> **"
# beginning
$sandbox = -> do
ActiveRecord::Base.connection.begin_transaction
end
# end
at_exit do
ActiveRecord::Base.connection.rollback_transaction
end
end
then only you need add at the beginning of your task.rake file
require_relative 'path_to_your/sandbox.rb'
..and add at the beggining of your task code
desc "description task"
task example_task: :environment do
$sandbox.call if $sandbox.present?
...

Rake task working on local machine, not on heroku

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"']

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

How can I tell if Rails code is being run via rake or script/generate?

I've got a plugin that is a bit heavy-weight. (Bullet, configured with Growl notifications.) I'd like to not enable it if I'm just running a rake task or a generator, since it's not useful in those situations. Is there any way to tell if that's the case?
It's as simple as that:
if $rails_rake_task
puts 'Guess what, I`m running from Rake'
else
puts 'No; this is not a Rake task'
end
Rails 4+
Instead of $rails_rake_task, use:
File.basename($0) == 'rake'
I like NickMervin's answer better, because it does not depend on the internal implementation of Rake (e.g. on Rake's global variable).
This is even better - no regexp needed
File.split($0).last == 'rake'
File.split() is needed, because somebody could start rake with it's full path, e.g.:
/usr/local/bin/rake taskname
$0 holds the current ruby program being run, so this should work:
$0 =~ /rake$/
It appears that running rake will define a global variable $rakefile, but in my case it gets set to nil; so you're better off just checking if $rakefile has been defined... seeing as __FILE__ and $FILENAME don't get defined to anything special.
$ cat test.rb
puts(global_variables.include? "$rakefile")
puts __FILE__
puts $FILENAME
$ cat Rakefile
task :default do
load 'test.rb'
end
$ ruby test.rb
false
test.rb
-
$ rake
(in /tmp)
true
./test.rb
-
Not sure about script/generator, though.
The most stable option is to add $is_rake = true at the beginning of Rakefile and use it from your code.
Use of $0 or $PROGRAM_NAME sometimes will fail, for example when using spring and checking variables from config/initializers
You can disable the plugin using environment variable:
$ DISABLE_BULLET= 1 rake some:task
And then in your code:
unless ENV['DISABLE_BULLET']
end
We could ask this
Rake.application.top_level_tasks
In a rails application, this is an empty array, whereas in a Rake task, the array has the task name in it.
top_level_tasks probably isn't a public API, so it's subject to changes. But this is the only thing I have found.

Resources