Rails not including modules on Models when run in Rake - ruby-on-rails

In Rails 3.2.16, I have a model:
class Person < ActiveRecord::Base
module Testmodule
def testmethod
puts "It's included"
end
end
include Testmodule
end
when I run bundle exec rails c, I can type Person.new.testmethod and get the expected result
If I create a small rake task:
task :myraketask => :environment do
Person.new.testmethod
end
I receive an error that testmethod isn't defined on Person.
However, if I explicitely set eager loading in the rake task, it will work:
task :myraketask => :environment do
Rails.application.eager_load!
Person.new.testmethod
end
If I create a brand new Rails project, I cannot replicate the error. Can anybody point out to me what may be wrong in my project that is causing the error in the first rake task?

Related

Rails dynamically create model and use it

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

Cannot load namespaced model when invoking rake task

I got a rake task which invokes other rake tasks, so my development data can be easily reset.
the first rake task (lib/tasks/populate.rake)
# Rake task to populate development database with test data
# Run it with "rake db:populate"
namespace :db do
desc 'Erase and fill database'
task populate: :environment do
...
Rake::Task['test_data:create_company_plans'].invoke
Rake::Task['test_data:create_companies'].invoke
Rake::Task['test_data:create_users'].invoke
...
end
end
the second rake task (lib/tasks/populate_sub_scripts/create_company_plans.rake)
namespace :test_data do
desc 'Create Company Plans'
task create_company_plans: :environment do
Company::ProfilePlan.create!(name: 'Basic', trial_period_days: 30, price_monthly_cents: 4000)
Company::ProfilePlan.create!(name: 'Professional', trial_period_days: 30, price_monthly_cents: 27_500)
Company::ProfilePlan.create!(name: 'Enterprise', trial_period_days: 30, price_monthly_cents: 78_500)
end
end
when I run bin/rake db:populate then i get this error
rake aborted! LoadError: Unable to autoload constant
Company::ProfilePlan, expected
/home/.../app/models/company/profile_plan.rb to define it
but when I run the second rake task independently it works well.
The model (path: /home/.../app/models/company/profile_plan.rb)
class Company::ProfilePlan < ActiveRecord::Base
# == Constants ============================================================
# == Attributes ===========================================================
# == Extensions ===========================================================
monetize :price_monthly_cents
# == Relationships ========================================================
has_many :profile_subscriptions
# == Validations ==========================================================
# == Scopes ===============================================================
# == Callbacks ============================================================
# == Class Methods ========================================================
# == Instance Methods =====================================================
end
Rails 5.0.1
Ruby 2.4.0
The App was just upgraded from 4.2 to 5
It works when I require the whole path:
require "#{Rails.root}/app/models/company/profile_plan.rb"
But this seems strange to me, because in the error message rails has the correct path to the Model. Does someone know why I have to require the file when invoked from another rake task?
Thank you very much
Well, it seems that rake doesn't eager load, so when you call the create_company_plans.rake alone it loads the referred objects, however when you invoke it from another rake, it doesn't know you will need them and so they are not loaded.
You can take a look at this other QA which was similar to yours.
I think maybe you don't need to require the whole path, just:
require 'models/company/profile_plan'
From what I understand, you can probably overcome the problem by reenable ing and then revoke ing the task as given below. Pardon me if this doesn't work.
['test_data:create_company_plans', 'test_data:create_companies'].each do |task|
Rake::Task[task].reenable
Rake::Task[task].invoke
end
There is more info on this stackoverflow question how-to-run-rake-tasks-from-within-rake-tasks .

How to integrate my own scraper in Rails app?

I have just created a Rails app with a model app/models/post.rb and have written a scraper scrapers/base_scraper.rb (class BaseScraper) that collect data from the target site to the hash variable data. Now I want to insert values of data into the Post model. How to do it properly in Rails? I have heard smth about Rake but have no idea how to utilize it properly. Help me please!
Assuming that data stores just one post and that each of the key stored in the datahash are valid Post fields (column_name), you can do simply this:
Post.create(data)
If you want to launch the whole process from console, you can create a rake task under lib/tasks directory of your process with the following:
# scraper.rake
namespace :scraper do
desc "Run scraper"
task :run => :environment do
data = BaseScraper.your_collect_data_class_method
Post.create(data) if data
end
end
task :default => 'scraper:run'
And then run it from console as a rake task with rake scraper
Of course I also assume that scrapers dir is in your Rails load path.
If not, add it to your application.rbfile.
# application.rb
...
module YourApp
class Application < Rails::Application
...
config.autoload_paths += Dir["#{config.root}/scrapers/"]
...
end
end

Is it possible to include modules in rake task and make its methods available for the task in rails app?

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 !!!

How do I access one of my models from within a ruby script in the /lib/ folder in my Rails 3 app?

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.

Resources