caller_method不返回我期望的值

问题描述 投票:0回答:1

[我想知道,什么方法调用了另一个方法(我只是试图创建简单的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 expect
1个回答
0
投票

在这种情况下,我建议不要使用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

之类的内容存储内部状态
© www.soinside.com 2019 - 2024. All rights reserved.