class Netologiest::Resource

This class describe client for Netology API. It contains finder actions and special handlers methods

Attributes

resource_name[RW]
token[R]
token_expire[R]

Public Class Methods

detail(id) click to toggle source
# File lib/netologiest/resource.rb, line 22
def self.detail(id)
  new.detail(id)
end
list() click to toggle source
# File lib/netologiest/resource.rb, line 18
def self.list
  new.list
end
new() click to toggle source
# File lib/netologiest/resource.rb, line 14
def initialize
  authorize!
end

Public Instance Methods

authorize!() click to toggle source

rubocop:disable /AbcSize, Metrics//MethodLength

# File lib/netologiest/resource.rb, line 43
def authorize!
  url = build_url('gettoken')
  params = { client_secret: Netologiest.config.api_key }
  HttpClient.get(url, params: params) do |response, _request, _result|
    case response.code
    when 200
      body = JSON.parse(response.body)
      @token_expire = Time.now.to_i + body.fetch('expires_in').to_i
      @token = body['access_token']
    when 401
      raise Netologiest::Unauthorized, response.body
    else
      response
    end
  end
end
detail(id) click to toggle source
# File lib/netologiest/resource.rb, line 34
def detail(id)
  handle_detail(
    get(
      build_url(self.class.resource_name, id)
    )
  )
end
get(url, options = {}) click to toggle source

rubocop:disable Metrics/MethodLength

# File lib/netologiest/resource.rb, line 72
def get(url, options = {})
  params = { token: (options[:token] || token) }.merge!(options)

  auth_method = options[:auth_method] || :authorize!

  HttpClient.get(url, params: params) do |response, _request, _result|
    if response.code == 401
      begin
        params[:token] = send(auth_method)
        new_response = HttpClient.get(url, params: params)
        if new_response.success?
          return new_response.body
        else
          raise Netologiest::Unauthorized, response.body
        end
      end
    end
    response.body
  end
end
handle_detail(_response) click to toggle source
# File lib/netologiest/resource.rb, line 69
def handle_detail(_response); end
handle_list(_response) click to toggle source
# File lib/netologiest/resource.rb, line 67
def handle_list(_response); end
list() click to toggle source
# File lib/netologiest/resource.rb, line 26
def list
  handle_list(
    get(
      build_url(self.class.resource_name)
    )
  )
end
token_expired?() click to toggle source

rubocop:enable Metrics/AbcSize, Metrics//MethodLength

# File lib/netologiest/resource.rb, line 61
def token_expired?
  return true if token_expire.to_s.empty?

  token_expire < Time.now.to_i
end

Protected Instance Methods

build_url(*args) click to toggle source

rubocop:enable Metrics/MethodLength

# File lib/netologiest/resource.rb, line 96
def build_url(*args)
  File.join(Netologiest.config.api_url, *args.map(&:to_s))
end