Rails 3 中的重写渲染 - 请求设计审查/代码重构
我正在寻找一种可扩展的方法来将功能注入控制器。
module Social
module Request
def self.included( base )
base.alias_method_chain :render, :social
base.alias_method_chain :process_action, :social
end
def process_action_with_social(method_name, *args)
@action = method_name
process_action_without_social(method_name, *args)
end
def render_with_social(action = nil, options = {}, &blk)
if @action == "new"
# do something social
end
render_without_social
end
end
end
class RequestController < ApplicationController
include Social::Request
def new
@request = RecommendationRequest.new
end
end
上面的代码可以工作,但我很确定它不是最佳的 ruby。我将为每个控制器创建不同的模块,实际上可能是一堆。每个控制器唯一的唯一代码是 render_with_social。
所以我的问题是:
- 有没有办法把其他两种方法拉出来,这样我就不能重复自己了? (抱歉,这是我第一次在 ruby 中使用模块)。
- 有没有一种方法可以做到这一点,而无需将 include Social::Request 放入 RequestController 中? (我希望能够删除这些模块,并让我的控制器继续工作,就像什么都没发生一样)
- 如果我最终拥有这些 Metrics::Request、Scoring::Request 等的不同套件,最好的方法是什么接近一个位置,我可以指定哪些模块将混合到哪些控制器中?
谢谢大家。
I'm looking for an extensible way to inject functionality into a controller.
module Social
module Request
def self.included( base )
base.alias_method_chain :render, :social
base.alias_method_chain :process_action, :social
end
def process_action_with_social(method_name, *args)
@action = method_name
process_action_without_social(method_name, *args)
end
def render_with_social(action = nil, options = {}, &blk)
if @action == "new"
# do something social
end
render_without_social
end
end
end
class RequestController < ApplicationController
include Social::Request
def new
@request = RecommendationRequest.new
end
end
This code above is working, but I'm pretty sure it's not optimal ruby. I'm going to be creating different modules for each controller, probably a bunch of them, actually. The only code that will be unique to each controller, is render_with_social.
So my questions are:
- Is there a way to pull the other two methods out, so I can not repeat myself? (Sorry, this is the first time I've used modules in ruby).
- Is there a way to do this without having to put the include Social::Request in the RequestController at all? (I want to be able to remove these modules, and have my controller continue to work as if nothing had happened)
- If I wind up having different suites of these Metrics::Request, Scoring::Request etc, what would be the best way to approach having a single location where I specify what modules will be mixed in to which controllers?
Thanks all.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论