我怎样才能干掉所有这些对 render :index 的调用?
我有一堆带有渲染索引视图的方法的控制器。这导致我在大多数方法的末尾编写 render :index
。下面是一个示例
def index
@models = Model.find(:all)
end
def new_models
@models = Model.find_by_new(true)
render :index
end
def old_models
@models = Model.find_by_new(false)
render :index
end
理想情况下,我只需将渲染代码移至后置过滤器中,但由于控制器在进入后置过滤器之前调用渲染,因此这不是一个选项。
我有大量这样的控制器,因此解决方案将删除大量重复的代码。
这个应用程序目前仍然是 Rails 2.3,但是,它将在未来一两个月内升级到 Rails 3。因此,虽然我更喜欢适用于 2.3 的技术,但仅限 Rails 3 的解决方案仍然会受到赞赏。
I have a bunch of controllers with methods that render the index view. This results in me writing render :index
at the end of the majority of methods. Here's an example
def index
@models = Model.find(:all)
end
def new_models
@models = Model.find_by_new(true)
render :index
end
def old_models
@models = Model.find_by_new(false)
render :index
end
Ideally, I would just move the render code into an after filter, but as the controller makes a call to render before going to the after filter that's not an option.
I have a large number of controllers like this so a solution would remove a lot of repeated code.
This app is currently still Rails 2.3, however, it will be upgraded to Rails 3 in the next month or two. So while I would prefer a technique that works on 2.3, Rails 3 only solutions would still be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果你真的想干掉这个动作,并且它很常见,那么你可以自己做一些元编程。首先使用此模块定义创建一个 render_with_index.rb 文件:
然后将该模块包含在控制器中并定义应使用索引渲染的方法(确保在方法声明之后发生 render_with_index 调用。
该模块现在允许您使用只需将索引模板添加到 render_with_index 调用即可。
If you really want to DRY up this action, and if it's very common, then you can do some meta-programming of your own. First create a render_with_index.rb file with this module definition:
Then include that module in your controller and define the methods that should render with index (make sure the render_with_index call happens after your method declarations.
This module now allows you to render any action with the index template simply by adding it to the render_with_index call.
对我来说看起来很干。恕我直言,如果您不想使用控制器方法特定的模板,那么提及您正在渲染哪个模板是一个好习惯。
如果您的渲染代码从一行扩展到多行代码,我会将它们干燥为单独的渲染方法。
Looks pretty DRY to me. IMHO it's a good habbit to mention which template you are rendering if you don't want to use controller method specific template.
If your render code extends from one-liner into several lines of code, I would DRY them up into separate render method.