Rails script access model - ruby-on-rails

i need a script to be able to access my model. I found a post about this which suggested doing
require "#{ENV['RAILS.root']}/config/environment.rb"
in the top of my script. then i can run ruby script/my_script.rb to run it. But this gives me the error
/Users/my_name/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require': no such file to load -- /config/environment.rb (LoadError)
what am i doing wrong

I think ENV['RAILS.root'] will be set after the environment is loaded. You can try
require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
However, a more commonly used idiom is writing Rake task. For example, create a file named lib/tasks/mytask.rake:
task :mytask => :environment do
# Do something with your model
end
Then execute rake mytask. The environment task will automatically load the Rails environment.

I found my own answer. forget what i said to include in the top. put this instead
ENV['RAILS_ENV'] = ARGV.first || ENV['RAILS_ENV'] || 'development'
require File.expand_path(File.dirname(__FILE__) + "/../config/environment")

Related

rake aborted! cannot load such file Ruby on Rails

I am trying to run a ruby file that updates the database using the rake task . But overtime I run the code, I get an error saying :
rake aborted!
cannot load such file -- app/services/insert_data
The ruby file 'insert_data' is located under the app directory in a folder named 'services'
Here is the rake task I created to run it:
require 'app/services/insert_data'
namespace :record_generate do
task :test do
ruby "app/services/insert_data"
end
end
Please help in removing this error.
To be able to use Rails environment within a rake task you need to declare that:
namespace :record_generate do
task :test => :environment do |_, args|
ruby "app/services/insert_data"
end
end
I think you should try placing your app/services/insert_data inside the script directory. I'm assuming that your ruby file is not a rails model with logic. I would try this.
Get your file and place it in the /script/ directory.
Place these line of code at the top of your file
#! /usr/bin/env ruby
require_relative "../config/environment"
Now on your command line you can do execute this:
rails runner name_of_your_file
That is one way of doing it. If you specifically need to use a rake task I can try posting an answer for that too.
Inside your task :test block try -
Rake.application.rake_require "#{Rails.root}/app/services/insert_data"

Rails: Where to put script/function that runs only when starting server?

I am using the Predictor gem for a recommendation system. I want to write a script to initialize the recommender when running rails server. If I put the script into the initializers/dirctory, it will also be run whenever rake is executed.
Is there a way to add scripts are executed only when running rails server?
Thought it is not recommended, you could update the file bin/rails:
#!/usr/bin/env ruby
puts "Write your custom code here"
APP_PATH = File.expand_path('../../config/application', __FILE__)
require_relative '../config/boot'
require 'rails/commands'
This runs whenever rails s, rails c or any rails command is called.

Rails app object in console versus in scripts

I'm trying to use the app object inside a Ruby script that loads the Rails environment but I have only problems...
Script looks like this:
ENV['RAILS_ENV'] = ARGV.first || ENV['RAILS_ENV'] || 'development'
require ::File.expand_path('../config/environment', __FILE__)
app = Rails.application
puts app.users_path(21)
I get
undefined method `users_path' for #<BacklinkHealth::Application:0x007fd6fac80d60> (NoMethodError)
If I include Rails.application.routes.url_helpers then it's ok...
but the problem is that I also need to call app.get and I don't know how to enable that.
Why is this app object so different in a script than it is in Rails command line?
I see that app is a method in console and it returns an instance of ActionDispatch::Integration::Session while Rails.application is BacklinkHealth::Application. So the solution is:
app = ActionDispatch::Integration::Session.new(Rails.application)

After installing minitest rails, rake test doesn't do anything

The question title pretty much sums it up, but here's a more chronological description:
I started a new rails 3.2.9 app, did not pass any special options (ie. did not skip test unit).
I added minitest-rails to the gemfile and ran bundle install.
I deleted the contents of the test folder, and ran rails g mini_test:install.
Now if I run rake test, nothing happens.
I can make my own rakefile and specify TestTask manually, but I don't get the options to do things like rake test:controllers that are supposed to come built-in unless I manually dupe all that.
Has anyone else run into this?
Make sure you add require 'test_helper' on top of your test file. e.g.
require 'test_helper'
class UsersControllerTest < ActionController::TestCase
test "should pass" do
assert true
end
end
The auto generated test_helper file I have looks like that:
ENV["RAILS_ENV"] ||= "test"
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
class ActiveSupport::TestCase
ActiveRecord::Migration.check_pending!
fixtures :all
end
Glad you are making the switch to MiniTest! I may be able to help you get on the right track.
Honestly, I would avoid rake entirely. Try running a test from the command line to make sure your testing suite is working.
ruby -Itest test/unit/something.rb
After you know your tests are passing then get guard-minitest and set it up to watch your files. When you save a change it will automatically run the test for you. The worst part of minitest and guard is the set up but once you get it going right you'll never want to go back.
https://github.com/guard/guard-minitest
Cheers
I guess you had not run/generate any controller or scaffold command so far.
Once you create a scaffold / controller / model and migrate the database your rake test will start working
Regarding rake test:controllers, when I tried to list out with rake -T it is not still listing
You may need to register minitest-rails as the default testing engine by adding the following to your config/application.rb file:
config.generators do |g|
g.test_framework :mini_test
end
After that, you can run controller tests with the following:
rake minitest:controllers

whenever gem schedule.rb file: doesn't recognize RAILS_ROOT variable

In schedule.rb file, the statement:
require "#{RAILS_ROOT}/config/environment.rb"
every "10 10 2 * * *" do
command "mysqldump -u #{#db_username} -p#{#db_password} --single-transaction #{#db_name} > #{#backup_Path}/#{#db_name}.sql 2> log/error_crontab.log"
end
When i try to execute the whenever cmd from terminal, getting the following error:
config/schedule.rb:48:in `initialize': uninitialized constant Whenever::JobList::RAILS_ROOT (NameError)
from /usr/local/lib/ruby/gems/1.9.1/gems/whenever-0.7.0/lib/whenever/job_list.rb:19:in `instance_eval'
from /usr/local/lib/ruby/gems/1.9.1/gems/whenever-0.7.0/lib/whenever/job_list.rb:19:in `initialize'
from /usr/local/lib/ruby/gems/1.9.1/gems/whenever-0.7.0/lib/whenever.rb:16:in `new'
from /usr/local/lib/ruby/gems/1.9.1/gems/whenever-0.7.0/lib/whenever.rb:16:in `cron'
from /usr/local/lib/ruby/gems/1.9.1/gems/whenever-0.7.0/lib/whenever/command_line.rb:40:in `run'
from /usr/local/lib/ruby/gems/1.9.1/gems/whenever-0.7.0/lib/whenever/command_line.rb:7:in `execute'
from /usr/local/lib/ruby/gems/1.9.1/gems/whenever-0.7.0/bin/whenever:38:in `<top (required)>'
from /usr/local/bin/whenever:19:in `load'
from /usr/local/bin/whenever:19:in `<main>'
i am using the require statement to get the dynamic values from the form to schedule the job. Please help to solve this issue?
Note: i have seen the following stackoverflow queries:
How to detect Rails environment inside whenever
Following this thread to get dynamic values, but facing problem with require statement.
Rails - Whenever gem - Dynamic values
Ruby/Rails - Whenever gem - Loop cron tasks
config file in schedule.rb with Rails Whenever gem?
Whenever doesn't require or depend on Rails at all, so when it runs, RAILS_ROOT is not defined, however because whenever's schedule.rb is generally kept in /config/schedule.rb, we can make an assumption that it is in a rails project, and set our own RAILS_ROOT like this:
# in schedule.rb
RAILS_ROOT = File.dirname(__FILE__) + '/..'
Edit: in the case that you actually need Rails loaded, do this:
# in schedule.rb
# this will require config/environment and load your entire rails environment
require File.expand_path(File.dirname(__FILE__) + "/environment")
The whenever developer already answered this question, check this out https://github.com/javan/whenever/issues/81
Javan Whenever no longer attempts to load your Rails environment. However, it does automatically set a path variable to the directory whenever was executed from. This should work just the same:
set :output, "#{path}/log/cron.log"
In Rails 4 try with:
require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
in your schedule.rb file.
This way you also have access to all your active-record models and initializers.

Resources