Why is #{} not adding the value to the string?

烂漫一生 提交于 2019-12-10 12:02:01

问题


Using httparty I'm making a GET request to:

https://api.marktplaats.nl/api3/categories.json?oauth_token=1me6jq76h8t6rim747m7bketkd&api_ver=3.7&session=ebc565b8-659f-40f6-9d0a-96986f1d1595&screenWidth=62&screenHeight=111&app_ver=Android3.1.0

Code A:

require 'httparty'

class Marktplaats  
  def categories
    HTTParty.get('https://api.marktplaats.nl/api3/categories.json?oauth_token=1me6jq76h8t6rim747m7bketkd&api_ver=3.7&session=ebc565b8-659f-40f6-9d0a-96986f1d1595&screenWidth=62&screenHeight=111&app_ver=Android3.1.0')
  end
end

Code B:

require 'httparty'

class Marktplaats
  @oauth_token = '1me6jq76h8t6rim747m7bketkd'

  def categories
    HTTParty.get("https://api.marktplaats.nl/api3/categories.json?oauth_token=#{@oauth_token}&api_ver=3.7&session=ebc565b8-659f-40f6-9d0a-96986f1d1595&screenWidth=62&screenHeight=111&app_ver=Android3.1.0")
  end
end

When doing:

m = Marktplaats.new
m.categories

Code A works, but Code B doesn't.

Calling .request.last_uri.to_s on the GET call of Code B returns:

https://api.marktplaats.nl/api3/categories.json?oauth_token=&api_ver=3.7&session=ebc565b8-659f-40f6-9d0a-96986f1d1595&screenWidth=62&screenHeight=111&app_ver=Android3.1.0

What could be going wrong?


回答1:


This is a case of defining a variable at the class-level versus the instance-level. You have defined @oauth_token at the class-level, but are trying to use it at the instance-level and can't. Try changing your code to this:

class Marktplaats
  def initialize
    @oauth_token = '1me6jq76h8t6rim747m7bketkd'
  end

  def categories
    HTTParty.get("https://api.marktplaats.nl/api3/categories.json?oauth_token=#{@oauth_token}&api_ver=3.7&session=ebc565b8-659f-40f6-9d0a-96986f1d1595&screenWidth=62&screenHeight=111&app_ver=Android3.1.0")
  end
end

OR to this, which uses a constant that is accessible at both the class and instance levels (but should never change).:

class Marktplaats
  OAUTH_TOKEN = '1me6jq76h8t6rim747m7bketkd'

  def categories
    HTTParty.get("https://api.marktplaats.nl/api3/categories.json?oauth_token=#{OAUTH_TOKEN}&api_ver=3.7&session=ebc565b8-659f-40f6-9d0a-96986f1d1595&screenWidth=62&screenHeight=111&app_ver=Android3.1.0")
  end
end



回答2:


You are creating a class-instance variable, but using a local instance variable in your method. Do this instead:

require 'httparty'

class Marktplaats
  OAUTH_TOKEN= '1me6jq76h8t6rim747m7bketkd'

  def categories
    HTTParty.get("https://api.marktplaats.nl/api3/categories.json?oauth_token=#{OAUTH_TOKEN}&api_ver=3.7&session=ebc565b8-659f-40f6-9d0a-96986f1d1595&screenWidth=62&screenHeight=111&app_ver=Android3.1.0")
  end
end


来源:https://stackoverflow.com/questions/24893661/why-is-not-adding-the-value-to-the-string

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