Rails: controller method or instance variable inside helper

I use bitly gem and would like to have access to the bitly API inside my helper methods (which invoke calls and mailers to create URLs).

I initiate an API connection in this method in my ApplicationController:

(is there any more suitable place for this BTW?)

class ApplicationController < ActionController::Base before_filter :bitly_connect def bitly_connect Bitly.use_api_version_3 @bitly ||= Bitly.new(APP_CONFIG['bitly_username'], APP_CONFIG['bitly_api_key'] ) end end 

By default, I do not have access to @bitly in my helpers. Can you suggest a way to do this?

The only related thread I found did not help: Rails 3 and controller instance variables inside the helper

Thanks.

+8
ruby-on-rails helpers
source share
2 answers

By convention, rails pass instance variables defined in controller actions (and filters) along with views. Helper methods are available in these views and must have access to the instance variables set inside your controller action.

Alternatively, you can set a local variable inside your helper method by passing the variable to the method or using the Object # instance_variable_get method: http://ruby-doc.org/core/classes/Object.html#M001028

 # app/controllers/example_controller.rb class ExampleController def index @instance_variable = 'foo' end end # app/helpers/example_helper.rb module ExampleHelper def foo # instance variables set in the controller actions can be accessed here @instance_variable # => 'foo' # alternately using instance_variable_get variable = instance_variable_get(:@instance_variable) variable # => 'foo' end end 

As for your problems with the placement of logic, it does not look like it belongs to the controller. Think of the controller as routing requests for your application. Most of the logic should be executed inside your model classes. "Skinny controller, fat model.": Http://weblog.jamisbuck.org/2006/10/18/skinny-controller-fat-model

+9
source share

If you need a controller method for access as an assistant, you can use helper_method

 class ApplicationController < ActionController::Base helper_method :bitly_connect def bitly_connect @bitly ||= begin Bitly.use_api_version_3 Bitly.new(APP_CONFIG['bitly_username'], APP_CONFIG['bitly_api_key'] ) end end end 

Note that I also changed the method so that it does not call Bitly.use_api_version_3 every time it is called.

As Ben Simpson noted, you should probably port this to the model.

+2
source share

All Articles