Class: Curlyrest::CurlResponseParser

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

Overview

class for parsing curl responses

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(response) ⇒ CurlResponseParser

Returns a new instance of CurlResponseParser.



28
29
30
31
32
33
34
# File 'lib/curlyrest.rb', line 28

def initialize(response)
  @state = :read_status
  @response = nil
  @body_lines = []
  @body = nil
  parse(response)
end

Instance Attribute Details

#responseObject

Returns the value of attribute response.



26
27
28
# File 'lib/curlyrest.rb', line 26

def response
  @response
end

Instance Method Details

#bodyObject



36
37
38
# File 'lib/curlyrest.rb', line 36

def body
  @body || @body_lines.join
end

#parse(response) ⇒ Object



40
41
42
43
44
45
# File 'lib/curlyrest.rb', line 40

def parse(response)
  response.lines.each do |line|
    parse_line(line)
  end
  @response.body = body
end

#parse_headers(line) ⇒ Object



60
61
62
63
64
65
66
67
68
69
# File 'lib/curlyrest.rb', line 60

def parse_headers(line)
  if /^\s*$/.match?(line)
    @state = :body
    return
  end
  /^([\w-]+):\s(.*)/ =~ line.chop
  raise "invalid line while parsing headers: #{line}" unless Regexp.last_match

  @response.add_field(Regexp.last_match(1), Regexp.last_match(2))
end

#parse_line(line) ⇒ Object



71
72
73
74
75
76
77
78
79
80
# File 'lib/curlyrest.rb', line 71

def parse_line(line)
  case @state
  when :body
    @body_lines << line
  when :read_status
    parse_status(line)
  when :headers
    parse_headers(line)
  end
end

#parse_status(line) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/curlyrest.rb', line 47

def parse_status(line)
  re = %r{^HTTP/(\d+|\d+\.\d+)\s(\d+)\s*(.*)$}
  return unless re.match(line.chop)

  r = Regexp.last_match(2)
  return if r && r == '100'

  @state = :headers
  @response = CurlResponse.new(Regexp.last_match(1),
                               Regexp.last_match(2),
                               Regexp.last_match(3))
end