ruby - 如何有条件地选择两种方法之一来接收相同的 block

标签 ruby

我正在尝试更改依赖于变量 req 的代码的过程,您如何在此处看到:

@res = @conn.post do |request| if req == 'post'
@res = @conn.get do |request| if req == 'get'

问题是这似乎引发了一个错误:

stack.rb:89: syntax error, unexpected end-of-input, expecting keyword_end
user2.send_csr

我的问题是,我必须更改什么才能避免此问题?如果您需要有关我的代码的更多信息:

def send(req,ww,text1=nil,text2=nil)
@conn = Faraday.new 'https://zombo.de/rest', :ssl => {:verify => false}
@conn.basic_auth(@username,@password)
@res = @conn.post do |request| if req == 'post'
@res = @conn.get do |request| if req == 'get'
 request.url ww
 request.headers['Content-Type'] = text1 unless text1 == nil
 request.body = text2 unless text2 == nil
end
puts @res.body
end

def send_csr
  send('post','csr','text/plain',"#{File.read(@csr[0..-5])}")
end

user2.send_csr

最佳答案

如果您稍微扩展一下代码会怎样?添加一些格式并更改进入两个 block 的内容?

def send(req, ww, text1=nil, text2=nil)
  @conn = Faraday.new 'https://zombo.de/rest', :ssl => {:verify => false}

  @conn.basic_auth(@username,@password)

  @res = @conn.post { |request| handle_request(request) } if req == 'post'
  @res = @conn.get { |request| handle_request(request) } if req == 'get'

  @res.body
end

def handle_request request
  request.url ww
  request.headers['Content-Type'] = text1 unless text1 == nil
  request.body = text2 unless text2 == nil
  request
end

def send_csr
  send('post','csr','text/plain',"#{File.read(@csr[0..-5])}")
end

user2.send_csr

关于ruby - 如何有条件地选择两种方法之一来接收相同的 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19045918/

相关文章:

ruby-on-rails - ActionController::ParameterMissing - 参数缺失或值为空:用户:

mysql - mysql 表中具有最大值的 activerecord ruby​​ 行

ruby-on-rails - 试图在 rails3 中创建一个特定的数组

ruby-on-rails - Rails : difference between ENV. fetch() 和 ENV[]

ruby - 引用具有指定索引的枚举器值

Ruby 的 "hello world".scan(/(\w){2}/) 和 "hello world".scan(/\w{2}/) 不一样?

ruby-on-rails - CarrierWave Backgrounder 没有将版本图像上传到 AWS S3

ruby - Ruby 中的Scheme 动态风的等价物

Ruby自编源码

ruby - 在哪里可以找到数组某些方法的文档?