Skip to content

Instantly share code, notes, and snippets.

@johnkchow
Created May 30, 2012 16:05
Show Gist options
  • Save johnkchow/2837275 to your computer and use it in GitHub Desktop.
Save johnkchow/2837275 to your computer and use it in GitHub Desktop.
Simple action routing architecture w/ EM
# This is the base class for all Action processing classes. This is somewhat
# similar in concept to the Rails Controller/Action, and how the Rails router
# knows by convention what class/method to call.
class ActionBase
# Store all inherited classes.
def self.inherited(klass)
@actions ||= {}
@actions[klass.name] = klass
end
class << self
#
def route_to_action(name, data, connection)
klass = @actions[name]
action = klass.new(connection)
catch(:end_action) {
action.process(data.with_indifferent_access)
}
return action.response
end
end
attr_accessor :connection
# @param [EM::Connection] connection The connection that sent the message
def initialize(connection)
@connection = connection
end
# This is very much like the Controller#render in Rails
def respond(message)
@response = message
throw(:end_action)
end
# This is similar to a rendered view ready to be sent back to the Client
def response
return nil unless @response
klass = self.class.name
klass = klass[0].downcase + klass[1..-1]
response_class = klass.gsub("Message", "Response")
return @response.merge(:class => response_class, :status_code => @status_code)
end
end
# Any incoming message with the format of '{"class":"RedirectAction", ...} will
# be routed to RedirectMessage#process method
class RedirectAction < ActionBase
def process(data)
respond(:redirect_to => "example_redirection_message")
end
end
class ServerConnection < EM::Connection
# This is where the message first enters our App
def receive_data(data)
# use a buffer tokenizer to convert raw JSON to hash i.e. EM::BufferedTokenizer
bufferd_hash = JSON.parse(buffered_data).with_indifferent_access
action = data[:class]
# Lookup the corresponding Action class to process data
output = ActionBase.route_to_action(action, data, self)
# Respond back with the response
send_data(output.to_json)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment