Class: MQTTPipe::Listener

Inherits:
Object
  • Object
show all
Defined in:
lib/mqtt_pipe/listener.rb

Overview

Used to store topics along with their actions. Contains conveniens methods for matching the topic to a given string as well as calling the action.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(topic, &action) ⇒ Listener

The listener requires a topic string and a callable action to initialize.

An ArgumentError is raised if no action is given

Raises:

  • (ArgumentError)


17
18
19
20
21
22
23
24
25
# File 'lib/mqtt_pipe/listener.rb', line 17

def initialize topic, &action
  raise ArgumentError, 'No block given' if action.nil?
  
  @topic = topic
  @action = action
  
  pattern = topic.gsub('*', '([^/]+)').gsub('/#', '/?(.*)').gsub('#', '(.*)')
  @pattern = %r{^#{pattern}$}
end

Instance Attribute Details

#actionObject (readonly)

Returns the value of attribute action.



9
10
11
# File 'lib/mqtt_pipe/listener.rb', line 9

def action
  @action
end

#patternObject (readonly)

Returns the value of attribute pattern.



9
10
11
# File 'lib/mqtt_pipe/listener.rb', line 9

def pattern
  @pattern
end

#topicObject (readonly)

Returns the value of attribute topic.



9
10
11
# File 'lib/mqtt_pipe/listener.rb', line 9

def topic
  @topic
end

Instance Method Details

#===(topic) ⇒ Object

Returns true if the topic matches listener topic Otherwise false.



43
44
45
# File 'lib/mqtt_pipe/listener.rb', line 43

def === topic
  @pattern === topic
end

#call(*args) ⇒ Object Also known as: run

Call the listener action



50
51
52
53
# File 'lib/mqtt_pipe/listener.rb', line 50

def call *args
  #raise ArgumentError, 'No value provided' if args.empty?
  @action.call *args
end

#match(topic) ⇒ Object

Check if a given topic string matches the listener topic.

Returns an array containing any matched sections of topic, if there was a match. False otherwise.



34
35
36
37
# File 'lib/mqtt_pipe/listener.rb', line 34

def match topic
  m = @pattern.match topic
  m.nil? ? false : m.captures
end