问题
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