Add the error response type to the library

This commit is contained in:
Nick Thomas
2011-11-13 20:09:55 +00:00
parent d96239dd65
commit 3f8b74005d
4 changed files with 61 additions and 1 deletions

View File

@@ -2,6 +2,7 @@ require 'json'
require 'qmp_client/messages/command'
require 'qmp_client/messages/greeting'
require 'qmp_client/messages/error'
require 'qmp_client/messages/event'
require 'qmp_client/messages/query'
require 'qmp_client/messages/reply'
@@ -36,6 +37,7 @@ module QMPClient
return Event::build(hsh) if Event::represents?(hsh)
return Command::build(hsh) if Command::represents?(hsh)
return Query::build(hsh) if Query::represents?(hsh)
return Error::build(hsh) if Error::represents?(hsh)
return Greeting::build(hsh) if Greeting::represents?(hsh)

View File

@@ -0,0 +1,48 @@
require 'qmp_client/messages/message'
module QMPClient
module Messages
class Error < Message
attr_reader :request_id
attr_reader :error_class
attr_reader :data
attr_reader :desc
# Does the hash represent a Command?
def self.represents?(hsh)
super(hsh) &&
(hsh.keys - %w|id error|).empty? && hsh['error'].is_a?(Hash) &&
hsh['error']['class'].is_a?(String) &&
hsh['error']['data'].is_a?(Hash) &&
hsh['error']['desc'].is_a?(String)
end
def ==(other)
other.is_a?(Error) && [
:request_id, :error_class, :data, :desc
].all? {|m| self.send(m) == other.send(m) }
end
def self.build(hsh)
err = hsh['error']
new(hsh['id'], err['class'], err['data'], err['desc'])
end
def initialize(request_id, err_kls, data, desc)
@request_id = request_id
@error_class = err_kls
@data = data
@desc = desc
end
def to_hash
{ 'id' => request_id,
'error' => {
'class' => error_class, 'data' => data, 'desc' => desc
}
}
end
end
end
end