Class: OpenTriviaDB
- Inherits:
-
Object
- Object
- OpenTriviaDB
- Defined in:
- lib/open_trivia_db.rb
Overview
Retrieve questions from OpenTrivia DB with an encrypted answer key
Instance Attribute Summary collapse
-
#generator ⇒ class
Generator that implements the GenerateAnswerKey interface.
-
#url ⇒ string
Url of the service; defaults to opentdb.com/api.php.
Instance Method Summary collapse
-
#get(params = {}) ⇒ hash
Retrieve questions from OpenTrivia DB.
-
#initialize ⇒ OpenTriviaDB
constructor
A new instance of OpenTriviaDB.
Constructor Details
#initialize ⇒ OpenTriviaDB
Returns a new instance of OpenTriviaDB.
22 23 24 |
# File 'lib/open_trivia_db.rb', line 22 def initialize @url = 'https://opentdb.com/api.php' end |
Instance Attribute Details
#generator ⇒ class
Returns Generator that implements the GenerateAnswerKey interface.
14 15 16 |
# File 'lib/open_trivia_db.rb', line 14 def generator @generator end |
#url ⇒ string
Returns url of the service; defaults to opentdb.com/api.php.
17 18 19 |
# File 'lib/open_trivia_db.rb', line 17 def url @url end |
Instance Method Details
#get(params = {}) ⇒ hash
Retrieve questions from OpenTrivia DB. See Trivia API for definition of parameters.
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
# File 'lib/open_trivia_db.rb', line 34 def get(params = {}) # Ensure amount parameter passed params = params.merge({ amount: 10 }, params) uri = URI(@url) uri.query = URI.encode_www_form(params) res = Net::HTTP.get_response(uri) out = { response_code: 0, response_message: 'OK', params: params, questions: {} } # rubocop:disable Style/ConditionalAssignment case res.code.to_i when 200 json = JSON.parse(res.body) case json['response_code'] when 0 # Valid query out = out.merge({ questions: process_questions(json['results']) }) else # Invalid, possibly parameters related out = out.merge({ response_code: json['response_code'], response_message: 'invalid query' }) end else # Server error (ie 404, 503) out = out.merge({ response_code: res.code.to_i, response_message: res. }) end # rubocop:enable Style/ConditionalAssignment out end |