ruby-on-rails – Rails:帮助程序中的控制器方法或实例变量
发布时间:2020-12-16 19:14:00 所属栏目:百科 来源:网络整理
导读:我正在使用有点宝石,并希望能够访问我的帮助器方法中的有点API(由视图和邮件程序调用以生成URL). 我在ApplicationController中使用此方法启动API连接: (有没有更适合做BTW的地方?) class ApplicationController ActionController::Base before_filter :bit
我正在使用有点宝石,并希望能够访问我的帮助器方法中的有点API(由视图和邮件程序调用以生成URL).
我在ApplicationController中使用此方法启动API连接: (有没有更适合做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 默认情况下,我无法访问助手中的@bitly.你能建议一种方法来实现这一目标吗? 我找到的唯一相关主题没有帮助: 谢谢. 解决方法
按照惯例,Rails将控制器操作(和过滤器)中设置的实例变量传递给视图.辅助方法在这些视图中可用,并且应该可以访问您在控制器操作中设置的实例变量.
或者,您可以通过将变量传递给方法或使用Object#instance_variable_get方法在助手方法中设置局部变量: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 至于您对逻辑位置的关注,它看起来不像它属于控制器.将控制器视为应用程序的路由请求.大多数逻辑应该在模型类中执行. “瘦的控制器,胖模型.”:http://weblog.jamisbuck.org/2006/10/18/skinny-controller-fat-model (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |