我很难理解 ruby 公开课程的错误。在测试环境 (rails) 中覆盖方法会导致初始化时出现无效参数错误。出于某种原因,重写新方法解决了这个问题。为什么?
我的课:
require 'adwords_api'
require 'adwords_config'
require 'scanf'
class AdwordsHelper
attr_accessor :adwords_id
attr_accessor :campaign_id
attr_accessor :adgroup_id
attr_accessor :invalid_ops
@@RETRY_INTERVAL = 3
@@RETRIES_COUNT = 500
@@config = 'adwords_api.yml'
def initialize(args = {})
self.adwords_id = AdwordsConfig.config[:master_account]
return unless args.is_a?(Hash)
args.each do |k,v|
instance_variable_set("@#{k}", v) unless v.nil?
end
end
def set_budget(budget)
@api = get_adwords_api
budget_id = get_budget_id
service = @api.service(:BudgetService)
operation = {
:operator => 'SET',
:operand => {
:budget_id => budget_id,
:amount => {
:micro_amount => budget
}
}
}
service.mutate([operation])
end
end
现在在测试中,我想覆盖其中一种方法,因为我不希望与实际的 adwords 服务器进行通信。
require "test_helper"
# FIXME override this in another file eventually
class AdwordsHelper
def set_budget(budget)
true
end
end
打电话
AdwordsHelper.new(campaign_id: 1)
为 0 错误给出无效参数 1。
现在,覆盖新功能,解决了错误。
class AdwordsHelper
def self.new(*args, &block)
obj = allocate
obj
end
def set_budget(budget)
true
end
end
是否覆盖方法 set_budget 会导致其他怪癖?