Created
April 11, 2012 05:05
-
-
Save justinko/2357038 to your computer and use it in GitHub Desktop.
A potential solution (very rough!) to Rails ivars-in-views problem
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
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.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I agree, which is why I put them in procs.