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

I'm a little out of the loop... what's the issue with just using :helper_method again?

@justinko
Copy link
Author

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

@donwb
Copy link

donwb commented Apr 11, 2012

After writing doing node.js for the better part of a year, I forget just how elegant Ruby is...

@avdi
Copy link

avdi commented Apr 11, 2012 via email

@justinko
Copy link
Author

@avdi @tenderlove has tried that: https://gist.github.com/2287133

Personally, I'd rather just stick with ivars instead of creating new classes.

@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