Class: LoremImageWare::Middleware
- Inherits:
-
Object
- Object
- LoremImageWare::Middleware
- Defined in:
- lib/lorem-image-ware.rb
Instance Method Summary collapse
- #_call(env) ⇒ Object
- #call(env) ⇒ Object
- #fetch_image(url) ⇒ Object
-
#initialize(app, options = {}) ⇒ Middleware
constructor
A new instance of Middleware.
- #provider ⇒ Object
- #root ⇒ Object
- #serve_image(url) ⇒ Object
Constructor Details
#initialize(app, options = {}) ⇒ Middleware
Returns a new instance of Middleware.
56 57 58 59 |
# File 'lib/lorem-image-ware.rb', line 56 def initialize(app, = {}) @app = app @options = end |
Instance Method Details
#_call(env) ⇒ Object
65 66 67 68 69 70 71 72 73 74 |
# File 'lib/lorem-image-ware.rb', line 65 def _call(env) request = Rack::Request.new(env) if request.fullpath =~ %r{^#{root}/image/(\d+)/(\d+)/?(/?([a-z]+))?}i url = provider.url(width: $1, height: $2, type: $4) serve_image(url) else @app.call(env) end end |
#call(env) ⇒ Object
61 62 63 |
# File 'lib/lorem-image-ware.rb', line 61 def call(env) self.dup._call(env) end |
#fetch_image(url) ⇒ Object
86 87 88 89 90 91 92 93 94 |
# File 'lib/lorem-image-ware.rb', line 86 def fetch_image(url) @@image_cache ||= Hash.new do |h, url| uri = URI(url) res = Net::HTTP.get_response(uri) h[url] = res.body if res.code == "200" end @@image_cache[url] end |
#provider ⇒ Object
100 101 102 |
# File 'lib/lorem-image-ware.rb', line 100 def provider @provider ||= @options.fetch(:provider, LoremPixelProvider.new) end |
#root ⇒ Object
96 97 98 |
# File 'lib/lorem-image-ware.rb', line 96 def root @options.fetch(:root, "/lorem") end |
#serve_image(url) ⇒ Object
76 77 78 79 80 81 82 83 84 |
# File 'lib/lorem-image-ware.rb', line 76 def serve_image(url) if image_data = fetch_image(url) Rack::Response.new([], 200, {"Content-Type" => "image/jpeg"}).finish do |res| res.write(image_data) end else [404, {"Content-Type" => "test/plain"}, ["Not found"]] end end |