I'm trying to make a rake-task in a such way:
require 'open-uri'
namespace :news_parser do
desc 'Parsing news from 6 news sites'
task :parse_news do
load 'lib/news_parser.rb'
ProcherkParser.new.save_novelties
VikkaParser.new.save_novelties
InfomistParser.new.save_novelties
ZmiParser.new.save_novelties
VycherpnoParser.new.save_novelties
ProvceParser.new.save_novelties
end
end
In my lib/news_parser.rb I have classes and instance methods, which perfectly work in a rails console, by doing the following:
load 'lib/news_parser.rb'
ProcherkParser.new.save_novelties
It saves to my db all the information I need. But how can I do it in a rake-task? Any help would be appreciate. Thanks.
Does it work when you replace
task :parse_news do
with
task :parse_news => :environment do
?
It will load your Rails environment before your task, and your code should work just like in the rails console.
Also, you could DRY your code a bit :
require 'open-uri'
namespace :news_parser do
desc 'Parsing news from 6 news sites'
task :parse_news => :environment do
load 'lib/news_parser.rb'
[ProcherkParser, VikkaParser, InfomistParser, ZmiParser, VycherpnoParser, ProvceParser].each do |parser_klass|
parser_klass.new.save_novelties
end
end
end
This is how I am using in my app
namespace :raw_logs do
desc 'Download - Decrypt - Save raw logs'
task process: :environment do
LogItem.create(org_id: 12)
end
end
My rake task is rake raw_logs:process
Related
I am creating a model whose name is the input argument in a rake task. After the rake task, I wish to use the model to insert data.
So for example, I call my rake task with input Apple and the model Apple is created. Then I wish to do Apple.insert_all([{name: x},{name: y}...]) in another rake task but I get NameError: uninitialized constant Apple
Here's a better picture of the flow of what I'm doing
Rake::Task["create:fruit"].invoke("Apple") # create model here
Rake::Task["create:insert"].invoke("Apple") # insert data here but getting error
This is how I process the input in the second rake task:
task :insert, [:name] do |t, args|
fruit = args.name
fruit.classify.constantize.insert_all(xxx)
end
Any suggestions for how to go about this?
I created a new project and tried your code. I think the problem is in this line
fruit.classify.constantize.insert_all(xxx)
The code bellow works and create new records. I use a simple rake command to run it.
create.rake file
namespace :create do
desc "TODO"
task :insert, [:name] do |t, args|
klass = Object.const_get(args.name)
klass.create([{name: 'x'},{name: 'y'}])
p klass.count # testing new records have been saved
end
end
Rakefile file
require File.expand_path('../config/application', __FILE__)
Rails.application.load_tasks
task :default do
Rake::Task["create:insert"].invoke("Apple")
end
In our rails 3.2.12 app, there is a rake task created under lib/tasks. The rake task needs to call a method find_config() which resides in another rails module authentify (module is not under /lib/). Can we include Authentify in rake task and make method find_config() available to call in the rake task?
Here is what we would like to do in the rake task:
include Authentify
config = Authentify::find_config()
Thanks for comments.
require 'modules/module_name'
include ModuleName
namespace :rake_name do
desc "description of rake task"
task example_task: :environment do
result = ModuleName::method_name()
end #end task
end
This works for me. Since your Module is not in /lib you might have to edit how it is required. But it should work. Hope it helps.
PLEASE PAY ATTENTION TO THIS AND SAVE SOME RANDOM HEADACHES!! .
Don't include your module before your namespace:
include YourModule
namespace :your_name do
desc 'Foo'
task foo: :environment do
end
end
or inside your namespace:
namespace :your_name do
include YourModule
desc 'Foo'
task foo: :environment do
end
end
as that will include your module for the whole app and it could bring you a lot of troubles (like me adding in the module some :attr_accessors and breaking factory-bot functioning or other things it has happened in the past for this same reason).
The "no issues" way is inside of your task's scope:
namespace :your_name do
desc 'Foo'
task foo: :environment do
include YourModule
end
end
And yes, if you have multiple tasks, you should include in each of them:
namespace :your_name do
desc 'Foo'
task foo: :environment do
include YourModule
end
desc 'Bar'
task bar: :environment do
include YourModule
end
end
or simply call your method directly if you're only calling a method once in the task:
namespace :your_name do
desc 'Foo'
task foo: :environment do
YourModule.your_method
end
desc 'Bar'
task bar: :environment do
YourModule.your_method
end
end
How to require a Rails service/module in a Rake task?
I had the same problem and manage to solve it by requiring the rails files inside the rake task.
I had a rake task named give_something defined in the file lib/tasks/a_task.rake.
Within that task I needed to call the function give_something from the module AService which lives in the file app/services/a_service.rb
The rake task was defined as follows:
namespace :a_namespace do
desc "give something to a list of users"
task give_something: :environment do
AService.give_something(something, users)
end
end
I was getting the error: uninitialized constant AService
To solve it I had to require the module not at the beginning of the file a_task.rake, but inside the rake task:
namespace :a_namespace do
desc "give something to a list of users"
task give_something: :environment do
require 'services/a_service' # <-- HERE!
AService.give_something(something, users)
end
end
In rails 5.x.x we can do as-
Module file exist her app/lib/module/sub_module.rb like-
module Module
module SubModule
def self.method(params1, params2)
// code goes here...
end
end
end
and my rake_task presented here /lib/tasks/my_tasks.rake as-
namespace :my_tasks do
desc "TODO"
task :task_name => :environment do
Module::SubModule.my_method(params1, params2)
end
end
Note:- the above task file presented in outer lib not in app/lib
Now run the task using following command-
rake my_tasks:task_name
from app directory not from rails console
That worked for me !!!
In my lib/tasks folder I added a new .rake file.
In the rake task, I am doing this:
p = Post.new( ....)
p.save!
When I run my task, I get the error:
rake aborted!
uninitialized constant Post
What do I have to do to import my Post model?
I'm thinking you're probably missing the environment declaration. This is necessary in order for Rake to know about your Rails environment. Your rake task call should look something like this:
task :my_rake_task => [:environment] do
# Your code here
end
Let me know if that solves the problem!
You want to make the task dependent on the rails environment. You can do so by specifying the => :environment after the task declaration as such:
namespace :my_task do
desc "an example task"
task :create_post => :environment do
Post.new .... # the rest of the implementation
end
end
I'm trying to test a rake task and it uses an active record in it.
require 'spec_helper'
require 'rake'
load File.join(Rails.root, 'lib', 'tasks', 'survey.rake')
describe "survey rake tasks" do
describe "survey:send_report" do
it "should send a report" do
Rake::Task['survey:send_report'].invoke
end
end
end
When I run this spec rspec spec/lib/survey_spec.rb, I get this error "
RuntimeError:
Don't know how to build task 'environment'
How do I load the :enviroment task inside by example spec?
I think you should first load the tasks:
require 'rake'
MyRailsApp::Application.load_tasks
and then invoke your task:
Rake::Task['survey:send_report'].invoke
I suspect the problem is that your survey:send_report task depends on :environment but you haven't loaded the file that defines the :environment task. That'll be in rails somewhere, and your main Rakefile loads it.
So, I think if you change
load File.join(Rails.root, 'lib', 'tasks', 'survey.rake')
to
load File.join(Rails.root, 'Rakefile')
it'll work.
Sounds like your take task may need the Rails environment to be loaded. You can stub this out by adding this line to your before(:all) hook:
Rake::Task.define_task(:environment)
Is your task adding the :enviroment to do it before? In your .rake file you should have something like this:
namespace :survey do
# ...
task :send_report => :enviroment do
# ... stuff
end
This is because you need to load the full enviroment to do that task. You can check this railcast to get more information http://railscasts.com/episodes/66-custom-rake-tasks
I tried putting my script in a class that inherited from my model, like so:
class ScriptName < MyModel
But when I ran rake my_script at the command-line, I got this error:
rake aborted!
uninitialized constant MyModel
What am I doing wrong?
Also, should I name my file my_script.rb or my_script.rake?
Just require the file. I do this in one of my rake tasks (which I name my_script.rake)
require "#{Rails.root.to_s}/app/models/my_model.rb"
Here's a full example
# lib/tasks/my_script.rake
require "#{Rails.root.to_s}/app/models/video.rb"
class Vid2 < Video
def self.say_hello
"Hello I am vid2"
end
end
namespace :stuff do
desc "hello"
task :hello => :environment do
puts "saying hello..."
puts Vid2.say_hello
puts "Finished!"
end
end
But a better design is to have the rake task simply call a helper method. The benefits are that it's easier to scan the available rake tasks, easier to debug, and the code the rake task runs becomes very testable. You could add a rake_helper_spec.rb file for example.
# /lib/rake_helper.rb
class Vid2 < Video
def self.say_hello
"Hello I am vid2"
end
end
# lib/tasks/myscript.rake
namespace :stuff do
desc "hello"
task :hello => :environment do
Vid2.say_hello
end
end
All I had to do to get this to work was put my requires above the task specification, and then just declare the :environment flag like so:
task :my_script => :environment do
#some code here
end
Just by doing that, gave me access to all my models. I didn't need to require 'active_record' or even require my model.
Just specified environment and all my models were accessible.
I was also having a problem with Nokogiri, all I did was removed it from the top of my file as a require and added it to my Gemfile.