Skip to content

Instantly share code, notes, and snippets.

@Odaeus
Last active June 15, 2021 09:34
Show Gist options
  • Star 19 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Odaeus/5238423 to your computer and use it in GitHub Desktop.
Save Odaeus/5238423 to your computer and use it in GitHub Desktop.
Alternative to Rails' sharing of instance variables between controller and views.
class ApplicationController < ActionController::Base
# Creates an accessor which is exposed to the view
def self.view_accessor(*names)
attr_accessor *names
helper_method *names
end
end
class ArticlesController < ApplicationController
# List the variables/methods you want to expose to the view
view_accessor :article, :articles
def index
# Assign the variable in the action
self.articles = Article.all
end
def show
end
protected
# Or implement directly as a method
def article
Article.find(params[:id])
end
end
%h1 Articles
-# Simply call the articles method instead of the instance variable.
- articles.each do |article|
%article
%h1.title= article.title
require 'spec_helper'
# Easy to test as well.
describe ArticlesController do
describe "index" do
let!(:articles) { create_list :article, 3 }
it "assigns all the articles" do
get :index
controller.articles.should == articles
end
end
end
@invisiblefunnel
Copy link

Nice work! Here's what I think this could look like as a gem: https://github.com/invisiblefunnel/view_accessor.

@ka8725
Copy link

ka8725 commented May 6, 2013

What is wrong with using @articles or @article?

@dolan
Copy link

dolan commented Feb 17, 2016

@ka8725 "Bare words" references to data in the views would be better, because if you decided at some later date to change what was just an accessor to a method call, or something, you would still not have to refactor any of the views. Also, it lends itself to being more easily able to extract a partial from a given piece of view code, that would use bare words to access the local parameters, as opposed to instance variables of the controller. Avdi Grimm did a good video explaining the finer points here

@ka8725
Copy link

ka8725 commented Jun 15, 2021

Thanks @dolan , that makes perfectly logical sense!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment