首页 > 解决方案 > caller_method 返回的不是我期望的值

问题描述

我想知道,什么方法调用另一种方法(我只是想创建简单的 expect("string").to eq("string") 模型(就像在 RSpect 中一样,但更容易)。

但我得到“主要”,那是什么?(我第一次看到“主要”)

public

def expect(message)
  message.to_s
end

def to
  caller_method = caller_locations.first.label
  puts caller_method
end

expect("test").to #=> <main>
#what output i expected:
expect("test").to #=> expect

我的目标:

#first i need to do something like that:
expect("test").to eq("test") #=> true
#final must look like this:
expect(expect("test").to eq("test")).to eq(true) #=> true

标签: ruby

解决方案


我建议不要caller_method在这种情况下使用。相反,创建一个其方法返回的类self- 这样它们就可以链接:

module Expectation
  attr_accessor :caller_method
  def expect(arg)
    self.caller_method = "expect"
    self
  end
  def to
    caller_method
  end
end

include Expectation

expect("foo").to
# => "expect"

显然这只是一个起点,实际上还没有进行任何比较/验证。但希望你能理解这种模式。关键是返回self以创建可链接的 API,并使用类似的东西存储内部状态attr_accessor


推荐阅读