是否可以从同名方法中调用先前定义的方法?

And*_*vey 2 ruby-on-rails

是否可以覆盖一个方法并仍然回退到原始方法(假设不涉及超类)?

def User
  def method
    # do some original stuff
  end
  def method
    # do some new stuff
    call_the_original :method
  end
end
Run Code Online (Sandbox Code Playgroud)

希望我的具体例子能让我的意思更清楚。

在 User 模型中使用 activestoragehas_one_attached :avatar添加了 setter 方法。我想在调用此 setter 时做一些事情,但我仍然希望运行原始方法。

class User 
  has_one_attached :avatar
  # According to the source (see references) this mixes in the following setter method 
  def avatar=(attachable)
    # do activestorage stuff 
  end 

  # I want to add some custom functions to this, before still running "do activestorage
  # stuff". I could copy, paste and edit the entire function. But out of interest, 
  # I wondered if a more elegant solution exists. 
  def avatar=(attachable)
    # do my stuff
    super(attachable)
  end
end
Run Code Online (Sandbox Code Playgroud)

super显然不起作用,因为 User 没有继承avatar=()定义的任何内容。

我可以创建例如包含并从中继承的MasterUser类,但这对于这种特殊情况似乎太过分了。has_one_attachedUser

我可以提交给一个custom_avatar_method=(attachable)which 调用avatar=(attachable)

但对于这个问题,我真正感兴趣的是是否有办法从同名方法调用先前定义的方法?

参考

Jag*_*ngh 6

您可以alias_method在此处访问之前的定义:

class User 
  def avatar=(attachable)
    # do activestorage stuff 
  end 
  alias_method :original_avatar=, :avatar=

  def avatar=(attachable)
    # do my stuff
    self.original_avatar=(attachable)
  end
end
Run Code Online (Sandbox Code Playgroud)