LoginSignup
18
16

More than 5 years have passed since last update.

current_userからactive_decoratorで定義したメソッドを呼ぶ方法

Last updated at Posted at 2014-05-02

※前の内容が色々と誤解を招きそうな感じだったので修正しました。

Viewで current_user.name などと書くことがあるかと思いますが、この書き方だとactive_decoratorで定義したメソッドを呼べません。何故かというとこれはactive_decoratorはrenderメソッドを呼んだタイミングでインスタンス変数にdecoratorで定義したメソッドを追加しているからで、直接Viewでcurrent_userを呼ぶとモデルのインスタンスをそのまま参照するだけになってしまい、当然decoratorで定義したメソッドはNoMethodErrorになってしまうからです。

対応としては主に以下の2パターンがあります。

1. 明示的にインスタンス変数に入れる

current_userとpundit_userを上書き
class HogeController < ApplicationController
  # インスタンス変数経由で参照する
  def show
    @user = current_user
  end
end

個人的にはこちらを推奨。これならrenderメソッドが呼ばれ、@userがdecorateされます。この書き方であればコントローラーを見ただけでログインユーザーのデータを参照しているアクションが一目瞭然というメリットもあります。

2. current_userをオーバーライドする

該当のメソッドをオーバーライドして直接decorateする方法。

current_userとpundit_userを上書き
class ApplicationController < ActionController::Base
  # devise の current_userを使うには
  def current_user
    ActiveDecorator::Decorator.instance.decorate(super) if super.present?
    super
  end
end

毎回明示的にインスタンス変数に入れるなんて面倒。そもそもログインが前提のサービスだし!って時はまあこっちでもいいと思います。

18
16
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
18
16