Class: MQTTPipe::Listener
- Inherits:
-
Object
- Object
- MQTTPipe::Listener
- 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
-
#action ⇒ Object
readonly
Returns the value of attribute action.
-
#pattern ⇒ Object
readonly
Returns the value of attribute pattern.
-
#topic ⇒ Object
readonly
Returns the value of attribute topic.
Instance Method Summary collapse
-
#===(topic) ⇒ Object
Returns true if the topic matches listener topic Otherwise false.
-
#call(*args) ⇒ Object
(also: #run)
Call the listener action.
-
#initialize(topic, &action) ⇒ Listener
constructor
The listener requires a topic string and a callable action to initialize.
-
#match(topic) ⇒ Object
Check if a given topic string matches the listener topic.
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
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
#action ⇒ Object (readonly)
Returns the value of attribute action.
9 10 11 |
# File 'lib/mqtt_pipe/listener.rb', line 9 def action @action end |
#pattern ⇒ Object (readonly)
Returns the value of attribute pattern.
9 10 11 |
# File 'lib/mqtt_pipe/listener.rb', line 9 def pattern @pattern end |
#topic ⇒ Object (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 |