The idea of this class is I would be able to limit the use of an api/method by sending it a key which would be an ip address or username and it would tell me if they are under the rate limit.
Here is the code:
require 'time' class RateLimit def initialize(time, limit) @reset_on = Time.now + time @limit = limit @keys = {} end def increment(key) reset if Time.now >= @reset_on if @keys[key] == nil @keys[key] = 1 else @keys[key] += 1 end return @keys[key] >= @limit end def current_level(key) reset if Time.now >= @reset_on return @keys[key] end def is_limited?(key) reset if Time.now >= @reset_on return @keys[key] != nil && @keys[key] >= @limit end def reset @reset_on = Time.now + @limit @keys = {} end end
To me this seems like some pretty clean code but are there any issues I have missed or things that could be done better?