Expose Rails App Environment to Ruby Script - ruby-on-rails

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

Related

Run Rails commands outside of console

With my large application, the Rails console takes a while to load up. Is there a way to single commands more easily?
I'd also like to be able to automate stuff, and echo "query" | rails console isn't a great way to do things.
Thoughts?
EDIT: What about a long-running process that I can ping queries to whenever I have need?
There are two main ways to run commands outside console:
Rake task which depends on :environment
rails runner (previously script/runner), eg:
$ rails runner "query"
Both are pretty well documented on the rails guide: https://guides.rubyonrails.org/command_line.html#bin-rails-runner
Both of these methods will still take the same time as a console to fire up, but they are useful for non-interactive tasks.
Just pipe it in:
echo 'puts Article.count' | bundle exec rails c
It should now be a lot faster than when then the question was originally asked, because of Spring. It's not immediate, but still a lot faster than spinning up the whole app. Use this for the fast lane, it should run in under a second (assuming your required command is fast):
echo 'puts Article.count' | spring rails c
If you really want a single long-running process, you could easily do it by creating a controller action that simply runs whatever you POST to it, then send commands to it using curl behind an alias. The action would of course be completely insecure and should be triple-guarded against running anywhere near production, but it would be easy to setup.
Solution: bundle exec command allows us to run an executable script in the specific context of the project's bundle - making all gems specified in the Gemfile available to require in Ruby application. In addition it eventually avoids any conflicts with other versions of rake installed globally.
echo '<command>' | bundle exec rails c
for more information look at the documentation of bundler
example:
configuration_item=$(echo 'ConfigurationManager.getKey("authentication_method")' | bundle exec rails c )
echo $configuration_item
#output:
MFA_authentication

How to deploy Rails 3 project using "Rake"?

How to deploy Rails project on live server using Rake task?
For other projects I used Capistrano deployment.But for this project I wish to use rake...if anybody guide me please ... What gem I will need to install or what is the procedure I should follow?
You already answered your question yourself:
Either you use capistrano (the recommended way) - or you write your own custom rake Tasks that do what you want.
Writing Rake tasks is nothing complicated, you simply define tasks that depend on each other for each step of your deployment and then run them.
Remember: Rake tasks are just plain Ruby and you therefore can use any Gem that suits your needs.
Only if you get a bit more detailed on what tasks you want to do during your deployment I can start recommending Gems or what Tasks you may need to write.
Article by Martin Fowler on Rake: http://martinfowler.com/articles/rake.html
Generally a Rake file looks pretty much like this:
task :default => [:test]
task :test do
# You can write regular ruby here and do anything you want
puts "Foo"
end
task :dependant => [:test] do
# This task will automatically make sure task test is run before running.
puts "Hello World"
end
Linux or windows? which is the os you are using?
you can follow this refeerence
http://guides.rubyonrails.org/command_line.html
http://www.tutorialspoint.com/ruby-on-rails/rails-and-rake.htm
Just guessing a bit.
You probably would need:
A command line options parser
A way to interact through ssh
Some linux command execution
Optionally a way to interact with git

Rails 3 Create Script to Manipulate My DB

I'm trying to create a script to mess around with the db entries in my rails application, but I don't know how to properly set it up to gain access to all my models etc.
I can do this easily with scripts like seeds.rb using 'rake db:seed' to execute or in my application controllers, but I want to create scripts outside of these that I can run in the background or just once.
Do I need to include something, or call the script with a certain rails command? And as a second related question, is there any way for me to execute rails commands like 'rake db:seed' from within a ruby script? The only method I know of right now that works is running 'rails console' and executing commands there.
require 'config/environment.rb'
When the script is in your rails root...

RoR environment in Ruby standalone script

I want to run a standalone ruby script in which I need my RoR environment to be used. Specifically, I need my models extending ActionMailer and ActiveRecord. I also need to read the database configuration from my database.yml.
How do I go about it?
The easiest way is to change the shebang of your script from :
#!/usr/bin/ruby
to
#!/path/to/your/rails/script/runner
Et voilĂ , your script will be run with the full rails environment loaded. You can also run your script as ./my_script -e production to have it run with the production database.
Check out this thread:
How do I run Ruby tasks that use my Rails models?
Essentially it boils down to:
require "#{ENV['RAILS_ROOT']}/config/environment.rb"
Have fun!
I think the best way to do this is to make it a rake task.
# lib/tasks/mystuff.rake
desc 'do my stuff'
task :my_stuff => [:environment] do
# do my stuff
end
The [:environment] stanza loads the rails environment.

Running Rake Without Shell Access?

For a RoR installation, is there any way to run rake commands without root access?
To put it another way, is there any way to get db:create and db:migrate to be run without root access (perhaps automatically or something)? Or can I run rake commands from a RoR controller?
Take a look at rails-2.X.X/lib/tasks/databases.rake and you can see the code called to create, drop, and migrate your database.
Once a rails environment is initialized, you can use the code inside the rake task file to create, drop, and migrate.
I do not know if you can do this at the controller level before it errors, but you can always try. You could also do it after rails has finished initializing in the environment file.
config/environment.rb
...
ActiveRecord::Migration.verbose = false
ActiveRecord::Migrator.migrate(File.join(Rails.root, 'db', 'migrate'))
Well, it is a bit of a chicken-egg problem, you may be able to start your RoR instance without the database created but I doubt it. If your hosting provider is able to host RoR apps, there must be a way for them to run rake for you or to let you run it somehow.
Since it sounds like you are running into troubles with creating the database, is there a way to do it from the hosting control panel? Still, how are you going to migrate your database? Sounds like you might need to look at a new host. I use Slicehost and think they are great :)
Give this code a try:
require 'rake'
require 'rake/testtask'
require 'rake/rdoctask'
require 'tasks/rails'
Rake::Task["db:version"].invoke
I just tried it in ./script/console and that worked. It wouldn't work without the require lines.
I use it to call other rake tasks from a rake task (when it's not a pre-req but something that has to happen in the middle).
Note, that won't get you any of the output from the command. If you want that you could just go with good old backticks and run the command like this:
output = `rake db:version`
That'll launch another process, but I don't think there's a problem with that.
Just to be clear, you do not need root access, you need just shell (ssh) access to that machine.
How are you deploying it without access ? If you're using capistrano than you already have shell access and it can run those tasks for you.

Resources