如何在 Ruby 中覆盖类变量

Posted

技术标签:

【中文标题】如何在 Ruby 中覆盖类变量【英文标题】:How to override class variable in Ruby 【发布时间】:2018-06-24 04:48:54 【问题描述】:

我正在尝试覆盖https://github.com/activemerchant/active_merchant/blob/master/lib/active_merchant/billing/credit_card.rb 第 315 行上的“requires_name”方法或其变量,以便不执行第 328 行的检查。在澳大利亚,通常不会在付款过程中收集卡名,所以我试图输入 nils。我没有任何工作要做。

我试过 class_variable_set 之类的:

ActiveMerchant::Billing::CreditCard.class_variable_set(:@@requires_name, Proc.new do
    false
end)

我在这里尝试过 requires_name 和 require_name。没有区别。

我试过了:

ActiveMerchant::Billing::CreditCard.requires_name = Proc.new do
    false
end)

我尝试了其他各种方法。如何覆盖它?

【问题讨论】:

试试ActiveMerchant::Billing::CreditCard.require_name = false @Stefan 谢谢。就是这么简单!完美运行。 【参考方案1】:

您可以覆盖该方法,但设置该方法返回的值更容易:

ActiveMerchant::Billing::CreditCard.require_name = false

在内部,require_name 存储为类实例变量

ActiveMerchant::Billing::CreditCard.instance_variable_get(:@require_name)
#=> false

【讨论】:

以上是关于如何在 Ruby 中覆盖类变量的主要内容,如果未能解决你的问题,请参考以下文章