Skip to content

Instantly share code, notes, and snippets.

@Odaeus
Last active June 15, 2021 09:34
Show Gist options
  • 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
@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