tony_perkis666
tony_perkis666

Reputation: 251

Adding a variable to URI

I'm pulling an integer from a JSON response, and then using that integer as the upper-limit in a loop:

data = response.parsed_response["meta"]
pages = data['total']   

            (1..pages.to_i).step(1) do |page_num|

                response2 = client.get('/item?page=#{page_num}&per_page=1', :headers => {'Authorization' => auth, 'Content-Type' => 'application/json'})

However, I seem to be unable to pass the variable into the URI in a way that is usable with HTTParty:

/opt/chef/embedded/lib/ruby/1.9.1/uri/common.rb:176:in `split': bad URI(is not URI?): /items?page=#{page_num}&per_page=1 (URI::InvalidURIError)

I tried other methods ('/item?page=' + page_num + '&...', for example) that were, likewise unsuccessful. I'm not where what I'm overlooking, but is there another, more correct way of doing this.

The output is being returned as an integer, and is usable, but it seems not to be getting passed into the URI string above.

I came across this thread:

URI with variable

but I was unsure that this applied, and an attempt to adapt the solution was unsuccessful (undefined method `strip' for 10:Fixnum (NoMethodError))

Upvotes: 0

Views: 348

Answers (1)

SHS
SHS

Reputation: 7744

Instead of:

'/item?page=#{page_num}&per_page=1'

Use:

"/item?page=#{page_num}&per_page=1"

Strings with single-quotation marks don't allow interpolation; thus to interpolate, you must use double-quotation marks strings.

And just FYI: When it comes to an integer range, you need not specify "step(1)" as it is the default value.

Upvotes: 1

Related Questions