2015-10-19 49 views
0

我有這個類:的Ruby的method_missing參數

class Mock 

    attr_accessor :implementations 

    def initialize() 
     @implementations = Array.new 
    end 

    def method_missing(method_name, *arguments, &block) 
     implementation = findImplementation(method_name, arguments) 
     if implementation.nil? 
      raise "Undefined method #{method_name}." 
     else 
      puts "Implemented Method!" 
     end 
    end 

    def implement_method(method_name, parameters, return_value) 
     @implementations.unshift(Implementation.new(method_name, parameters, return_value)) 
     @method_to_mock = nil 
     @parameter = nil 
     @return_value = nil 
    end 

    def findImplementation(method_name, args) 
     return @implementations.find { |i| i.method_name == method_name && i.parameters == args } 
    end 

end 

如果我做:

m = Mock.new 
m.implement_method(:something, 10, true) 
m.findImplementation(:something, 10) 

它返回我在第二行添加的實現。但是當我這樣做時:

m.something(10) 

它輸出「未定義的方法」。很明顯,我在method_missing方法中調用的findImplementation調用返回nil。我究竟做錯了什麼?

+0

貴'find'工作?當你在'執行_方法'中執行'binding.pry'後,它不在那裏?開始調試! :)不相關,但它應該是'find_implementation'。 –

+0

'* argumentss'會創建一個'Array',這可能是爲什麼它返回'nil',因爲它不能找到一個帶有參數'[10]'的實現,因爲你希望它找到一個參數爲'10'的參數。不知道你想要完成什麼,所以答案几乎沒有用,但這是問題所在。 – engineersmnky

+0

@engineersmnky是它的問題,我該如何解決它,使這些值可比較? – Alan

回答

0

最簡單的解決方案是將您的參數作爲數組傳遞。 (你將如何處理多個PARAMS呢?)

所以,你的代碼變得

m = Mock.new 
m.implement_method(:something, [10], true) 
m.findImplementation(:something, [10])