1

我试图改变依赖于变量的代码过程,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
4

3 回答 3

2

如果你稍微扩展你的代码呢?添加一些格式并更改块的内容?

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
于 2013-09-27T08:21:36.297 回答
1

post-fixif不能按照你的方式放置,因为从技术上讲,它位于你想要传递给 get 或 post 的块的中间。

你可以这样做:

@res = @conn.get do |request| 
 request.url ww
 request.headers['Content-Type'] = text1 unless text1 == nil
 request.body = text2 unless text2 == nil
end if req == 'get'

但这需要您为每种情况重复代码块。另外,我建议不要在长块后修复条件,以后阅读代码时很难发现它们。

因此,使用这种语法send可能最适合您(它之所以有效,是因为您的字符串与方法名称匹配)

@conn.send(req) do |request| 
 request.url ww
 request.headers['Content-Type'] = text1 unless text1 == nil
 request.body = text2 unless text2 == nil
end
于 2013-09-27T08:20:30.487 回答
1

法拉第postget方法调用run_request

run_request(method, url, body, headers)

你也可以这样做:

def send(req, ww, text1=nil, text2=nil)
  @conn = Faraday.new 'https://zombo.de/rest', :ssl => {:verify => false}
  @conn.basic_auth(@username, @password)
  headers = text1 && {'Content-Type' => text1 }
  @res = @conn.run_request(req.to_sym, ww, text2, headers)
  puts @res.body
end

我通过了,req.to_sym因为run_request需要一个符号(:post而不是"post")而不是设置urlbody并且headers在块中,我也通过了它们。

也许您应该重命名一些变量并用本地变量替换实例变量:

def send(method, url, content_type=nil, body=nil)
  conn = Faraday.new 'https://zombo.de/rest', :ssl => {:verify => false}
  conn.basic_auth(@username, @password)
  headers = content_type && {'Content-Type' => content_type }
  res = conn.run_request(method.to_sym, url, body, headers)
  puts res.body
end
于 2013-09-27T09:14:04.063 回答