Class: Yaic::Message

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(tags: {}, source: nil, command: nil, params: []) ⇒ Message

Returns a new instance of Message.



9
10
11
12
13
14
15
# File 'lib/yaic/message.rb', line 9

def initialize(tags: {}, source: nil, command: nil, params: [])
  @tags = tags
  @source = source
  @command = command
  @params = params
  @raw = nil
end

Instance Attribute Details

#commandObject (readonly)

Returns the value of attribute command.



7
8
9
# File 'lib/yaic/message.rb', line 7

def command
  @command
end

#paramsObject (readonly)

Returns the value of attribute params.



7
8
9
# File 'lib/yaic/message.rb', line 7

def params
  @params
end

#rawObject (readonly)

Returns the value of attribute raw.



7
8
9
# File 'lib/yaic/message.rb', line 7

def raw
  @raw
end

#sourceObject (readonly)

Returns the value of attribute source.



7
8
9
# File 'lib/yaic/message.rb', line 7

def source
  @source
end

#tagsObject (readonly)

Returns the value of attribute tags.



7
8
9
# File 'lib/yaic/message.rb', line 7

def tags
  @tags
end

Class Method Details

.parse(str) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/yaic/message.rb', line 17

def self.parse(str)
  return nil if str.nil? || str.empty?

  str = str.b.force_encoding("UTF-8")
  str = str.encode("UTF-8", "ISO-8859-1", invalid: :replace, undef: :replace) unless str.valid_encoding?

  stripped = str.chomp("\r\n").chomp("\n")
  return nil if stripped.empty?

  scanner = StringScanner.new(stripped)

  tags = parse_tags(scanner)
  source = parse_source(scanner)
  command = parse_command(scanner)
  params = parse_params(scanner)

  msg = new(tags: tags, source: source, command: command, params: params)
  msg.instance_variable_set(:@raw, str)
  msg
end

Instance Method Details

#to_sObject



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/yaic/message.rb', line 38

def to_s
  parts = []
  parts << @command

  @params.each_with_index do |param, idx|
    is_last = idx == @params.length - 1
    parts << if is_last && needs_trailing_prefix?(param, @params.length)
      ":#{param}"
    else
      param
    end
  end

  "#{parts.join(" ")}\r\n"
end