Rails:助手内的控制器方法或实例变量
我正在使用 bitly gem,并且希望能够访问我的辅助方法中的 bitly API(视图和邮件程序调用这些 API 来生成 URL)。
我在我的 ApplicationController 中的这个方法中启动了一个 API 连接:(
顺便说一句,有更合适的地方来执行此操作吗?)
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
默认情况下,我无权访问我的助手中的 @bitly
。您能建议一种方法来实现这一目标吗?
我发现的唯一相关线程没有帮助: 助手内的 Rails 3 和控制器实例变量
谢谢。
I'm using the bitly gem and would like to have access to the bitly API inside my helper methods (which get called by views and mailers to generate URLs).
I initiate an API connection in this method in my ApplicationController:
(is there a more appropriate place to do 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 don't have access to @bitly
in my helpers. Can you suggest a way to accomplish that?
The only related thread I found wasn't helpful:
Rails 3 and Controller Instance Variables Inside a Helper
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
按照惯例,Rails 将控制器操作(和过滤器)中设置的实例变量传递到视图。辅助方法在这些视图中可用,并且应该可以访问您在控制器操作中设置的实例变量。
或者,您可以通过将变量传递给方法或使用 Object#instance_variable_get 方法在辅助方法中设置局部变量: http://ruby-doc.org/core/classes/Object.html#M001028
至于您对逻辑放置的担忧,它看起来它不属于控制器。将控制器视为应用程序的路由请求。大多数逻辑应该在模型类内部执行。 “瘦控制器,胖模型。”:http://weblog。 jamisbuck.org/2006/10/18/skinny-controller-fat-model
Rails by convention passes instance variables set in the controller actions (and filters) along to the views. The helper methods are available in these views, and should have access to the instance variables you set inside your controller action.
Alternately, you can set a local variable inside your helper method by passing the variable to the method, or by using the Object#instance_variable_get method: http://ruby-doc.org/core/classes/Object.html#M001028
As for your concerns with the placement of the logic, it does not look like it belongs in the controller. Think of the controller as routing requests for your application. Most logic should be performed inside of your model classes. "Skinny controller, fat model.": http://weblog.jamisbuck.org/2006/10/18/skinny-controller-fat-model
如果您需要一个控制器方法作为助手进行访问,您可以使用 helper_method
请注意,我还更改了该方法,以便每次调用时都不会调用
Bitly.use_api_version_3
。正如本·辛普森(Ben Simpson)指出的那样,您可能应该将其移至模型中。
If you need a controller method to be accessible as a helper, you can use helper_method
Note that I also altered the method, so that it doesn't call
Bitly.use_api_version_3
each time it is called.As Ben Simpson noted, you should probably move this into a Model though.