I am testing this in local. My ip is 127.0.0.1. The ip_permissions table, is empty. When I browse the site, everything works as expected.
Now, I want to simulate browsing the site with a banned IP. So I add the IP into the ip_permissions table via:
IpPermission.create!(:ip => '127.0.0.1', :note => 'foobar', :category => 'blacklist')
In Rails console, I clear the cache via; Rails.cache.clear. I browse the site. I don't get sent to pages#blacklist.
If I restart the server. And browse the site, then I get sent to pages#blacklist. Why do I need to restart the server every time the ip_permissions table is updated? Shouldn't it fetch it based on cache?
Routes look like:
class BlacklistConstraint
def initialize
@blacklist = IpPermission.blacklist
end
def matches?(request)
@blacklist.map { |b| b.ip }.include? request.remote_ip
end
end
Foobar::Application.routes.draw do
match '/(*path)' => 'pages#blacklist', :constraints => BlacklistConstraint.new
....
end
My model looks like:
class IpPermission < ActiveRecord::Base
validates_presence_of :ip, :note, :category
validates_uniqueness_of :ip, :scope => [:category]
validates :category, :inclusion => { :in => ['whitelist', 'blacklist'] }
def self.whitelist
Rails.cache.fetch('whitelist', :expires_in => 1.month) { self.where(:category => 'whitelist').all }
end
def self.blacklist
Rails.cache.fetch('blacklist', :expires_in => 1.month) { self.where(:category => 'blacklist').all }
end
end