首页 > 解决方案 > 是否可以从同名方法中调用先前定义的方法?

问题描述

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

def User
  def method
    # do some original stuff
  end
  def method
    # do some new stuff
    call_the_original :method
  end
end

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

在 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

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

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

我可以提交一个custom_avatar_method=(attachable)which calls avatar=(attachable)

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

参考资料

标签: ruby-on-rails

解决方案


您可以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

推荐阅读