0

I have a simple API called wrapped in my lib/

lib/riotapi.rb

class RiotApi
    riot_url = 'https://na.api.pvp.net/api/lol/na/v1.4/summoner/by-name/RiotSchmick?api_key=ENV['mykey']'

    def unique_url
        response = HTTParty.get(riot_url)
        json = JSON.parse(response.body)
        json
    end
end

my controller

class WelcomeController < ApplicationController

    require 'riotapi'

    def index
        api = RiotApi.new()
        @list = api.unique_url
    end
end

I have my welcome#index as the index page of the application. When I open it up, it says that undefined local variable or method "riot_url"

What am I doing wrong here?

Edit: The above sample is taken from here Very Basic Rails 4.1 API Call using HTTParty

3
  • Take a look at the syntax highlighting in your first block. Did you copy/paste that in? Seems like you are missing a ' Commented Jul 14, 2015 at 21:38
  • 1
    sorry that was typo on my part, the syntax is all good as far as I checked! Commented Jul 14, 2015 at 21:40
  • @AbM interesting, that seem to did the trick! If you'd like to answer this question, I would love to accept your solution. Commented Jul 14, 2015 at 21:45

1 Answer 1

1

You should use a ruby constant (ALL CAPITAL) for this:

lib/riotapi.rb

class RiotApi
    RIOT_URL = 'https://na.api.pvp.net/api/lol/na/v1.4/summoner/by-name/RiotSchmick?api_key=ENV['mykey']'

    def unique_url
        response = HTTParty.get(RIOT_URL)
        JSON.parse(response.body)
    end
end

Also note that you do not have to use the json variable in your unique_url

Here's is a SO answer that goes over the variable scope in a class. Note that I chose a ruby constant since I assumed the url will not changed. If you have a method in your class that changes the url, you should use a class variable (the one with @@)

Sign up to request clarification or add additional context in comments.

1 Comment

Could you add an explanation as to the difference between riot_url and RIOT_URL?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.