Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Added GDBM support and code examples.

  • Loading branch information...
commit 98d039a12799faf07543a56b7566c8dd551a4de4 1 parent 3eb22cc
@bendiken bendiken authored
Showing with 25 additions and 1 deletion.
  1. +8 −0 README.md
  2. +7 −0 etc/gdbm.ru
  3. +10 −1 lib/rack/throttle/limiter.rb
View
8 README.md
@@ -10,12 +10,14 @@ Sinatra.
Features
--------
+
* Throttles a Rack application by enforcing a minimum interval (by default,
1 second) between subsequent HTTP requests from a particular client.
* Compatible with any Rack application and any Rack-based framework.
* Stores rate-limiting counters in any key/value store implementation that
responds to `#[]`/`#[]=` (like Ruby's hashes) or to `#get`/`#set` (like
memcached or Redis).
+* Compatible with the [gdbm][] binding included in Ruby's standard library.
* Compatible with the [memcached][], [memcache-client][], [memcache][] and
[redis][] gems.
* Compatible with [Heroku][]'s [memcached add-on][Heroku memcache]
@@ -36,6 +38,11 @@ Examples
use Rack::Throttle::Interval, :min => 3.0
+### Using GDBM to store rate-limiting counters
+
+ require 'gdbm'
+ use Rack::Throttle::Interval, :cache => GDBM.new('tmp/throttle.db')
+
### Using Memcached to store rate-limiting counters
require 'memcached'
@@ -134,6 +141,7 @@ License
information, see <http://unlicense.org/> or the accompanying UNLICENSE file.
[Rack]: http://rack.rubyforge.org/
+[gdbm]: http://ruby-doc.org/stdlib/libdoc/gdbm/rdoc/classes/GDBM.html
[memcached]: http://rubygems.org/gems/memcached
[memcache-client]: http://rubygems.org/gems/memcache-client
[memcache]: http://rubygems.org/gems/memcache
View
7 etc/gdbm.ru
@@ -0,0 +1,7 @@
+$:.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
+require 'rack/throttle'
+require 'gdbm'
+
+use Rack::Throttle::Interval, :min => 3.0, :cache => GDBM.new('/tmp/throttle.db')
+
+run lambda { |env| [200, {'Content-Type' => 'text/plain'}, "Hello, world!\n"] }
View
11 lib/rack/throttle/limiter.rb
@@ -122,7 +122,16 @@ def cache_get(key, default = nil)
def cache_set(key, value)
case
when cache.respond_to?(:[]=)
- cache[key] = value
+ begin
+ cache[key] = value
+ rescue TypeError => e
+ # GDBM throws a "TypeError: can't convert Float into String"
+ # exception when trying to store a Float. On the other hand, we
+ # don't want to unnecessarily coerce the value to a String for
+ # any stores that do support other data types (e.g. in-memory
+ # hash objects). So, this is a compromise.
+ cache[key] = value.to_s
+ end
when cache.respond_to?(:set)
cache.set(key, value)
end
Please sign in to comment.
Something went wrong with that request. Please try again.