Class: Sawyer::Response

Inherits:
Object
  • Object
show all
Defined in:
lib/lessonly/response.rb

Instance Method Summary collapse

Constructor Details

#initialize(agent, res, options = {}) ⇒ Response

rubocop:disable MethodLength



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/lessonly/response.rb', line 7

def initialize(agent, res, options = {})
  if res.status >= 400
    fail Lessonly::ResponseError.new(
      res.status.to_s,
      response: res,
      body: agent.decode_body(res.body),
      cause: res.status
    )
  end

  @res = res
  @agent = agent
  @status = res.status
  @headers = res.headers
  @env = res.env
  @rels = process_rels
  @started = options[:sawyer_started]
  @ended = options[:sawyer_ended]
  @data = if @headers[:content_type] =~ /json|msgpack/
            process_data(@agent.decode_body(res.body))
          else
            res.body
          end

  log_response
end

Instance Method Details

#klass_from_type(result) ⇒ Object



53
54
55
56
57
58
# File 'lib/lessonly/response.rb', line 53

def klass_from_type(result)
  # Get sub object type if exists, otherwise
  # defer to parent type
  type = type_from_data(result) || @type
  "Lessonly::#{type.classify}".constantize
end

#log_responseObject

rubocop:enable MethodLength



35
36
37
# File 'lib/lessonly/response.rb', line 35

def log_response
  # puts @env
end

#process_data(data) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/lessonly/response.rb', line 39

def process_data(data)
  @type = type_from_data(data) || @type
  fail 'No type!' unless @type

  data = data[@type.to_sym] if data.key?(@type.to_sym)

  case data
  when Hash  then klass_from_type(data).new(agent, data)
  when Array then data.map { |hash| process_data(hash) }
  when nil   then nil
  else data
  end
end

#type_from_data(data) ⇒ Object



60
61
62
63
64
65
66
67
# File 'lib/lessonly/response.rb', line 60

def type_from_data(data)
  # Create user type: `create_user`
  # Delete user type: `delete_user`
  # Course assignment type: `course_assignments`
  # Use the last segment of type to determine resource class
  return nil unless data.key? :type
  data[:type].split('_').last
end