Phil Gyford
Phil Gyford

Reputation: 14594

Ruby URI module oddness in modular Sinatra app

I'm having trouble using the Ruby URI module's encode_www_form method in a modular Sinatra app. For some reason, URI is interpreted as being the URI::Parser subclass, and so the method call understandably fails.

I've reduced this to a minimal test case. The Gemfile:

source 'https://rubygems.org'
ruby '1.9.3'

gem 'sinatra'

And app.rb:

require 'sinatra/base'

class Frontend < Sinatra::Base
  get '/test/' do
    URI.encode_www_form(:a => 1, :b => 2)
  end

  run! if app_file == $0
end

If I then run ruby app.rb and access /test/ I get:

NoMethodError - undefined method `encode_www_form' for #<URI::Parser:0x007fa9221ca868>:
    app.rb:6:in `block in <class:Frontend>'

If I convert it to a classic-style Sinatra app, so that app.rb is like this:

require 'sinatra'

get '/test/' do
  URI.encode_www_form(:a => 1, :b => 2)
end

Then call ruby app.rb and access /test/, the page shows "a=1&b=2" as desired.

So what's going wrong in the modular format that means something's up with URI?

Upvotes: 0

Views: 498

Answers (3)

superquadratic
superquadratic

Reputation: 310

As of Sinatra 1.4.4, the URI module is no longer overwritten.

Upvotes: 0

Peter Alfvin
Peter Alfvin

Reputation: 29409

The class Sinatra::Base redefines URI on line 856 of https://github.com/sinatra/sinatra/blob/master/lib/sinatra/base.rb, which is why your URI reference gets evaluated as that value.

If you want to avoid this problem, you can change your reference to ::URI.

Upvotes: 3

jomo
jomo

Reputation: 14911

I tried to reproduce this in irb. This may sound stupid, but require 'uri' did the trick there.

Upvotes: -2

Related Questions