1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

RailsコンソールでDecoratorを呼び出す方法

Posted at

はじめに

Railsでは、モデルの表示用ロジックを分離するためにDecoratorが使うことは多く、開発中やデバッグ時に、RailsコンソールからDecoratorのメソッドを呼び出したい場面は多いでしょう。
この記事では、RailsコンソールでDecoratorを呼び出す方法を備忘録としてまとめます。(毎回忘れるのd)

ActiveDecoratorを使用している場合

# まずはモデルのインスタンスを取得
user = User.find(1)

# デコレータを適用
decorated_user = ActiveDecorator::Decorator.instance.decorate(user)

# デコレータのメソッドを呼び出す
decorated_user.full_name  # => "山田 太郎"

元のインスタンスを直接修飾する方法

user = User.find(1)
ActiveDecorator::Decorator.instance.decorate(user)
user.full_name  # => "山田 太郎"

モジュールを直接適用する方法

user = User.find(1)
user.extend(UserDecorator)
user.full_name  # => "山田 太郎"

まとめ

Decoratorを使うことで、モデルとビューのロジックを適切に分離し、より保守性の高いコードを書くことができます!
デバッグ時にもこれらの方法を活用して、Decoratorが正しく機能しているか確認しよう!

1
0
1

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?