Overriding Render in Rails 3 - Request for design review / code refactor
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, optio开发者_开发技巧ns = {}, &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.
精彩评论