Ruby no method error with HTTParty

2019-09-06 12:25发布

I am trying to make a post request in Ruby and I am getting inconsistent behaviour. I am currently using ruby-2.0.0-p598 on OSX.

When using PRY and I type the following post command:

HTTParty.post(@base_uri + '/method/?argument1&api_key=' + @api_key)

I get a successful respond from the API. However when I run it through my specs or inside the class I get:

undefined method `+' for nil:NilClass

I know it has to do with the plus sign, but I find it weird that I am getting a different behaviour. Can you please suggest what is the correct way of doing this?

Thanks in advance.

2条回答
手持菜刀,她持情操
2楼-- · 2019-09-06 12:32

It looks like @base_uri and/or @api_key is null. Please double check if they are initialized with valid strings or not. Then try

 HTTParty.post("#{@base_uri}/method/?argument1&api_key=#{@api_key}")

In this case, ruby will automatically try to convert @base_uri and @api_key to string so no need to call to_s method explicitly.

查看更多
萌系小妹纸
3楼-- · 2019-09-06 12:45

Good day Behavior correct - some variable = nil. You have check variables, or (in this case it is better not to do) call to_s:

HTTParty.post(@base_uri.to_s + '/method/?argument1&api_key=' + @api_key.to_s)
查看更多
登录 后发表回答