LoginSignup
6
5

More than 5 years have passed since last update.

cells を利用してパーシャル内のロジックを分離する

Last updated at Posted at 2014-08-22

注意: この内容は cell 3.x のものです。
4.x 系では大きな変更が加えられました。詳しくはこちらを参照してください。 From Cells 3 to Cells 4 Upgrading Guide · apotonick/cells Wiki

概要

apotonick/cells という gem を利用すると、パーシャル(のようなもの)単位でのコントローラ(のようなもの)を定義することができます。

  • 再利用性を考えてパーシャルを作成したがパーシャル内にロジックが入り込んでしまっている
  • 様々なビューから呼び出されるパーシャルで利用するオブジェクトを毎回コントローラで定義するのが微妙だ

のようなシチュエーションでうまい具合にロジックを分離してくれます。

実装

インストール & 生成

Gemfile に cells を加えます。

Gemfile
gem 'cells'

いつもどおり bundle install

generator を利用して必要なファイル一式を生成します。
後述の rspec-cells をインストールしておくと、rspec ファイルも生成されます。

./bin/rails g cell article show -e haml

呼び出す

生成された cells/article/show.html.haml を view から呼び出します。

= render_cell :article, :show, article: @article

引数で渡された値は以下のように利用します。

app/cells/article_cell.rb
class ArticleCell < Cell::Rails
  def show(args)
    @article = args[:article]
    render
  end
end

Devise のヘルパーメソッドを利用したい

current_useruser_signed_in? などを使いたい場合はこんな感じ。

app/cells/article_cell.rb
class ArticleCell < Cell::Rails
  include Devise::Controllers::Helpers
  helper_method :user_signed_in?, :current_user

  def list(args)
    @article = args[:article]

    if user_signed_in?
      my_name = current_user.name
      ...
    end
    render
  end

end

Rspec

rspec でテストするには rspec-cells gem を使うと良いです。

apotonick/rspec-cells

Gemfile
  gem 'rspec-cells'

devise のヘルパーを利用している場合は、Device::TestHelpers を利用するように設定しておきましょう。

spec/support/devise.rb
RSpec.configure do |config|
  config.include Devise::TestHelpers, :type => :cell # 追加
end

spec/cells/article_cell_spec.rb
describe ArticleCell, type: :cell do

  context 'cell rendering' do
    before { @article = FactoryGirl.create(:article) }
    context 'rendering list' do
      subject { render_cell(:article, :show, article: @article) }
      it { is_expected.to have_selector('div.article-container') }
      it { is_expected.to have_selector('h3.article-title', text: "「
#{@article.title}」") }
    end
    describe "assigns" do
      it "should assigns article" do
        render_cell(:article, :show, biz_service: @article)
        expect(view_assigns[:article]).to eq @article
      end
    end
  end
end
6
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5