How do I get Sinatra to work with HTTPClient?

安稳与你 提交于 2019-12-18 07:02:45

问题


I'm trying to create a facade API that receives requests via Sinatra then launches HTTP requests on Github API in the backend.

In my "hello world" script I have:

#!/usr/bin/ruby

require 'httpclient'
require 'sinatra'

get '/foo' do
    "hello world"
end

However, it runs into errors like:

$ ./api.rb 
/usr/local/share/gems/gems/sinatra-1.4.3/lib/sinatra/base.rb:1408:in `run!': undefined method `run' for HTTP:Module (NoMethodError)
from /usr/local/share/gems/gems/sinatra-1.4.3/lib/sinatra/main.rb:25:in `block in <module:Sinatra>'

I don't understand why this happens. If I comment out the require 'httpclient' line, it works just fine:

#!/usr/bin/ruby

#require 'httpclient'
require 'sinatra'

get '/foo' do
  "hello world"
end

$ ./api.rb 
[2013-06-26 21:43:12] INFO  WEBrick 1.3.1
[2013-06-26 21:43:12] INFO  ruby 1.9.3 (2013-05-15) [x86_64-linux]
[2013-06-26 21:43:12] WARN  TCPServer Error: Cannot assign requested address - bind(2)
== Sinatra/1.4.3 has taken the stage on 4567 for development with backup from WEBrick
[2013-06-26 21:43:12] INFO  WEBrick::HTTPServer#start: pid=31272 port=4567

My guess is that Sinatra is using HTTPClient by itself and some kind of namespace collision is happening. Is there a way to use HTTPClient and Sinatra at the same time?

OK here is the requested info:

$ gem list sinatra httpclient

*** LOCAL GEMS ***

sinatra (1.4.3)

$ gem out sinatra httpclient
bigdecimal (1.1.0 < 1.2.0)
io-console (0.3 < 0.4.2)
json (1.6.8 < 1.8.0)
rdoc (3.12 < 4.0.1)

I figured out httpclient version this way:

$ locate httpclient.rb
/usr/local/share/gems/gems/httpclient-2.3.3/lib/httpclient.rb
/usr/local/share/gems/gems/httpclient-2.3.3/test/test_httpclient.rb

My OS is Fedora 17, though not sure if it matters.


回答1:


I found the reason. HTTPClient defines a module named HTTP. By default Sinatra looks for Rack handlers with namespace names HTTP and WEBrick, in that order.

Since the HTTP namespace has been defined Sinatra actually thinks it's a Rack handler. I think this is a bug in Sinatra. It should check if the handler responds to run before using it.

Anyway the fix is to use Thin, or if you want to use WEBrick then explicitly tell Sinatra to skip the automatic Rack detection by doing:

set :server, 'webrick'

That will prevent Sinatra from thinking the HTTPClient HTTP module is Rack handler.



来源:https://stackoverflow.com/questions/17334734/how-do-i-get-sinatra-to-work-with-httpclient

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!