lib/safubot/bot.rb in safubot-0.0.5 vs lib/safubot/bot.rb in safubot-0.0.6

- old
+ new

@@ -76,11 +76,11 @@ # inherit from this class when building your own bot, but # delegation is also entirely feasible. class Bot include Evented - attr_reader :opts, :twitter, :xmpp + attr_reader :opts, :twitter, :xmpp, :subbots ## # Records an error in processing and emits a corresponding :request_error event. # @param req The Request for which the error was encountered. # @param e The caught Exception. @@ -217,56 +217,54 @@ end push end end - # Runs an initial request-processing loop and then forks the streaming processes. - def run_nowait + def run pull; process; push - @twitter.run if @twitter - @xmpp.run if @xmpp - end - # Calls run_nowait and then waits for all child processes. - def run - run_nowait - begin - Process.waitall - rescue Interrupt - stop + @subbots[0..-2].each do |subbot| + subbot.fork end + + # Run the final subbot in this process to avoid unnecessary forking + # and thus memory consumption. + @subbots[-1].run end # Shuts down the streaming processes. def stop - @twitter.stop if @twitter - @xmpp.stop if @xmpp + @subbots.each { |subbot| subbot.stop } end # Initialises Twitter-related functionality. def enable_twitter(opts={}) @twitter = Twitter::Bot.new(opts) @twitter.on(:request) do |req| process_request(req) req.responses.where(:dispatched => false).map(&method(:dispatch)) end + @subbots.push(@twitter) end # Initialises XMPP-related functionality. def enable_xmpp(options={}) defaults = { :jid => nil, :password => nil } @xmpp = XMPP::Bot.new(defaults.merge(options)) @xmpp.on(:request) do |req| process_request(req) req.responses.where(:dispatched => false).map(&method(:dispatch)) end + @subbots.push(@xmpp) end def initialize(options={}) defaults = { :database => "safubot" } @opts = defaults.merge(options) MongoMapper.database = @opts[:database] MongoMapper.connection = Mongo::Connection.new('localhost', 27017, :pool_size => 5) + MongoMapper::Document.plugin(MongoMapper::Plugins::IdentityMap) @handlers = {} + @subbots = [] end end end