-
-
Save justinko/2357038 to your computer and use it in GitHub Desktop.
ActionController::Base.class_eval do | |
def self.context(*actions, &block) | |
contexts[actions] << block | |
end | |
def self.contexts | |
@contexts ||= Hash.new {|h, k| h[k] = [] } | |
end | |
end | |
class MyController < ApplicationController | |
before_filter do | |
contexts = self.class.contexts.select do |actions, context| | |
actions.empty? || actions.include?(@_action_name.to_sym) | |
end | |
contexts.values.each do |procs| | |
procs.each do |cxt| | |
self.class.helper(&cxt) # so we can call from the view | |
instance_eval(&cxt) # so we can call from the controller | |
end | |
end | |
end | |
def about | |
foo # raises "from foo" | |
bar | |
end | |
context do | |
def foo | |
raise 'from foo'.inspect | |
end | |
def bar | |
raise 'from bar'.inspect | |
end | |
end | |
context :nope do | |
def foo | |
raise 'from nope'.inspect | |
end | |
end | |
end |
1.) Restricting the API/helper methods to certain actions. This was a concern of @tenderlove
2.) A "blog_post" helper method may return differents things depending on the action (context). Without something like this, you would have to create multiple helper methods or add branching logic (if params[:id]) to the single method. This is my main motivation. I hate doing this:
def post
@post = params.key?(:id) ? Post.find(params[:id]) : Post.new
end
After writing doing node.js for the better part of a year, I forget just how elegant Ruby is...
@avdi @tenderlove has tried that: https://gist.github.com/2287133
Personally, I'd rather just stick with ivars instead of creating new classes.
I agree, which is why I put them in procs.
Going to try this out sometime: https://github.com/jonleighton/focused_controller
If you want to have more fine-grained control over what's exposed to your views, does https://github.com/hudge/proffer help at all? It removes all instance variables from views and gives you an interface to expose only the variables you want as locals.
I'm a little out of the loop... what's the issue with just using
:helper_method
again?