Skip to content

A router for small messages, like Tweets and SMS

License

Notifications You must be signed in to change notification settings

polleverywhere/message_router

Repository files navigation

Message Router

<img src=“https://travis-ci.org/polleverywhere/message_router.svg?branch=master” alt=“Build Status” /> <img src=“https://codeclimate.com/github/polleverywhere/message_router/badges/gpa.svg” />

Message router is a DSL for routing and processing simple messages, like SMS messages or Tweets.

Installation

sudo gem install message_router

Example Code

See rdoc for MessageRouter::Router.build (lib/message_router/router.rb) for examples.

And now some irb action.

class HelloRouter < MessageRouter::Router
  match /hi/ do
    puts "Hi there. You sent me: #{env.inspect}"
    true # puts returns nil, and that would fail the matcher
  end
end
# => [[/hi/, #<Proc:0x00000000026963b8@(irb):2>]]
HelloRouter.call({'body' => 'can you say hi to me?'})
# Hi there. You sent me: {'body'=>"can you say hi to me?"}
# => true
class MainRouter < MessageRouter::Router
  match({'to' => 'greeter'}, HelloRouter)
  match(true) do
    puts "WTF? I don't know how to do that!"
    true # puts returns nil, and that would fail the matcher
  end
end
# => [[{"to"=>"greeter"}, HelloRouter], [true, #<Proc:0x007f98c39e5b70@(irb):13>]]
MainRouter.call({'body' => 'can you say hi to me?'})
# WTF? I don't know how to do that!
# => true
MainRouter.call({'body' => 'can you say hi to me?', 'to' => 'greeter'})
# Hi there. You sent me: {'body'=>"can you say hi to me?", 'to'=>"greeter"}
# => true

TODO

Get docs working nicely (formatting, etc.) with RDoc.

Add tests to ensure that instance variables can be shared between initializers and helpers. For example:

class MyRouter < MessageRouter::Router
  def initilaize(config)
    @sender = config[:sender]
    super
  end

  match true do
    send_something
  end

  def send_something
    @sender.puts 'something'
  end
end
MyRouter(:sender => STDOUT).call({})  # prints out 'something' to standard out.

Pass Regexp captures on to the proc when there is a match. Examples:

match /some (cool|awesome) thing/ do |match|
  puts "You thought the thing was #{match[1]}"
end
match 'some_attr' => /some (cool|awesome) thing/, 'body' => /(.*)/ do |matches|
  puts "You thought that #{matches['body'][1]} was #{matches['some_attr'][1]}"
end
-- OR --
match /some (cool|awesome) thing/ do
  puts "You thought the thing was #{env['message_router_match'][1]}"
end
match 'some_attr' => /some (cool|awesome) thing/, 'body' => /(.*)/ do
  puts "You thought that #{env['message_router_matches']['body'][1]} was #{env['message_router_matches']['some_attr'][1]}"
end
-- OR -- (probably best because it is simplest)
match /some (cool|awesome) thing(.*)/ do |word, the_rest|
  puts "You thought the thing was #{word}. But the rest is #{the_rest}"
end
match 'some_attr' => /some (cool|awesome) thing(.*)/, 'body' => /(.*)/ do |hash|
  puts "You thought that #{hash['body']} was #{hash['some_attr'][0]}. But the rest is #{hash['some_attr'][1]}"
end
-- OR -- (if the note below about setting context/scope of annonymous functions is done)
match /some (cool|awesome) thing(.*)/ do |word, the_rest|
  puts "You thought the thing was #{word}. But the rest is #{the_rest}"
end
match 'some_attr' => /some (cool|awesome) thing(.*)/, 'body' => /(.*)/ do |hash|
  puts "You thought that #{hash['body']} was #{hash['some_attr'][0]}. But the rest is #{hash['some_attr'][1]}"
end

Improve specs to minimize use of global variables. The idea below about passing copies of the env hash around (instead of modifying it in place) might help here. I could have various bits of code being tested modify the env hash, and the final return value would be the env hash, which I could examine.

Consider making the String matcher more flexible. There could be options for:

  • Exact match

  • Case sensitivity

  • Partial matches:

    • starts with

    • ends with

    • contains

Recursion detection: It could be done by having a specific key in the message hash for parents. Before sending #call to a matcher’s proc we could run something like “message << self”. Then we could check the size of this. The maximum number of levels would need to be configurable to allow some recursion.

  • We could just rely on a stack overflow, but having recursion detection would make debugging easier.

Make helper methods defined (or included) in parent routers available in sub routers. It could be done with delegation, but that might get messy. It may be easier to not implement this and just require the user to use sub-classing to get the desired behavior.

Pass around copies of the env Hash instead of modifying the existing Hash in place.

  • This might help with multi-threading

    • Perhaps a parent router wants to delegate to 2 sub-routers which are independent of each other. The current implementation has a shared env hash, so I couldn’t use multi-threading, (though forking could work). I would have to trust the user to call #dup on at least one of the env hashes. With this new way, it is safe by default.

  • Convention would be for the ‘condition’ Procs to return a copy of the env hashes, either modified or not, depending on their needs.

    • They would still return nil or false if they don’t match.

  • We could also require (by convention only) that sub-routers also return a copy of the env hash (if they succeed) so this (optionally modified) env hash can be used for further routing.

    • This would give the original router access to both the modified env hash and the original env hash.

Find a way to allow user-defined ‘action’ procs/blocks to not have to return a true value to be considered to have matched. We still need a way to know if a sub-router matched or not. This _may_require that the code treat sub-routers and user-defined ‘action’ procs/blocks differently, which could get awkward.

Allow routers to accept an optional logger. Depending on the log level, print out info such as:

  • When a matcher is registered

  • Each time a matcher is evaluated, including what the return value was.

  • Each time a ‘action’ block is evaluated, including what the return value was.

Each time we write to the log include the following (depending on the log level):

  • The value of the env hash

  • The name of the class (so we can tell which subclass we are in)

  • Any instance variables set (so we know the config and if it changed)

Consider creating some sort of RouterRun class, each instance of which would encapsulate a call to MessageRouter::Router#call. This class would have all the helper methods as well as the #env helper method. This may help make this gem more threadsafe by keeping the shared state in the MessageRouter::Router objects immutable.

Consider having #call duplicate the router so that each run happens in its own instance. When MessageRouter::Router#call was called, call ‘self.dup.call(env, :no_dup)`. This would create a copy of the router for handling the message. It would be safe to use instance variables, except (maybe) deep-nested ones, but they could be handled by requiring the user to overwrite #dup.

Consider having a class called Run nested within the router’s namespace. Instead of allowing users to define helper methods inside the router, they would be defined inside a subclass of MessageGateway::Router::Run. MessageGateway::Router#call might look something like:

def call(env)
  Run.new(env, self).run
end

Run#run might look something like:

def run
  router.rules.detect do |condition, action|
    condition = if condition.kind_of?(Proc)
      self.instance_eval &condition
    else
      condition.call env
    end

    if condition
      action = if action.kind_of?(Proc)
        self.instance_eval &action
      else
        action.call env
      end

      return action if action
    end
  end
end

A user’s router might look like this:

class MyRouter < MessageRouter::Router
  match :hello? { say 'hi' }
  class Run < MessageRouter::Router::Run
    def hello?
      env['body'] == 'hi'
    end
    def say(msg)
      puts msg
    end
  end
end

This would make all instance variables inside the helpers safe and intuitive. I’d need to double check, but I think Ruby’s constant lookup method would allow for inheritance to work fairly intuitively as long as the Run class and the router class both inherit from the same place. (I.e. if you inherit from MyBaseRouter, then your run class should also inherit from MyBaseRouter::Run.)

License

Copyright © 2009-2012, Poll Everywhere

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

About

A router for small messages, like Tweets and SMS

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages