Class: Minecraft::JSONAPIv2::Request

Inherits:
Object
  • Object
show all
Defined in:
lib/minecraft_jsonapiv2/request.rb

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Request

Returns a new instance of Request.



4
5
6
7
8
9
10
11
# File 'lib/minecraft_jsonapiv2/request.rb', line 4

def initialize(options={})
    @host = options[:host].nil? ? '127.0.0.1' : options[:host]
    @port = options[:port].nil? ? 20059 : options[:port]
    @user = options[:user]
    @auth = Minecraft::JSONAPIv2::Authorization.new(options)
    @json = []
    @req = []
end

Instance Method Details

#generate_array_for_json(options = {}) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/minecraft_jsonapiv2/request.rb', line 47

def generate_array_for_json(options={})
    if options.is_a? Array
        options.each do |o|
            generate_array_for_json o
        end
    else
    raise 'No username given' if options[:user].nil?
    raise 'No key given' if options[:key].nil?
    raise 'No method given' if options[:method].nil?
    raise 'No method name given' if options[:method][:name].nil?
    @json.push({
        name: options[:method][:name],
        username: options[:user],
        arguments: map_to_array(options[:method][:args]),
        key: options[:key],
    })
    end
    @json
end

#generate_request(method) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/minecraft_jsonapiv2/request.rb', line 22

def generate_request(method)
    if method.is_a? Array
        method.each do |m|
            generate_request m
        end
    else
        @req.push(
            user: @user,
            method: method,
            key: @auth.key_for(method[:name])
        )
    end
    @req
end

#make_request(options) ⇒ Object



13
14
15
16
17
18
19
20
# File 'lib/minecraft_jsonapiv2/request.rb', line 13

def make_request(options)
    url = Minecraft::JSONAPIv2::BASE_URI % {host: @host, port: @port}
    request = generate_array_for_json( generate_request(options) ).to_json
    response = HTTParty.post(url, body: request, headers: {'Content-Type' => 'application/json'} )
    @json = []
    @req = []
    response.body
end

#map_to_array(arguments) ⇒ Object



37
38
39
40
41
42
43
44
45
# File 'lib/minecraft_jsonapiv2/request.rb', line 37

def map_to_array(arguments)
    if arguments.nil?
        []
    elsif arguments.is_a?(Array) || arguments.is_a?(Hash)
        arguments
    else
        [arguments]
    end
end