ruby-on-rails - 是否可以从同名方法中调用先前定义的方法?
问题描述
是否可以覆盖一个方法并仍然回退到原始方法(假设不涉及超类)?
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)
。
但是对于这个问题,我真正感兴趣的是是否有办法从同名方法调用先前定义的方法?
参考资料:
解决方案
您可以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
推荐阅读
- r - 在无状态(谷歌云引擎)docker上保留来自R的永久日志的最佳方法是什么?
- php - 仅在结帐时禁用特定运输方式的支付网关
- amazon-web-services - 具有固定 IP 的 AWS 客户端 VPN
- c# - EpiServer 网站注销不再起作用
- pandas - 如何使用方法链接跨列使用 groupby 转换?
- google-apps-script - 如何在饼图中显示值 - Google Apps 脚本
- python-3.x - Pandas:如何计算 DateTime 索引
- nginx - Nginx 2 重写 2 例
- javascript - 导航栏不展开(React JS)
- reactjs - 样式(css)不适用于阴影 DOM 中的 React 应用程序