与继承一起使用时,alias_method的异常行为

问题描述 投票:1回答:1

当尝试将alias_method与继承一起使用时,出现这种有线行为:

class First
  def calculate
    puts value
  end
end

class Second < First
  def result
    'Second:result'
  end
  alias_method :value, :result
end

class Third < Second
  def result
    'Third:result'
  end
end

Third.new.calculate
# => Second:result
  • 期望:“'第三:结果'”
  • 实际:“第二:结果”

因此,我们可以通过以下方式解决它:

class First
  def calculate
    puts value
  end
end

class Second < First
  def result
    'Second:result'
  end

  def value
    result
  end
end

class Third < Second
  def result
    'Third:result'
  end
end

Third.new.calculate
# => Third:result

或这种方式:

class First
  def calculate
    puts value
  end
end

class Second < First
  def result
    'Second:result'
  end
  alias_method :value, :result
end

class Third < Second
  def result
    'Third:result'
  end
  alias_method :value, :result
end

Third.new.calculate
# => Third:result

但是问题是:为什么在第一种情况下它不像expected一样工作?

继承是一种“错误模式”,但是当在Rails中使用带有DRY的策略继承时,它可能很有价值。>

[在尝试将alias_method与继承一起使用时,出现了这种有线行为:class First def计算将值放到端类class Second

Turns out that alias_method creates an alias that references the original method rather than the overwritten one.

详细信息来源:https://theinternate.com/2014/02/14/inheritable-aliases-in-ruby.html


注意:

对我来说很困惑,所以这就是为什么我决定分享它,我希望它对某人有帮助,以避免可能的困惑。


note_2:

alias关键字相同:

class First
  def calculate
    puts value
  end
end

class Second < First
  def result
    'Second:result'
  end
  alias value result
end

class Third < Second
  def result
    'Third:result'
  end
end

Third.new.calculate
# => Second:result
ruby inheritance alias
1个回答
1
投票

Turns out that alias_method creates an alias that references the original method rather than the overwritten one.

© www.soinside.com 2019 - 2024. All rights reserved.