Class: Gamefic::Messenger

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

Overview

Message formatting and buffering.

Instance Method Summary collapse

Constructor Details

#initializeMessenger

Returns a new instance of Messenger.



7
8
9
# File 'lib/gamefic/messenger.rb', line 7

def initialize
  @buffers = ['']
end

Instance Method Details

#bufferString

Create a temporary buffer while yielding the given block and return the buffered text.

Returns:



15
16
17
18
19
# File 'lib/gamefic/messenger.rb', line 15

def buffer
  @buffers.push('')
  yield if block_given?
  @buffers.pop
end

#flushString

Clear the buffered messages.

Returns:

  • (String)

    The flushed message



54
55
56
# File 'lib/gamefic/messenger.rb', line 54

def flush
  @buffers.pop.tap { @buffers.push '' }
end

#format(message) ⇒ Object



58
59
60
61
62
63
64
# File 'lib/gamefic/messenger.rb', line 58

def format(message)
  "<p>#{message.strip}</p>"
    .gsub(/[ \t\r]*\n[ \t\r]*\n[ \t\r]*/, "</p><p>")
    .gsub(/[ \t]*\n[ \t]*/, ' ')
    .gsub(/<p>\s*<p>/, '<p>')
    .gsub(%r{</p>\s*</p>}, '</p>')
end

#messagesString

Get the currently buffered messages.

Returns:



47
48
49
# File 'lib/gamefic/messenger.rb', line 47

def messages
  @buffers.last
end

#stream(message) ⇒ String

Add a raw text message to the current buffer.

Unlike #tell, this method will not wrap the message in HTML paragraphs.

Parameters:

Returns:

  • (String)

    The messages in the current buffer



39
40
41
42
# File 'lib/gamefic/messenger.rb', line 39

def stream(message)
  @buffers.push(@buffers.pop + message.to_s)
          .last
end

#tell(message) ⇒ String

Add a formatted message to the current buffer.

This method will automatically wrap the message in HTML paragraphs. To send a message without formatting, use #stream instead.

Parameters:

Returns:

  • (String)

    The messages in the current buffer



28
29
30
31
# File 'lib/gamefic/messenger.rb', line 28

def tell(message)
  @buffers.push(@buffers.pop + format(message.to_s))
          .last
end