Skip to content

Commit

Permalink
Allow changing placeholder image host.
Browse files Browse the repository at this point in the history
  • Loading branch information
mostlyobvious committed Nov 9, 2018
1 parent 1b5ef80 commit ac71e83
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 3 deletions.
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,23 @@ Rails.application.configure do
end
```

You can even change placeholder image host, if for example you prefer [fillmurray](https://fillmurray.com):

```ruby
Rails.application.configure do
config.middleware.use ImagePlaceholder::Middleware, size_pattern: { /.*/ => '320/320' }, host: 'fillmurray.com'
end
```

Last but not least, this middleware can be used with any Rack application:

```ruby
# config.ru
use ImagePlaceholder::Middleware, size_pattern: { /.*/ => '320/320' }, host: 'fillmurray.com'
run YourRackApp
```


## Development

After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
Expand Down
2 changes: 1 addition & 1 deletion config.ru
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
require 'image_placeholder'

use ImagePlaceholder::Middleware, size_pattern: { /.*/ => 320 }
use ImagePlaceholder::Middleware, size_pattern: { /.*/ => '320/320' }, host: 'fillmurray.com'
run Rack::File.new(File.expand_path(File.join(__dir__, 'spec/support')))
5 changes: 3 additions & 2 deletions lib/image_placeholder/middleware.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@

module ImagePlaceholder
class Middleware
def initialize(app, image_extensions: %w(jpg png), size_pattern: {/.*/ => 100})
def initialize(app, image_extensions: %w(jpg png), size_pattern: {/.*/ => 100}, host: 'via.placeholder.com')
@app = app
@image_extensions = image_extensions
@size_pattern = size_pattern
@host = host
end

def call(env)
Expand All @@ -22,7 +23,7 @@ def call(env)
private

def serve_placeholder_image(size = 100)
net_response = Net::HTTP.get_response(URI("https://via.placeholder.com/#{size}"))
net_response = Net::HTTP.get_response(URI("https://#{@host}/#{size}"))
rack_response = Rack::Response.new(net_response.body, net_response.code.to_i)
safe_headers = net_response.to_hash
.reject { |key, _| hop_by_hop_header_fields.include?(key.downcase) }
Expand Down
1 change: 1 addition & 0 deletions spec/middleware_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ def app
Rack::Lint.new(
Middleware.new(
Rack::File.new(static_path),
host: 'via.placeholder.com',
image_extensions: %w(jpg),
size_pattern: {
%r{/uploads/.*/s_[0-9]+\.[a-z]{3}$} => 200,
Expand Down

0 comments on commit ac71e83

Please sign in to comment.