Module: Shioruby

Defined in:
lib/shioruby.rb

Overview

SHIORI Protocol Parser / Builder

Defined Under Namespace

Classes: ParseError

Constant Summary collapse

@@response_message =

response messages for status codes

{
  200 => 'OK',
  204 => 'No Content',
  310 => 'Communicate',
  311 => 'Not Enough',
  312 => 'Advice',
  400 => 'Bad Request',
  418 => "I'm a tea pot",
  451 => 'Unavailable For Legal Reasons',
  500 => 'Internal Server Error',
}

Class Method Summary collapse

Class Method Details

.build_response(response) ⇒ String

build SHIORI/3.x Response

Parameters:

  • response (OpenStruct)

    SHIORI/3.x Response object

Returns:

  • (String)

    SHIORI/3.x Response string


45
46
47
48
49
50
51
52
53
# File 'lib/shioruby.rb', line 45

def build_response(response)
  message = response.message || @@response_message[response.code]
  response.version
  lines = ["SHIORI/#{response.version} #{response.code} #{message}"]
  response.each_pair.reject {|key, _| ['code', 'message', 'version', :code, :message, :version].include?(key)}.each do |key, value|
    lines << "#{key}: #{value}"
  end
  lines.join("\n") + "\n\n"
end

.parse_request(request_str) ⇒ OpenStruct

parse SHIORI/3.x Request

Parameters:

  • request_str (String)

    SHIORI/3.x Request string

Returns:

  • (OpenStruct)

    SHIORI/3.x Request object


24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/shioruby.rb', line 24

def parse_request(request_str)
  lines = request_str.each_line.map(&:chomp).reject(&:empty?)
  request_line = lines.shift
  unless request_line_result = request_line.match(/^(.+) SHIORI\/([\d.]+)$/)
    raise ParseError.new("invalid request line")
  end
  request = OpenStruct.new
  request.method = request_line_result[1]
  request.version = request_line_result[2]
  lines.each do |line|
    unless header_result = line.match(/^(.+?): (.*)$/)
      raise ParseError.new("invalid header")
    end
    request[header_result[1]] = header_result[2]
  end
  request
end