Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling an ApplicationController method from console in Rails

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)
like image 641
Martin Avatar asked May 20 '12 02:05

Martin


3 Answers

It is not exactly the question asked, but you can also debug with the pry gem, similarly to debugger.

Add to the Gemfile:

gem "pry"
gem "pry-remote"
gem "pry-stack_explorer"
gem "pry-debugger"

In your method:

def myMethod
  binding.pry
  # some code
end

Done!

When you run your method, the page processing will freeze at binding.pry and pry will take over the prompt. Type n for each new step of the method, and play around with your variables that can be print (just typing them) in "real-time"!

like image 119
Teo Inke Avatar answered Oct 21 '22 00:10

Teo Inke


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:

  • Pry on RubyGems.org
  • RailsCast: Pry with Rails

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

like image 30
slant Avatar answered Oct 22 '22 14:10

slant


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

like image 3
Patrick Klingemann Avatar answered Oct 22 '22 15:10

Patrick Klingemann