How can I call controller/view helper methods from the console in Ruby on Rails? How can I call controller/view helper methods from the console in Ruby on Rails? ruby-on-rails ruby-on-rails

How can I call controller/view helper methods from the console in Ruby on Rails?


To call helpers, use the helper object:

$ ./script/console>> helper.number_to_currency('123.45')=> "R$ 123,45"

If you want to use a helper that's not included by default (say, because you removed helper :all from ApplicationController), just include the helper.

>> include BogusHelper>> helper.bogus=> "bogus output"

As for dealing with controllers, I quote Nick's answer:

> app.get '/posts/1'> response = app.response# you now have a rails response object much like the integration tests> response.body            # get you the HTML> response.cookies         # hash of the cookies# etc, etc


An easy way to call a controller action from a script/console and view/manipulate the response object is:

> app.get '/posts/1'> response = app.response# You now have a Ruby on Rails response object much like the integration tests> response.body            # Get you the HTML> response.cookies         # Hash of the cookies# etc., etc.

The app object is an instance of ActionController::Integration::Session

This works for me using Ruby on Rails 2.1 and 2.3, and I did not try earlier versions.


If you need to test from the console (tested on Ruby on Rails 3.1 and 4.1):

Call Controller Actions:

app.get '/'   app.response   app.response.headers  # => { "Content-Type"=>"text/html", ... }   app.response.body     # => "<!DOCTYPE html>\n<html>\n\n<head>\n..."

ApplicationController methods:

foo = ActionController::Base::ApplicationController.newfoo.public_methods(true||false).sortfoo.some_method

Route Helpers:

app.myresource_path     # => "/myresource"app.myresource_url      # => "http://www.example.com/myresource"

View Helpers:

foo = ActionView::Base.newfoo.javascript_include_tag 'myscript' #=> "<script src=\"/javascripts/myscript.js\"></script>"helper.link_to "foo", "bar" #=> "<a href=\"bar\">foo</a>"ActionController::Base.helpers.image_tag('logo.png')  #=> "<img alt=\"Logo\" src=\"/images/logo.png\" />"

Render:

views = Rails::Application::Configuration.new(Rails.root).paths["app/views"]views_helper = ActionView::Base.new viewsviews_helper.render 'myview/mytemplate'views_helper.render file: 'myview/_mypartial', locals: {my_var: "display:block;"}views_helper.assets_prefix  #=> '/assets'

ActiveSupport methods:

require 'active_support/all'1.week.ago=> 2013-08-31 10:07:26 -0300a = {'a'=>123}a.symbolize_keys=> {:a=>123}

Lib modules:

> require 'my_utils' => true> include MyUtils => Object> MyUtils.say "hi"evaluate: hi => true