Created
March 1, 2011 18:12
-
-
Save lusis/849571 to your computer and use it in GitHub Desktop.
In-process EM.spawn for Sinatra app
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'sinatra/base' | |
module FavIcon | |
class Service < Sinatra::Base | |
configure do | |
set :app_file, __FILE__ | |
set :root, File.expand_path(File.join(File.dirname(__FILE__), '..','..')) | |
set :server, %w[thin mongrel webrick] | |
set :logging, true | |
set :raise_errors, false | |
set :show_exceptions, false | |
set :run, false | |
set :cache_dir, ENV['FAVICON_CACHE_DIR'] || File.expand_path(File.join(File.dirname(__FILE__), '..', '..', 'cache')) | |
set :logger, FavIcon::LOGGER | |
set :default_icon, "#{cache_dir}/default.png" | |
end | |
configure(:development) do | |
begin | |
require 'sinatra/reloader' | |
register Sinatra::Reloader | |
rescue LoadError | |
settings.logger.warn("sinatra-reloader gem missing. reloading disabled") | |
end | |
end | |
not_found do | |
content_type 'image/png' | |
File.read(settings.default_icon) | |
end | |
error do | |
content_type 'image/png' | |
File.read(settings.default_icon) | |
end | |
get '/favicon.ico' do | |
content_type 'image/png' | |
File.read(settings.default_icon) | |
end | |
get '/:url' do |url| | |
content_type "image/png" | |
(url =~ /^www\..*/).nil? ? url=url : url=url.gsub(/^www\.(.*)/,'\1') | |
file_name = "#{url}.favicon.png" | |
icon = File.join(settings.cache_dir, file_name) | |
if File.exists?(icon) | |
File.read(icon) | |
else | |
EM.reactor_running? ? settings.worker.notify(url) : settings.logger.warn("Reactor not running") | |
File.read(settings.default_icon) | |
end | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
$:.unshift(File.expand_path(File.join(File.dirname(__FILE__), "..", "lib"))) | |
require 'eventmachine' | |
require 'thin' | |
require 'favicon_service' | |
require 'favicon_service/app' | |
EventMachine.run do | |
grabber = EM.spawn {|url| | |
# Do some stuff with url | |
} | |
app = FavIcon::Service # This is my sinatra/base app | |
app.set :worker, grabber | |
Thin::Server.start('0.0.0.0', 9292, app) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This will sort of fall apart if you use rackup w/Thin because Thin IS running in a reactor. For robustness, you should define a default "settings.worker" fallback to be used if running under, say, webrick.