如何在Rails中修补一个类

时间:2018-03-20 01:25:37

标签: ruby-on-rails ruby

我正试图用“Tinder”模块修补“Tumble”这个类。但是当我向类中添加方法时,它们不会被继承。然而,常数是。

LIB / tumble.rb:

class Tumble
  ...

LIB /翻滚/ tinder.rb

module Tinder
  APP_ID = 1234567890

  # Without self
  def xyz
    puts 'bar'
  end

配置/初始化/ tumble.rb

Tumble.include Tinder

该应用加载Tumble和Tinder,我可以访问APP_ID:

$ rails r 'puts Tumble::APP_ID'
1234567890

但是Tumble没有继承这些方法:

[~/tinder]$ rails r 'puts Tumble.foo'
Please specify a valid ruby command or the path of a script to run.
Run 'bin/rails runner -h' for help.

undefined method `foo' for Tumble:Class
[~/tinder]$ rails r 'puts Tumble.xyz'
Please specify a valid ruby command or the path of a script to run.
Run 'bin/rails runner -h' for help.

undefined method `xyz' for Tumble:Class

如何修补Tumble以包含Tinder中的这些方法?

谢谢:)

2 个答案:

答案 0 :(得分:2)

当您致电Tumble.foo时,正在调用foo,就像它是一种类方法一样。

然而,当您执行Tumble.include Tinder时,会将模块的实例方法添加为Tumble的实例方法

因此,如果您执行Tumble.new.foo,那么您当前的代码应该有效。

您还可以Tumble.foo使用Tumble.extend Tinder

答案 1 :(得分:0)

class Tinder
 def initialize
  # some code here
 end
end

想象一下,上面是你想要修补的类。要修补它,你只需要再次编写(在任何加载的地方)类Tinder,并添加如下代码:

class Tinder
 def some_more_code
  # does great stuff
 end
end

这是猴子补丁。模块不会做猴子补丁。它们以不同的方式扩展功能。

请注意不要覆盖原始类的任何想要进行猴子补丁的方法,当然,除非这是你的目标。