Class: MPD::ServerResponse

Inherits:
String
  • Object
show all
Defined in:
lib/mpd/server_response.rb

Overview

Just a frozen string with some useful methods

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(response_text) ⇒ ServerResponse

Returns a new instance of ServerResponse.


19
20
21
22
# File 'lib/mpd/server_response.rb', line 19

def initialize(response_text)
  super
  freeze
end

Class Method Details

.from_connection(conn) ⇒ Object

Reads data from `MPD::Connection` instance to next OK/ACK


7
8
9
10
11
12
13
14
15
16
17
# File 'lib/mpd/server_response.rb', line 7

def self.from_connection(conn)
  line = ''
  buffer = ''
  while line != "OK\n" && !line.start_with?('ACK')
    line = conn.gets
    raise(ConnectionError) if line.nil?
    buffer << line
  end

  new(buffer.force_encoding('UTF-8'))
end

Instance Method Details

#contentObject

text without status


49
50
51
# File 'lib/mpd/server_response.rb', line 49

def content
  lines[0..-2].join
end

#error?Boolean

Returns:

  • (Boolean)

58
59
60
# File 'lib/mpd/server_response.rb', line 58

def error?
  status.start_with?('ACK')
end

#key_value_pairsObject

MPD often sends data as:

id: 1
title: some title
id: 2
title: another title

So this method comes useful.


38
39
40
41
42
43
44
45
46
# File 'lib/mpd/server_response.rb', line 38

def key_value_pairs
  content.split("\n").map do |line|
    index = line.index(':')
    raise "can't create key-value pair" unless index
    key = line[0...index]
    value = line[(index + 1)..-1].strip
    [key, value]
  end
end

#statusObject

last line of response


54
55
56
# File 'lib/mpd/server_response.rb', line 54

def status
  lines.last.chomp
end

#to_hObject


24
25
26
# File 'lib/mpd/server_response.rb', line 24

def to_h
  key_value_pairs.to_h
end