Ruby no method error with HTTParty

风格不统一 提交于 2019-12-13 04:53:12

问题


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.


回答1:


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.




回答2:


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)


来源:https://stackoverflow.com/questions/29985406/ruby-no-method-error-with-httparty

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