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

More than 3 years have passed since last update.

カラム名のメソッドをカスタマイズしたい

Posted at

前提

Userモデルが存在しており、nameというカラムがある

実現したいこと

  • user.nameと呼び出したときに、特定の条件Aのときは、nameを加工して返したい
  • メソッド名はnameから変えたくない

結論

class User < ActiveRecord::Base
  def name
    if A
      func(name)
    else
      self[:name]
    end
  end
end

or

class User < ActiveRecord::Base
  def name
    if A
      func(name)
    else
      super
    end
  end
end

エラーになるパターン

class User
  def name
    if A
      func(name)
    else
      name 
    end
  end
end

user.name 
=> "SystemStackError: stack level too deep"

そりゃそうなるよね。

参考にした記事

https://qiita.com/Asama334/items/6fb79e4890a5118d8dee
https://qiita.com/motoakii/items/f4da20611d1536a5ef9a

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