Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 我能做这个吗;块包装“;以惯用/简洁的方式可选?_Ruby - Fatal编程技术网

Ruby 我能做这个吗;块包装“;以惯用/简洁的方式可选?

Ruby 我能做这个吗;块包装“;以惯用/简洁的方式可选?,ruby,Ruby,在ruby中,您可以像这样调用远程api def get_remote_date Net::HTTP.get('example.com', '/index.json') end 如果您执行gem安装vcr,则可以执行此操作 def get_remote_date VCR.use_cassette("cassette_001") do Net::HTTP.get('example.com', '/index.json') end end Vcr录制/播放有助于在开发过程中

在ruby中,您可以像这样调用远程api

def get_remote_date
  Net::HTTP.get('example.com', '/index.json')
end
如果您执行
gem安装vcr
,则可以执行此操作

def get_remote_date
  VCR.use_cassette("cassette_001") do
    Net::HTTP.get('example.com', '/index.json')
  end
end
Vcr录制/播放有助于在开发过程中 远程api很昂贵。 是否使用vcr应该是可选的,如图所示 通过函数的第一个参数:

def get_remote_date(should_use_vcr)
  VCR.use_cassette("cassette_001") do
    Net::HTTP.get('example.com', '/index.json')
  end
end
我的问题是,如何重写该方法,使“块包装”/“VCR.use_Case(“Case_001”)do”以“应该使用_VCR”局部变量的布尔值为条件

我可以

def get_remote_date(should_use_vcr)
  if conditional here
    VCR.use_cassette("cassette_001") do
      Net::HTTP.get('example.com', '/index.json')
    end
  else
    Net::HTTP.get('example.com', '/index.json')     
  end
end
但是对于一个包含“Net::HTTP.get”(“加上十几行代码)的复杂方法,代码重复太多了,
因此,正在寻找一种更简洁的方法。

您可以将重复的代码放入一个方法中,并调用该方法,该方法可以包装在VCR do块中,也可以不使用VCR。

您可以尝试使用以下方法:

def get_remote_date
  record_request { Net::HTTP.get('example.com', '/index.json') }
end

def record_request(&request)
  ENV['RECORD_REQUEST'] ? VCR.use_cassette("cassette_001", &request) : request.call
end


这是一个很好的例子,它解释了
&block
(符号和参数)的含义以及它与
收益率
关键字的关系。

说明了基于收益率的解决方案

  def maybe_cache_http_requests(cassette)
    if ENV['CACHE_HTTP_REQUESTS'] == "1"
      require 'vcr'
      VCR.configure do |config|
        config.cassette_library_dir = "vcr_cassettes"
        config.hook_into :webmock
      end
      VCR.use_cassette(cassette) do
        yield
      end
    else
      yield
    end
  end

这里可以提供帮助吗?@american ninja warrior我不这么认为,但我的ruby有点生锈。创建一个方法对VCR不起作用吗?或者为什么要询问产量?可以找到
#call
的文档。