gpt4 book ai didi

ruby-on-rails - Ruby on Rails : alias_method_chain, 究竟是做什么的?

转载 作者:数据小太阳 更新时间:2023-10-29 06:21:03 25 4
gpt4 key购买 nike

我尝试阅读了各种博客文章,这些文章试图解释 alias_method_chain 以及使用和不使用它的原因。我特别注意:

http://weblog.rubyonrails.org/2006/4/26/new-in-rails-module-alias_method_chain

http://yehudakatz.com/2009/03/06/alias_method_chain-in-models/

我仍然看不到 alias_method_chain 有任何实际用途。谁能解释一下。

1 - 它还在使用吗?
2 - 你什么时候会使用 alias_method_chain 以及为什么?

最佳答案

1 - is it still used at all?

显然是的,alias_method_chain()still used in Rails (从版本 3.0.0 开始)。

2 - when would you use alias_method_chain and why?

(注意:以下内容主要基于 Paolo Perrotta 在 Metaprogramming Ruby 中对 alias_method_chain() 的讨论,这是一本你应该得到的好书。)

让我们从一个基本示例开始:

class Klass
def salute
puts "Aloha!"
end
end

Klass.new.salute # => Aloha!

现在假设我们想用日志记录行为包围 Klass#salute()。我们可以做到这一点,Perrotta 称之为周围别名:

class Klass
def salute_with_log
puts "Calling method..."
salute_without_log
puts "...Method called"
end

alias_method :salute_without_log, :salute
alias_method :salute, :salute_with_log
end

Klass.new.salute
# Prints the following:
# Calling method...
# Aloha!
# ...Method called

我们定义了一个名为 salute_with_log() 的新方法,并将其命名为 salute()。用于调用 salute() 的代码仍然有效,但它也获得了新的日志记录行为。我们还为原始的 salute() 定义了一个别名,因此我们仍然可以在不记录的情况下致敬:

Klass.new.salute_without_log # => Aloha!

因此,salute() 现在称为 salute_without_log()。如果我们想要记录日志,我们可以调用 salute_with_log()salute(),它们是同一方法的别名。使困惑?好!

根据 Perrotta 的说法,这种环绕别名在 Rails 中很常见:

Look at another example of Rails solving a problem its own way. A few versions ago, the Rails code contained many instances of the same idiom: an Around Alias (155) was used to add a feature to a method, and the old version of the method was renamed to something like method_without_feature(). Apart from the method names, which changed every time, the code that did this was always the same, duplicated all over the place. In most languages, you cannot avoid that kind of duplication. In Ruby, you can sprinkle some metaprogramming magic over your pattern and extract it into its own method... and thus was born alias_method_chain().

换句话说,您提供原始方法 foo() 和增强方法 foo_with_feature(),最后得到三个方法:foo()foo_with_feature()foo_without_feature()。前两个包含该功能,而第三个则不包含。 alias_method_chain() provided by ActiveSupport 而不是到处复制这些别名,为你做所有的别名。

关于ruby-on-rails - Ruby on Rails : alias_method_chain, 究竟是做什么的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3695839/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com