Eric Hu
Eric Hu

Reputation: 18218

Rails Console: where are helper and app defined?

In rails console, two objects are available: app and helper. Several blog posts cover what these are useful for. Unfortunately, they're not available in the source code of a normal Rails application.

Where are these methods defined, or how can I use them inside of Rails apps?

Upvotes: 3

Views: 296

Answers (1)

Eric Hu
Eric Hu

Reputation: 18218

TLDR

.../gems/railties-3.2.8/lib/rails/console/app.rb
.../gems/railties-3.2.8/lib/rails/console/helpers.rb

Long version

I'm covering how I discovered this information and what the declarations look like.

The How:

# in rails console
1.9.3p194 :019 > a = self
 => main
1.9.3p194 :020 > a.method :helper
 => #<Method: Object(Rails::ConsoleMethods)#helper>
1.9.3p194 :021 > _.source_location
 => ["/Users/erichu/.rvm/gems/ruby-1.9.3-p194@global/gems/railties-3.2.8/lib/rails/console/helpers.rb", 3]

Relevant source from that file:

def helper
  @helper ||= ApplicationController.helpers
end

So helpers is just an alias for ApplicationController.helpers

The procedure for finding the source of app is similar. Here's the relevant source:

def app(create=false)
  @app_integration_instance = nil if create
  @app_integration_instance ||= new_session do |sess|
    sess.host! "www.example.com"
  end
end

So app in the console is an alias for @app_integration_instance, which I can verify is available in controllers

Is it good practice to use these inside an application? Probably not.

Is this a way to get quick-and-dirty access to Rails view helpers and renderers? I think so.

Upvotes: 5

Related Questions