We use Dalli for memcached-based route caching with Padrino 0.12. I wanted to add rate throttling for all /api route handlers to our app and wanted to use Dalli for that as well.
I found Rack::Attack, a really nice Rack-based gem that allows for connection throttling, blacklisting and whitelisting of clients. Cool stuff, perfect for our needs. Except it expects the caching layer to conform to the ActiveSupport::Cache::Store interface:
Note that Rack::Attack.cache is only used for throttling; not
blacklisting & whitelisting. Your cache store must implement increment
and write like ActiveSupport::Cache::Store.
Darn! Oh, wait, not so bad. But I don’t want to have to do inline creation of the client etc in app/app.rb, especially because I’m likely to have different throttling requirements for different environments.
Modules and blocks to the rescue!
- Create a subclass for the Dalli client that conforms to the ActiveSupport API.
- Create a helper method that can be used inline in app/app.rb that takes a block with an environment-specific policy.
- Wrap the use and cache client creation so it doesn’t have to be repeated in app/app.rb
Our security mixin module with configure_security helper
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
|
Now use it in app/app.rb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|