Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a custom name for delegate method in Rails 5?

I have a model with a delegate method,

class Card < ApplicationRecord
  has_one :meta_sm2

  delegate :next_repetition,
           to: :meta_sm2
end

Because the underlying model (currently is meta_sm2) might change in the future, so I would like to make the delegate method next_repetition to a custom name, like priority for example.

How can I defined a custom name delegate method, so that I can call the next_repetition like card.priority?

like image 569
X.Creates Avatar asked Dec 14 '22 00:12

X.Creates


1 Answers

You can use alias_method to achieve this.

class Card < ApplicationRecord
  has_one :meta_sm2

  delegate :next_repetition,
           to: :meta_sm2

alias_method :priority, :next_repetition

end
like image 186
theterminalguy Avatar answered Dec 16 '22 12:12

theterminalguy