Skip to content

Commit

Permalink
Added GDBM support and code examples.
Browse files Browse the repository at this point in the history
  • Loading branch information
artob committed Mar 21, 2010
1 parent 3eb22cc commit 98d039a
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 1 deletion.
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand All @@ -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'
Expand Down Expand Up @@ -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
Expand Down
7 changes: 7 additions & 0 deletions etc/gdbm.ru
Original file line number Diff line number Diff line change
@@ -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"] }
11 changes: 10 additions & 1 deletion lib/rack/throttle/limiter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 98d039a

Please sign in to comment.