Skip to content

Instantly share code, notes, and snippets.

@justinko
Created April 11, 2012 05:05
Show Gist options
  • Save justinko/2357038 to your computer and use it in GitHub Desktop.
Save justinko/2357038 to your computer and use it in GitHub Desktop.
A potential solution (very rough!) to Rails ivars-in-views problem
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
@avdi
Copy link

avdi commented Apr 11, 2012 via email

@justinko
Copy link
Author

I agree, which is why I put them in procs.

@justinko
Copy link
Author

justinko commented May 8, 2012

@ohthatjames
Copy link

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