How to run some default commands after firing the Rails console? - ruby-on-rails

I need to run a few commands whenever I start my Rails console, like setting up the logger, or to set the time to my time zone.
Right now I'm copying and pasting these commands after Rails is started. Can I write a script to make these commands run automatically after IRB is started?

Rails' console is IRB. IRB supports an .irbrc file, which contains initialization information and settings.
Read "https://stackoverflow.com/questions/123494/whats-your-favourite-irb-trick" and "My .irbrc for console/irb" for ideas.

I wrote an extended answer to this in another question but the short answer is that if you are using Rails 3 or above you can use the console method on YourApp::Application to make it happen:
module YourApp
class Application < Rails::Application
...
console do
Time.zone = A.info.time_zone
end
end
end

Related

Does Rails initializers gets called when I run rails console

I want to put my chargify conf inside the initializer,
but I found the initializer won't execute in my rails c, is there a way to invoke my initializers so I can test in my console?
Chargify.configure do |c|
c.api_key = "keykey"
c.subdomain = "test-site"
end
The config/initializers will execute, but only once, on initial load. So if you're making changes to config/initializers while the console is running you won't see the results of those changes happening.
Your best option is to stop and restart rails c, or you can type the reload! command in the console.
Also, if you are using spring that will sometimes prevent changed initializers from reloading. in that case do spring stop before you restart the console.
Yes, every .rb file in config/initializers is run whenever you run the console, run a rake task, or run your tests. Additonally, the environment configuration (config/environments) is run before the initializers.
Apparently not anymore unless you disable spring:
export DISABLE_SPRING=1

.bashrc equivalent for rails console?

When I'm using the rails console I like having a clear! command along side the reload! command, so every time I launch the rails console I write
def clear!
system('clear')
end
When I repeat behavior in my bash shell I add it to my ~/.bashrc file. Is there a similar way for me to do this for my rails console?
Create a file in your home directory named ~/.irbrc. Inside, define any functions or settings you want to be applied to your irb.
Here's an example that explains what I mean.
You can do this with Pry if you use that instead of irb. You can configure custom commands in a ~/.pryrc
Pry.config.commands.command "clear!", "Clears the display" do |*args|
system("clear")
end
See pry-rails

Delayed_job and Prawn scripts

How do I run Prawn scripts with Delayed_job.
(Currently using Bj but not supported in Rails3)
This code does not work.
/lib/report_job.rb
class ReportJob < Struct.new(:prawn_script_name , :account_id )
def perform
bundle exec rails runner "#{Rails.root}/jobs/#{prawn_script_name}.rb #{#current_user.account_id} "
end
/reports_controller.rb
def generate_report(prawn_script_name)
Delayed::Job.enqueue(ReportJob.new("#{prawn_script_name}.rb","#{#current_user.account_id}"))
end
delayed_job table is populated as expected.
--- !ruby/struct:ReportJob
prawn_script_name: statements.rb
account_id: '18'
Error in last_error field.
{undefined method `runner' for ReportJob:0xc28f080
Any suggestions?
I think there are several misunderstandings here:
you meant to call runner from outside your app, e.g., in a shell script or command line. in other words, bundle exec rails runner are all commands and arguments of commands, not ruby methods or variables. runner is the first expression that is eval'd inside your perform method, hence your error.
rails runner just brings up your apps environment and evals the string or path argument given.
note account_id within the perform task, another mistake in your code I guess.
What you wanted to do could be a simple system call.
It seems your prawn script needs the environment, so simply calling
system "ruby #{Rails.root}/jobs/#{prawn_script_name}.rb #{account_id}"
won't work.
Now you could surely execute the script with runner from your project directory.
system "bundle exec rails runner #{Rails.root}/jobs/#{prawn_script_name}.rb #{account_id}"
but doing this via a system call within your environment is quite redundant. Delayed jobs already have access to your rails environment. so just simply load them.
class ReportJob < Struct.new(:prawn_script_name , :account_id )
def perform
load "#{Rails.root}/jobs/#{prawn_script_name}.rb"
end
end
hope this helps

Expose Rails App Environment to Ruby Script

Out of pure curiosity, I am wondering if it's possible (no doubt it is) to 'hook into' a Rails Application's environment. So for example, say I want to create a cron script (I don't) that operates some sort of maintenance on a Rails app, and I want to write it in Ruby and using all of the nice code that I already have, for example, User.find etc.
Is this possible, and if so, how?
I'm just curious, as I feel I would eventually want to do this for some reason or other.
I'm currently on Rails 3 with Ruby 1.9.1, in case it matters.
This is certainly possible. Here is a good writeup on how to do that: How to run a rake task from cron
Take a look at the Rails::Railtie class. If you need to run code code when you start up your app, this is a way to do it. Here's a very simple example.
From the beginning of Rails there is ./script/runner, designed exactly for such kind of problems.
In Rails 3 you call it as: ./script/rails runner "puts User.find(:all).map(&:inspect)"
Try ./script/runner --help or ./script/rails runner --help
As the argument to the runner you provide a filename or just a code.
It's often more useful than preparing a Rake task, because you can execute just one-time actions:
ssh prod#example.com "cd rails/app && ./script/runner -e production 'puts User.count'"
You could either use script/rails runner as suggested by Arsen7 or you could write your own script in which you load the app environment in the beginning:
require 'config/environment'
is actually everything you need.
To have your script working in a cron job, make sure that it is executable (chmod u+x) and that it starts with a correct shebang line (#!/usr/bin/env ruby or whatever is appropriate for your situation).
yeah just require these file at top of your script file
require 'config/boot.rb'
require 'config/application.rb'
Rails.application.require_environment!
Now you'll have access to your models

Log your SQL in Rails application inside unit test

I want to install a logger so that I can dump all executed SQL of my rails application. Problem is, such logger is associated with AbstractAdapter which initialized very soon under test mode, and thus cannot be set by my initializer code.
I try to put
ActiveRecord::Base.logger = MyCustomLogger.new(STDOUT)
in the end of environment.rb like someone advised but it only works when being run in console environment (kicked by script/console), not when run under test mode.
I wonder if there is any way to config such logger so that I will sure to be invoked under any environment (test, development, production, console)
Creating the logger in config/environment.rb should work. I get SQL logging on standard output when I run unit tests if I put the following line in either config/environment.rb or config/environments/test.rb:
ActiveRecord::Base.logger = Logger.new(STDOUT)
Does your MyCustomLogger class do anything special that causes it to fail during tests? Does it work better if you use Logger.new(STDOUT) instead?
In test/test_helper.rb, before loading config/environment.rb, add:
RAILS_DEFAULT_LOGGER = MyCustomLogger.new(STDOUT)
Relevant code in railties for 2.3 railties/lib/initializer.rb#L35. Not sure how to do it with Rails 3.0 yet. It looks like you need to call Rails#logger=, but I can't find a good spot for it yet.
The best way as far as I can found is to put such code in initializers folder. This way, regardless of the running environment, the logger is always properly installed. And no, on my mac osx Rails 2.3.2 on ruby 1.8.7, if I put ActiveRecord::Base.logger=... inside environment.rb then the logger is not properly installed, since the logger that the Sql Connection used to dump SQL was installed and cached before that.

Resources