Class: Mcjsonapi::API
- Inherits:
-
Object
- Object
- Mcjsonapi::API
- Defined in:
- lib/mcjsonapi/api.rb
Instance Attribute Summary collapse
-
#host ⇒ Object
readonly
Returns the value of attribute host.
-
#port ⇒ Object
readonly
Returns the value of attribute port.
-
#username ⇒ Object
readonly
Returns the value of attribute username.
Instance Method Summary collapse
- #call(options = {}) ⇒ Object
- #generate_key(method) ⇒ Object
-
#initialize(options = {}) ⇒ API
constructor
A new instance of API.
Constructor Details
#initialize(options = {}) ⇒ API
Returns a new instance of API.
5 6 7 8 9 10 11 12 13 |
# File 'lib/mcjsonapi/api.rb', line 5 def initialize( = {}) raise ArgumentError, "Username and password must be given." if [:username].nil? || [:password].nil? @host = [:host] || "localhost" @port = [:port] || 20059 @username = [:username] @password = [:password] end |
Instance Attribute Details
#host ⇒ Object (readonly)
Returns the value of attribute host.
3 4 5 |
# File 'lib/mcjsonapi/api.rb', line 3 def host @host end |
#port ⇒ Object (readonly)
Returns the value of attribute port.
3 4 5 |
# File 'lib/mcjsonapi/api.rb', line 3 def port @port end |
#username ⇒ Object (readonly)
Returns the value of attribute username.
3 4 5 |
# File 'lib/mcjsonapi/api.rb', line 3 def username @username end |
Instance Method Details
#call(options = {}) ⇒ Object
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
# File 'lib/mcjsonapi/api.rb', line 19 def call( = {}) if .is_a? String if .empty? raise ArgumentError, "A method must be given." else = { name: } end elsif .is_a? Hash if .empty? || [:name].nil? raise ArgumentError, "A method must be given." end else raise ArgumentError, "A method must be given." end [:username] = @username [:key] = generate_key([:name]) data = URI::encode JSON.generate() response = Net::HTTP.get_response URI("http://#{@host}:#{@port}/api/2/call?json=#{data}") raise APIError, "The API responded with an HTTP error." unless response.is_a? Net::HTTPOK response_data = JSON.parse(response.body)[0] if response_data["is_success"] return response_data["success"] else raise APIError, "The API raised an error: #{response_data["error"]["message"]} (Code #{response_data["error"]["code"]})" end end |
#generate_key(method) ⇒ Object
15 16 17 |
# File 'lib/mcjsonapi/api.rb', line 15 def generate_key(method) Digest::SHA256.hexdigest @username+method+@password end |