Alex Rivera | Logout

Calling an ApplicationController method from console in Rails

Asked 2012-05-20T02:36:08.383
15

In Rails, supposing that the file is already loaded, how it is possible to call my_method from this example from console?

# some_file.rb
class MyClass < ApplicationController::Base
  def my_method(args)
Edit
Report

2 Answers

33

Another, very simple way to do this is to use an instance of ApplicationController itself.

ApplicationController < ActionController::Base
  def example
    "O HAI"
  end
end

Then in the console, you can do the following:

>> ApplicationController.new.example

This will output the following:

O HAI

This, of course, has the restriction of not having access to everything a normal request would, such as the request object itself. If you need this, as the Patrick Klingemann suggested, you could use the debugger... I personally recommend using Pry:

This is likely much too late for you, but hopefully it will help someone in the future.

answered 2012-08-29T03:01:16.457
3

use debugger:

in your Gemfile add:

gem 'debugger'

then from the terminal:

> bundle
> rails s --debugger

in the controller action you're hitting:

class WidgetsController < ApplicationController
  def index
    debugger
    @widgets = Widget.all
    respond_with @widgets
  end
end

then point your browser to: http://localhost:3000/widgets, the page will not finish loading. Return to the terminal where your server is running and you'll be in an interactive debugging session where you can run: my_method

answered 2012-05-20T05:28:10.723

Your Answer