repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
mislav/will_paginate | https://github.com/mislav/will_paginate/blob/50017c3eb0712e7b3a53268a81e81a184b7a49f6/spec/spec_helper.rb | spec/spec_helper.rb | require 'rspec'
require 'view_helpers/view_example_group'
Dir[File.expand_path('../matchers/*_matcher.rb', __FILE__)].each { |matcher| require matcher }
RSpec::Matchers.alias_matcher :include_phrase, :include
RSpec.configure do |config|
config.include Module.new {
protected
def have_deprecation(msg)
output(/^DEPRECATION WARNING: #{Regexp.escape(msg)}/).to_stderr
end
def ignore_deprecation
if ActiveSupport::Deprecation.respond_to?(:silence)
ActiveSupport::Deprecation.silence { yield }
else
yield
end
end
}
config.mock_with :mocha
config.backtrace_exclusion_patterns << /view_example_group/
config.expose_dsl_globally = false
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
config.shared_context_metadata_behavior = :apply_to_host_groups
config.disable_monkey_patching!
end
| ruby | MIT | 50017c3eb0712e7b3a53268a81e81a184b7a49f6 | 2026-01-04T15:42:46.511340Z | false |
mislav/will_paginate | https://github.com/mislav/will_paginate/blob/50017c3eb0712e7b3a53268a81e81a184b7a49f6/spec/finders/active_record_spec.rb | spec/finders/active_record_spec.rb | require 'spec_helper'
require 'will_paginate/active_record'
require File.expand_path('../activerecord_test_connector', __FILE__)
ActiverecordTestConnector.setup
RSpec.describe WillPaginate::ActiveRecord do
extend ActiverecordTestConnector::FixtureSetup
fixtures :topics, :replies, :users, :projects, :developers_projects
it "should integrate with ActiveRecord::Base" do
expect(ActiveRecord::Base).to respond_to(:paginate)
end
it "should paginate" do
expect {
users = User.paginate(:page => 1, :per_page => 5).to_a
expect(users.length).to eq(5)
}.to execute(2).queries
end
it "should fail when encountering unknown params" do
expect {
User.paginate :foo => 'bar', :page => 1, :per_page => 4
}.to raise_error(ArgumentError)
end
describe "relation" do
it "should return a relation" do
rel = nil
expect {
rel = Developer.paginate(:page => 1)
expect(rel.per_page).to eq(10)
expect(rel.current_page).to eq(1)
}.to execute(0).queries
expect {
expect(rel.total_pages).to eq(2)
}.to execute(1).queries
end
it "should keep per-class per_page number" do
rel = Developer.order('id').paginate(:page => 1)
expect(rel.per_page).to eq(10)
end
it "should be able to change per_page number" do
rel = Developer.order('id').paginate(:page => 1).limit(5)
expect(rel.per_page).to eq(5)
end
it "remembers pagination in sub-relations" do
rel = Topic.paginate(:page => 2, :per_page => 3)
expect {
expect(rel.total_entries).to eq(4)
}.to execute(1).queries
rel = rel.mentions_activerecord
expect(rel.current_page).to eq(2)
expect(rel.per_page).to eq(3)
expect {
expect(rel.total_entries).to eq(1)
}.to execute(1).queries
end
it "supports the page() method" do
rel = Developer.page('1').order('id')
expect(rel.current_page).to eq(1)
expect(rel.per_page).to eq(10)
expect(rel.offset).to eq(0)
rel = rel.limit(5).page(2)
expect(rel.per_page).to eq(5)
expect(rel.offset).to eq(5)
end
it "raises on invalid page number" do
expect {
Developer.page('foo')
}.to raise_error(ArgumentError)
end
it "supports first limit() then page()" do
rel = Developer.limit(3).page(3)
expect(rel.offset).to eq(6)
end
it "supports first page() then limit()" do
rel = Developer.page(3).limit(3)
expect(rel.offset).to eq(6)
end
it "supports #first" do
rel = Developer.order('id').page(2).per_page(4)
expect(rel.first).to eq(users(:dev_5))
expect(rel.first(2)).to eq(users(:dev_5, :dev_6))
end
it "supports #last" do
rel = Developer.order('id').page(2).per_page(4)
expect(rel.last).to eq(users(:dev_8))
expect(rel.last(2)).to eq(users(:dev_7, :dev_8))
expect(rel.page(3).last).to eq(users(:poor_jamis))
end
end
describe "counting" do
it "should guess the total count" do
expect {
topics = Topic.paginate :page => 2, :per_page => 3
expect(topics.total_entries).to eq(4)
}.to execute(1).queries
end
it "should guess that there are no records" do
expect {
topics = Topic.where(:project_id => 999).paginate :page => 1, :per_page => 3
expect(topics.total_entries).to eq(0)
}.to execute(1).queries
end
it "forgets count in sub-relations" do
expect {
topics = Topic.paginate :page => 1, :per_page => 3
expect(topics.total_entries).to eq(4)
expect(topics.where('1 = 1').total_entries).to eq(4)
}.to execute(2).queries
end
it "supports empty? method" do
topics = Topic.paginate :page => 1, :per_page => 3
expect {
expect(topics).not_to be_empty
}.to execute(1).queries
end
it "support empty? for grouped queries" do
topics = Topic.group(:project_id).paginate :page => 1, :per_page => 3
expect {
expect(topics).not_to be_empty
}.to execute(1).queries
end
it "supports `size` for grouped queries" do
topics = Topic.group(:project_id).paginate :page => 1, :per_page => 3
expect {
expect(topics.size).to eq({nil=>2, 1=>2})
}.to execute(1).queries
end
it "overrides total_entries count with a fixed value" do
expect {
topics = Topic.paginate :page => 1, :per_page => 3, :total_entries => 999
expect(topics.total_entries).to eq(999)
# value is kept even in sub-relations
expect(topics.where('1 = 1').total_entries).to eq(999)
}.to execute(0).queries
end
it "supports a non-int for total_entries" do
topics = Topic.paginate :page => 1, :per_page => 3, :total_entries => "999"
expect(topics.total_entries).to eq(999)
end
it "overrides empty? count call with a total_entries fixed value" do
expect {
topics = Topic.paginate :page => 1, :per_page => 3, :total_entries => 999
expect(topics).not_to be_empty
}.to execute(0).queries
end
it "removes :include for count" do
expect {
developers = Developer.paginate(:page => 1, :per_page => 1).includes(:projects)
expect(developers.total_entries).to eq(11)
expect($query_sql.last).not_to match(/\bJOIN\b/)
}.to execute(1).queries
end
it "keeps :include for count when they are referenced in :conditions" do
developers = Developer.paginate(:page => 1, :per_page => 1).includes(:projects)
with_condition = developers.where('projects.id > 1')
with_condition = with_condition.references(:projects) if with_condition.respond_to?(:references)
expect(with_condition.total_entries).to eq(1)
expect($query_sql.last).to match(/\bJOIN\b/)
end
it "should count with group" do
expect(Developer.group(:salary).page(1).total_entries).to eq(4)
end
it "should count with select" do
expect(Topic.select('title, content').page(1).total_entries).to eq(4)
end
it "removes :reorder for count with group" do
Project.group(:id).reorder(:id).page(1).total_entries
expect($query_sql.last).not_to match(/\ORDER\b/)
end
it "should not have zero total_pages when the result set is empty" do
expect(Developer.where("1 = 2").page(1).total_pages).to eq(1)
end
end
it "should not ignore :select parameter when it says DISTINCT" do
users = User.select('DISTINCT salary').paginate :page => 2
expect(users.total_entries).to eq(5)
end
describe "paginate_by_sql" do
it "should respond" do
expect(User).to respond_to(:paginate_by_sql)
end
it "should paginate" do
expect {
sql = "select content from topics where content like '%futurama%'"
topics = Topic.paginate_by_sql sql, :page => 1, :per_page => 1
expect(topics.total_entries).to eq(1)
expect(topics.first.attributes.has_key?('title')).to be(false)
}.to execute(2).queries
end
it "should respect total_entries setting" do
expect {
sql = "select content from topics"
topics = Topic.paginate_by_sql sql, :page => 1, :per_page => 1, :total_entries => 999
expect(topics.total_entries).to eq(999)
}.to execute(1).queries
end
it "defaults to page 1" do
sql = "select content from topics"
topics = Topic.paginate_by_sql sql, :page => nil, :per_page => 1
expect(topics.current_page).to eq(1)
expect(topics.size).to eq(1)
end
it "should strip the order when counting" do
expected = topics(:ar)
expect {
sql = "select id, title, content from topics order by topics.title"
topics = Topic.paginate_by_sql sql, :page => 1, :per_page => 2
expect(topics.first).to eq(expected)
}.to execute(2).queries
expect($query_sql.last).to include('COUNT')
expect($query_sql.last).not_to include('order by topics.title')
end
it "shouldn't change the original query string" do
query = 'select * from topics where 1 = 2'
original_query = query.dup
Topic.paginate_by_sql(query, :page => 1)
expect(query).to eq(original_query)
end
end
it "doesn't mangle options" do
options = { :page => 1 }
options.expects(:delete).never
options_before = options.dup
Topic.paginate(options)
expect(options).to eq(options_before)
end
it "should get first page of Topics with a single query" do
expect {
result = Topic.paginate :page => nil
result.to_a # trigger loading of records
expect(result.current_page).to eq(1)
expect(result.total_pages).to eq(1)
expect(result.size).to eq(4)
}.to execute(1).queries
end
it "should get second (inexistent) page of Topics, requiring 1 query" do
expect {
result = Topic.paginate :page => 2
expect(result.total_pages).to eq(1)
expect(result).to be_empty
}.to execute(1).queries
end
describe "associations" do
it "should paginate" do
dhh = users(:david)
expected_name_ordered = projects(:action_controller, :active_record)
expected_id_ordered = projects(:active_record, :action_controller)
expect {
# with association-specified order
result = ignore_deprecation {
dhh.projects.includes(:topics).order('projects.name').paginate(:page => 1)
}
expect(result.to_a).to eq(expected_name_ordered)
expect(result.total_entries).to eq(2)
}.to execute(2).queries
# with explicit order
result = dhh.projects.paginate(:page => 1).reorder('projects.id')
expect(result).to eq(expected_id_ordered)
expect(result.total_entries).to eq(2)
expect {
dhh.projects.order('projects.id').limit(4).to_a
}.not_to raise_error
result = dhh.projects.paginate(:page => 1, :per_page => 4).reorder('projects.id')
expect(result).to eq(expected_id_ordered)
# has_many with implicit order
topic = Topic.find(1)
expected = replies(:spam, :witty_retort)
# FIXME: wow, this is ugly
expect(topic.replies.paginate(:page => 1).map(&:id).sort).to eq(expected.map(&:id).sort)
expect(topic.replies.paginate(:page => 1).reorder('replies.id ASC')).to eq(expected.reverse)
end
it "should paginate through association extension" do
project = Project.order('id').first
expected = [replies(:brave)]
expect {
result = project.replies.only_recent.paginate(:page => 1)
expect(result).to eq(expected)
}.to execute(1).queries
end
end
it "should paginate with joins" do
result = nil
join_sql = 'LEFT JOIN developers_projects ON users.id = developers_projects.developer_id'
expect {
result = Developer.where('developers_projects.project_id = 1').joins(join_sql).paginate(:page => 1)
result.to_a # trigger loading of records
expect(result.size).to eq(2)
developer_names = result.map(&:name)
expect(developer_names).to include('David')
expect(developer_names).to include('Jamis')
}.to execute(1).queries
expect {
expected = result.to_a
result = Developer.where('developers_projects.project_id = 1').joins(join_sql).paginate(:page => 1)
expect(result).to eq(expected)
expect(result.total_entries).to eq(2)
}.to execute(1).queries
end
it "should paginate with group" do
result = nil
expect {
result = Developer.select('salary').order('salary').group('salary').
paginate(:page => 1, :per_page => 10).to_a
}.to execute(1).queries
expected = users(:david, :jamis, :dev_10, :poor_jamis).map(&:salary).sort
expect(result.map(&:salary)).to eq(expected)
end
it "should not paginate with dynamic finder" do
expect {
Developer.paginate_by_salary(100000, :page => 1, :per_page => 5)
}.to raise_error(NoMethodError)
end
describe "scopes" do
it "should paginate" do
result = Developer.poor.paginate :page => 1, :per_page => 1
expect(result.size).to eq(1)
expect(result.total_entries).to eq(2)
end
it "should paginate on habtm association" do
project = projects(:active_record)
expect {
result = ignore_deprecation { project.developers.poor.paginate :page => 1, :per_page => 1 }
expect(result.size).to eq(1)
expect(result.total_entries).to eq(1)
}.to execute(2).queries
end
it "should paginate on hmt association" do
project = projects(:active_record)
expected = [replies(:brave)]
expect {
result = project.replies.recent.paginate :page => 1, :per_page => 1
expect(result).to eq(expected)
expect(result.total_entries).to eq(1)
}.to execute(2).queries
end
it "should paginate on has_many association" do
project = projects(:active_record)
expected = [topics(:ar)]
expect {
result = project.topics.mentions_activerecord.paginate :page => 1, :per_page => 1
expect(result).to eq(expected)
expect(result.total_entries).to eq(1)
}.to execute(2).queries
end
end
it "should not paginate an array of IDs" do
expect {
Developer.paginate((1..8).to_a, :per_page => 3, :page => 2, :order => 'id')
}.to raise_error(ArgumentError)
end
it "errors out for invalid values" do |variable|
expect {
# page that results in an offset larger than BIGINT
Project.page(307445734561825862)
}.to raise_error(WillPaginate::InvalidPage, "invalid offset: 9223372036854775830")
end
end
| ruby | MIT | 50017c3eb0712e7b3a53268a81e81a184b7a49f6 | 2026-01-04T15:42:46.511340Z | false |
mislav/will_paginate | https://github.com/mislav/will_paginate/blob/50017c3eb0712e7b3a53268a81e81a184b7a49f6/spec/finders/activerecord_test_connector.rb | spec/finders/activerecord_test_connector.rb | require 'active_record'
require 'active_record/fixtures'
require 'stringio'
require 'erb'
require 'time'
require 'date'
require 'yaml'
# forward compatibility with Rails 7 (needed for time expressions within fixtures)
class Time
alias_method :to_fs, :to_s
end unless Time.new.respond_to?(:to_fs)
# monkeypatch needed for Ruby 3.1 & Rails 6.0
YAML.module_eval do
class << self
alias_method :_load_orig, :load
def load(yaml_str)
_load_orig(yaml_str, permitted_classes: [Symbol, Date, Time])
end
end
end if YAML.method(:load).parameters.include?([:key, :permitted_classes])
$query_count = 0
$query_sql = []
ignore_sql = /
^(
PRAGMA | SHOW\ (max_identifier_length|search_path) |
SELECT\ (currval|CAST|@@IDENTITY|@@ROWCOUNT) |
SHOW\ ((FULL\ )?FIELDS|TABLES)
)\b |
\bFROM\ (sqlite_master|pg_tables|pg_attribute)\b
/x
ActiveSupport::Notifications.subscribe(/^sql\./) do |*args|
payload = args.last
unless payload[:name] =~ /^Fixture/ or payload[:sql] =~ ignore_sql
$query_count += 1
$query_sql << payload[:sql]
end
end
module ActiverecordTestConnector
extend self
attr_accessor :connected
FIXTURES_PATH = File.expand_path('../../fixtures', __FILE__)
# Set our defaults
self.connected = false
def setup
unless self.connected
setup_connection
load_schema
add_load_path FIXTURES_PATH
self.connected = true
end
end
private
module Autoloader
def const_missing(name)
super
rescue NameError
file = File.join(FIXTURES_PATH, name.to_s.underscore)
if File.exist?("#{file}.rb")
require file
const_get(name)
else
raise $!
end
end
end
def add_load_path(path)
if ActiveSupport::Dependencies.respond_to?(:autoloader=)
Object.singleton_class.include Autoloader
else
dep = defined?(ActiveSupport::Dependencies) ? ActiveSupport::Dependencies : ::Dependencies
dep.autoload_paths.unshift path
end
end
def setup_connection
db = ENV['DB'].blank?? 'sqlite3' : ENV['DB']
erb = ERB.new(File.read(File.expand_path('../../database.yml', __FILE__)))
configurations = YAML.load(erb.result)
raise "no configuration for '#{db}'" unless configurations.key? db
configuration = configurations[db]
# ActiveRecord::Base.logger = Logger.new(STDOUT) if $0 == 'irb'
puts "using #{configuration['adapter']} adapter"
ActiveRecord::Base.configurations = { db => configuration }
ActiveRecord::Base.establish_connection(db.to_sym)
if ActiveRecord.respond_to?(:default_timezone=)
ActiveRecord.default_timezone = :utc
else
ActiveRecord::Base.default_timezone = :utc
end
end
def load_schema
begin
$stdout = StringIO.new
ActiveRecord::Migration.verbose = false
load File.join(FIXTURES_PATH, 'schema.rb')
ensure
$stdout = STDOUT
end
end
module FixtureSetup
def fixtures(*tables)
table_names = tables.map { |t| t.to_s }
fixtures = ActiveRecord::FixtureSet.create_fixtures(ActiverecordTestConnector::FIXTURES_PATH, table_names)
@@loaded_fixtures = {}
@@fixture_cache = {}
unless fixtures.nil?
fixtures.each { |f| @@loaded_fixtures[f.table_name] = f }
end
table_names.each do |table_name|
define_method(table_name) do |*names|
@@fixture_cache[table_name] ||= {}
instances = names.map do |name|
if @@loaded_fixtures[table_name][name.to_s]
@@fixture_cache[table_name][name] ||= @@loaded_fixtures[table_name][name.to_s].find
else
raise StandardError, "No fixture with name '#{name}' found for table '#{table_name}'"
end
end
instances.size == 1 ? instances.first : instances
end
end
end
end
end
| ruby | MIT | 50017c3eb0712e7b3a53268a81e81a184b7a49f6 | 2026-01-04T15:42:46.511340Z | false |
mislav/will_paginate | https://github.com/mislav/will_paginate/blob/50017c3eb0712e7b3a53268a81e81a184b7a49f6/spec/fixtures/project.rb | spec/fixtures/project.rb | class Project < ActiveRecord::Base
has_and_belongs_to_many :developers, :join_table => 'developers_projects'
has_many :topics
# :finder_sql => 'SELECT * FROM topics WHERE (topics.project_id = #{id})',
# :counter_sql => 'SELECT COUNT(*) FROM topics WHERE (topics.project_id = #{id})'
has_many :replies, :through => :topics do
def only_recent(params = {})
where(['replies.created_at > ?', 15.minutes.ago])
end
end
end
| ruby | MIT | 50017c3eb0712e7b3a53268a81e81a184b7a49f6 | 2026-01-04T15:42:46.511340Z | false |
mislav/will_paginate | https://github.com/mislav/will_paginate/blob/50017c3eb0712e7b3a53268a81e81a184b7a49f6/spec/fixtures/topic.rb | spec/fixtures/topic.rb | class Topic < ActiveRecord::Base
has_many :replies, :dependent => :destroy
belongs_to :project
scope :mentions_activerecord, lambda {
where(['topics.title LIKE ?', '%ActiveRecord%'])
}
end
| ruby | MIT | 50017c3eb0712e7b3a53268a81e81a184b7a49f6 | 2026-01-04T15:42:46.511340Z | false |
mislav/will_paginate | https://github.com/mislav/will_paginate/blob/50017c3eb0712e7b3a53268a81e81a184b7a49f6/spec/fixtures/reply.rb | spec/fixtures/reply.rb | class Reply < ActiveRecord::Base
scope :recent, lambda {
where(['replies.created_at > ?', 15.minutes.ago]).
order('replies.created_at DESC')
}
validates_presence_of :content
end
| ruby | MIT | 50017c3eb0712e7b3a53268a81e81a184b7a49f6 | 2026-01-04T15:42:46.511340Z | false |
mislav/will_paginate | https://github.com/mislav/will_paginate/blob/50017c3eb0712e7b3a53268a81e81a184b7a49f6/spec/fixtures/schema.rb | spec/fixtures/schema.rb | ActiveRecord::Schema.define do
create_table "users", :force => true do |t|
t.column "name", :text
t.column "salary", :integer, :default => 70000
t.column "created_at", :datetime
t.column "updated_at", :datetime
t.column "type", :text
end
create_table "projects", :force => true do |t|
t.column "name", :text
end
create_table "developers_projects", :id => false, :force => true do |t|
t.column "developer_id", :integer, :null => false
t.column "project_id", :integer, :null => false
t.column "joined_on", :date
t.column "access_level", :integer, :default => 1
end
create_table "topics", :force => true do |t|
t.column "project_id", :integer
t.column "title", :string
t.column "subtitle", :string
t.column "content", :text
t.column "created_at", :datetime
t.column "updated_at", :datetime
end
create_table "replies", :force => true do |t|
t.column "content", :text
t.column "created_at", :datetime
t.column "updated_at", :datetime
t.column "topic_id", :integer
end
end
| ruby | MIT | 50017c3eb0712e7b3a53268a81e81a184b7a49f6 | 2026-01-04T15:42:46.511340Z | false |
mislav/will_paginate | https://github.com/mislav/will_paginate/blob/50017c3eb0712e7b3a53268a81e81a184b7a49f6/spec/fixtures/admin.rb | spec/fixtures/admin.rb | class Admin < User
has_many :companies
end
| ruby | MIT | 50017c3eb0712e7b3a53268a81e81a184b7a49f6 | 2026-01-04T15:42:46.511340Z | false |
mislav/will_paginate | https://github.com/mislav/will_paginate/blob/50017c3eb0712e7b3a53268a81e81a184b7a49f6/spec/fixtures/developer.rb | spec/fixtures/developer.rb | class Developer < User
has_and_belongs_to_many :projects, :join_table => 'developers_projects'
scope :poor, lambda {
where(['salary <= ?', 80000]).order('salary')
}
def self.per_page() 10 end
end
| ruby | MIT | 50017c3eb0712e7b3a53268a81e81a184b7a49f6 | 2026-01-04T15:42:46.511340Z | false |
mislav/will_paginate | https://github.com/mislav/will_paginate/blob/50017c3eb0712e7b3a53268a81e81a184b7a49f6/spec/fixtures/user.rb | spec/fixtures/user.rb | class User < ActiveRecord::Base
end
| ruby | MIT | 50017c3eb0712e7b3a53268a81e81a184b7a49f6 | 2026-01-04T15:42:46.511340Z | false |
mislav/will_paginate | https://github.com/mislav/will_paginate/blob/50017c3eb0712e7b3a53268a81e81a184b7a49f6/spec/view_helpers/action_view_spec.rb | spec/view_helpers/action_view_spec.rb | # encoding: utf-8
require 'spec_helper'
require 'action_controller'
require 'action_view'
require 'will_paginate/view_helpers/action_view'
require 'will_paginate/collection'
Routes = ActionDispatch::Routing::RouteSet.new
Routes.draw do
get 'dummy/page/:page' => 'dummy#index'
get 'dummy/dots/page.:page' => 'dummy#dots'
get 'ibocorp(/:page)' => 'ibocorp#index',
:constraints => { :page => /\d+/ }, :defaults => { :page => 1 }
get 'foo/bar' => 'foo#bar'
get 'baz/list' => 'baz#list'
end
RSpec.describe WillPaginate::ActionView do
before(:all) do
I18n.load_path.concat WillPaginate::I18n.load_path
I18n.enforce_available_locales = false
ActionController::Parameters.permit_all_parameters = false
end
before(:each) do
I18n.reload!
end
before(:each) do
@assigns = {}
@controller = DummyController.new
@request = @controller.request
@template = '<%= will_paginate collection, options %>'
end
attr_reader :assigns, :controller, :request
def render(locals)
lookup_context = []
lookup_context = ActionView::LookupContext.new(lookup_context)
klass = ActionView::Base
klass = klass.with_empty_template_cache if klass.respond_to?(:with_empty_template_cache)
@view = klass.new(lookup_context, @assigns, @controller)
@view.request = @request
@view.singleton_class.send(:include, @controller._routes.url_helpers)
@view.render(:inline => @template, :locals => locals)
end
## basic pagination ##
it "should render" do
paginate do |pagination|
assert_select 'a[href]', 3 do |elements|
validate_page_numbers [2,3,2], elements
expect(text(elements[2])).to eq('Next →')
end
assert_select 'span', 1 do |spans|
expect(spans[0]['class']).to eq('previous_page disabled')
expect(text(spans[0])).to eq('← Previous')
end
assert_select 'em.current', '1'
expect(text(pagination[0])).to eq('← Previous 1 2 3 Next →')
end
end
it "should override existing page param value" do
request.params :page => 1
paginate do |pagination|
assert_select 'a[href]', 3 do |elements|
validate_page_numbers [2,3,2], elements
end
end
end
it "should render nothing when there is only 1 page" do
expect(paginate(:per_page => 30)).to be_empty
end
it "should paginate with options" do
paginate({ :page => 2 }, :class => 'will_paginate', :previous_label => 'Prev', :next_label => 'Next') do
assert_select 'a[href]', 4 do |elements|
validate_page_numbers [1,1,3,3], elements
# test rel attribute values:
expect(text(elements[0])).to eq('Prev')
expect(elements[0]['rel']).to eq('prev')
expect(text(elements[1])).to eq('1')
expect(elements[1]['rel']).to eq('prev')
expect(text(elements[3])).to eq('Next')
expect(elements[3]['rel']).to eq('next')
end
assert_select '.current', '2'
end
end
it "should paginate using a custom renderer class" do
paginate({}, :renderer => AdditionalLinkAttributesRenderer) do
assert_select 'a[default=true]', 3
end
end
it "should paginate using a custom renderer instance" do
renderer = WillPaginate::ActionView::LinkRenderer.new
def renderer.gap() '<span class="my-gap">~~</span>' end
paginate({ :per_page => 2 }, :inner_window => 0, :outer_window => 0, :renderer => renderer) do
assert_select 'span.my-gap', '~~'
end
renderer = AdditionalLinkAttributesRenderer.new(:title => 'rendered')
paginate({}, :renderer => renderer) do
assert_select 'a[title=rendered]', 3
end
end
it "should have classnames on previous/next links" do
paginate do |pagination|
assert_select 'span.disabled.previous_page:first-child'
assert_select 'a.next_page[href]:last-child'
end
end
it "should match expected markup" do
paginate
expected = <<-HTML.strip.gsub(/\s{2,}/, ' ')
<div class="pagination" role="navigation" aria-label="Pagination"><span class="previous_page disabled" aria-label="Previous page">← Previous</span>
<em class="current" aria-label="Page 1" aria-current="page">1</em>
<a href="/foo/bar?page=2" aria-label="Page 2" rel="next">2</a>
<a href="/foo/bar?page=3" aria-label="Page 3">3</a>
<a href="/foo/bar?page=2" class="next_page" rel="next" aria-label="Next page">Next →</a></div>
HTML
expected_dom = parse_html_document(expected)
if expected_dom.respond_to?(:canonicalize)
expect(html_document.canonicalize).to eq(expected_dom.canonicalize)
else
expect(html_document.root).to eq(expected_dom.root)
end
end
it "should output escaped URLs" do
paginate({:page => 1, :per_page => 1, :total_entries => 2},
:page_links => false, :params => { :tag => '<br>' })
assert_select 'a[href]', 1 do |links|
query = links.first['href'].split('?', 2)[1]
parts = query.gsub('&', '&').split('&').sort
expect(parts).to eq(%w(page=2 tag=%3Cbr%3E))
end
end
## advanced options for pagination ##
it "should be able to render without container" do
paginate({}, :container => false)
assert_select 'div.pagination', 0, 'main DIV present when it shouldn\'t'
assert_select 'a[href]', 3
end
it "should be able to render without page links" do
paginate({ :page => 2 }, :page_links => false) do
assert_select 'a[href]', 2 do |elements|
validate_page_numbers [1,3], elements
end
end
end
## other helpers ##
it "should render a paginated section" do
@template = <<-ERB
<%= paginated_section collection, options do %>
<%= content_tag :div, '', :id => "developers" %>
<% end %>
ERB
paginate
assert_select 'div.pagination', 2
assert_select 'div.pagination + div#developers', 1
end
it "should not render a paginated section with a single page" do
@template = <<-ERB
<%= paginated_section collection, options do %>
<%= content_tag :div, '', :id => "developers" %>
<% end %>
ERB
paginate(:total_entries => 1)
assert_select 'div.pagination', 0
assert_select 'div#developers', 1
end
## parameter handling in page links ##
it "should preserve parameters on GET" do
request.params :foo => { :bar => 'baz' }
paginate
assert_links_match /foo\[bar\]=baz/
end
it "doesn't allow tampering with host, port, protocol" do
request.params :host => 'disney.com', :port => '99', :protocol => 'ftp'
paginate
assert_links_match %r{^/foo/bar}
assert_no_links_match /disney/
assert_no_links_match /99/
assert_no_links_match /ftp/
end
it "doesn't allow tampering with script_name" do
request.params :script_name => 'p0wned', :original_script_name => 'p0wned'
paginate
assert_links_match %r{^/foo/bar}
assert_no_links_match /p0wned/
end
it "should only preserve query parameters on POST" do
request.post
request.params :foo => 'bar'
request.query_parameters = { :hello => 'world' }
paginate
assert_no_links_match /foo=bar/
assert_links_match /hello=world/
end
it "should add additional parameters to links" do
paginate({}, :params => { :foo => 'bar' })
assert_links_match /foo=bar/
end
it "should add anchor parameter" do
paginate({}, :params => { :anchor => 'anchor' })
assert_links_match /#anchor$/
end
it "should remove arbitrary parameters" do
request.params :foo => 'bar'
paginate({}, :params => { :foo => nil })
assert_no_links_match /foo=bar/
end
it "should override default route parameters" do
paginate({}, :params => { :controller => 'baz', :action => 'list' })
assert_links_match %r{\Wbaz/list\W}
end
it "should paginate with custom page parameter" do
paginate({ :page => 2 }, :param_name => :developers_page) do
assert_select 'a[href]', 4 do |elements|
validate_page_numbers [1,1,3,3], elements, :developers_page
end
end
end
it "should paginate with complex custom page parameter" do
request.params :developers => { :page => 2 }
paginate({ :page => 2 }, :param_name => 'developers[page]') do
assert_select 'a[href]', 4 do |links|
assert_links_match /\?developers\[page\]=\d+$/, links
validate_page_numbers [1,1,3,3], links, 'developers[page]'
end
end
end
it "should paginate with custom route page parameter" do
request.symbolized_path_parameters.update :controller => 'dummy', :action => 'index'
paginate :per_page => 2 do
assert_select 'a[href]', 6 do |links|
assert_links_match %r{/page/(\d+)$}, links, [2, 3, 4, 5, 6, 2]
end
end
end
it "should paginate with custom route with dot separator page parameter" do
request.symbolized_path_parameters.update :controller => 'dummy', :action => 'dots'
paginate :per_page => 2 do
assert_select 'a[href]', 6 do |links|
assert_links_match %r{/page\.(\d+)$}, links, [2, 3, 4, 5, 6, 2]
end
end
end
it "should paginate with custom route and first page number implicit" do
request.symbolized_path_parameters.update :controller => 'ibocorp', :action => 'index'
paginate :page => 2, :per_page => 2 do
assert_select 'a[href]', 7 do |links|
assert_links_match %r{/ibocorp(?:/(\d+))?$}, links, [nil, nil, 3, 4, 5, 6, 3]
end
end
# Routes.recognize_path('/ibocorp/2').should == {:page=>'2', :action=>'index', :controller=>'ibocorp'}
# Routes.recognize_path('/ibocorp/foo').should == {:action=>'foo', :controller=>'ibocorp'}
end
## internal hardcore stuff ##
it "should be able to guess the collection name" do
collection = mock
collection.expects(:total_pages).returns(1)
@template = '<%= will_paginate options %>'
controller.controller_name = 'developers'
assigns['developers'] = collection
paginate(nil)
end
it "should fail if the inferred collection is nil" do
@template = '<%= will_paginate options %>'
controller.controller_name = 'developers'
expect {
paginate(nil)
}.to raise_error(ActionView::TemplateError, /@developers/)
end
## i18n
it "is able to translate previous/next labels" do
translation :will_paginate => {
:previous_label => 'Go back',
:next_label => 'Load more'
}
paginate do |pagination|
assert_select 'span.disabled:first-child', 'Go back'
assert_select 'a[rel=next]', 'Load more'
end
end
it "renders using ActionView helpers on a custom object" do
helper = Class.new {
attr_reader :controller
include ActionView::Helpers::UrlHelper
include Routes.url_helpers
include WillPaginate::ActionView
}.new
helper.default_url_options[:controller] = 'dummy'
collection = WillPaginate::Collection.new(2, 1, 3)
@render_output = helper.will_paginate(collection)
assert_select 'a[href]', 4 do |links|
urls = links.map {|l| l['href'] }.uniq
expect(urls).to eq(['/dummy/page/1', '/dummy/page/3'])
end
end
it "renders using ActionDispatch helper on a custom object" do
helper = Class.new {
include ActionDispatch::Routing::UrlFor
include Routes.url_helpers
include WillPaginate::ActionView
}.new
helper.default_url_options.update \
:only_path => true,
:controller => 'dummy'
collection = WillPaginate::Collection.new(2, 1, 3)
@render_output = helper.will_paginate(collection)
assert_select 'a[href]', 4 do |links|
urls = links.map {|l| l['href'] }.uniq
expect(urls).to eq(['/dummy/page/1', '/dummy/page/3'])
end
end
# TODO: re-enable once Rails 6.1.4 ships
it "page_entries_info" do
@template = "<%= page_entries_info collection, options %>"
output = render(
collection: WillPaginate::Collection.new(1, 1, 3),
options: {html: false},
)
expect(output).to eq("Displaying entries 1 - 0 of 3 in total")
end
private
def translation(data)
I18n.available_locales # triggers loading existing translations
I18n.backend.store_translations(:en, data)
end
# Normalizes differences between HTML::Document and Nokogiri::HTML
def text(node)
node.inner_text.gsub('→', '→').gsub('←', '←')
end
end
class AdditionalLinkAttributesRenderer < WillPaginate::ActionView::LinkRenderer
def initialize(link_attributes = nil)
super()
@additional_link_attributes = link_attributes || { :default => 'true' }
end
def link(text, target, attributes = {})
super(text, target, attributes.merge(@additional_link_attributes))
end
end
class DummyController
attr_reader :request
attr_accessor :controller_name
include ActionController::UrlFor
include Routes.url_helpers
def initialize
@request = DummyRequest.new(self)
end
def params
@request.params
end
def env
{}
end
def _prefixes
[]
end
end
class IbocorpController < DummyController
end
class DummyRequest
attr_accessor :symbolized_path_parameters
alias :path_parameters :symbolized_path_parameters
def initialize(controller)
@controller = controller
@get = true
@params = {}.with_indifferent_access
@symbolized_path_parameters = { :controller => 'foo', :action => 'bar' }
end
def routes
@controller._routes
end
def get?
@get
end
def post
@get = false
end
def relative_url_root
''
end
def script_name
''
end
def params(more = nil)
@params.update(more) if more
ActionController::Parameters.new(@params)
end
def query_parameters
if get?
params
else
ActionController::Parameters.new(@query_parameters)
end
end
def query_parameters=(more)
@query_parameters = more.with_indifferent_access
end
def host_with_port
'example.com'
end
alias host host_with_port
def optional_port
''
end
def protocol
'http:'
end
end
| ruby | MIT | 50017c3eb0712e7b3a53268a81e81a184b7a49f6 | 2026-01-04T15:42:46.511340Z | false |
mislav/will_paginate | https://github.com/mislav/will_paginate/blob/50017c3eb0712e7b3a53268a81e81a184b7a49f6/spec/view_helpers/view_example_group.rb | spec/view_helpers/view_example_group.rb | require 'active_support'
require 'stringio'
require 'minitest/assertions'
require 'rails/dom/testing/assertions'
require 'will_paginate/array'
module ViewExampleGroup
include Rails::Dom::Testing::Assertions::SelectorAssertions
include Minitest::Assertions
def assert(value, message)
raise message unless value
end
def paginate(collection = {}, options = {}, &block)
if collection.instance_of? Hash
page_options = { :page => 1, :total_entries => 11, :per_page => 4 }.merge(collection)
collection = [1].paginate(page_options)
end
locals = { :collection => collection, :options => options }
@render_output = render(locals)
@html_document = nil
if block_given?
classname = options[:class] || WillPaginate::ViewHelpers.pagination_options[:class]
assert_select("div.#{classname}", 1, 'no main DIV', &block)
end
@render_output
end
def parse_html_document(html)
Nokogiri::HTML::Document.parse(html)
end
def html_document
@html_document ||= parse_html_document(@render_output)
end
def document_root_element
html_document.root
end
def response_from_page_or_rjs
html_document.root
end
def validate_page_numbers(expected, links, param_name = :page)
param_pattern = /\W#{Regexp.escape(param_name.to_s)}=([^&]*)/
expect(links.map { |el|
unescape_href(el) =~ param_pattern
$1 ? $1.to_i : $1
}).to eq(expected)
end
def assert_links_match(pattern, links = nil, numbers = nil)
links ||= assert_select 'div.pagination a[href]' do |elements|
elements
end
pages = [] if numbers
links.each do |el|
href = unescape_href(el)
expect(href).to match(pattern)
if numbers
href =~ pattern
pages << ($1.nil?? nil : $1.to_i)
end
end
expect(pages).to eq(numbers) if numbers
end
def assert_no_links_match(pattern)
assert_select 'div.pagination a[href]' do |elements|
elements.each do |el|
expect(unescape_href(el)).not_to match(pattern)
end
end
end
def unescape_href(el)
CGI.unescape CGI.unescapeHTML(el['href'])
end
def build_message(message, pattern, *args)
built_message = pattern.dup
for value in args
built_message.sub! '?', value.inspect
end
built_message
end
end
RSpec.configure do |config|
config.include ViewExampleGroup, :type => :view, :file_path => %r{spec/view_helpers/}
end
| ruby | MIT | 50017c3eb0712e7b3a53268a81e81a184b7a49f6 | 2026-01-04T15:42:46.511340Z | false |
mislav/will_paginate | https://github.com/mislav/will_paginate/blob/50017c3eb0712e7b3a53268a81e81a184b7a49f6/spec/view_helpers/base_spec.rb | spec/view_helpers/base_spec.rb | require 'spec_helper'
require 'will_paginate/view_helpers'
require 'will_paginate/array'
require 'active_support'
require 'active_support/core_ext/string/inflections'
require 'active_support/inflections'
RSpec.describe WillPaginate::ViewHelpers do
before(:all) do
# make sure default translations aren't loaded
I18n.load_path.clear
I18n.enforce_available_locales = false
end
before(:each) do
I18n.reload!
end
include WillPaginate::ViewHelpers
describe "will_paginate" do
it "should render" do
collection = WillPaginate::Collection.new(1, 2, 4)
renderer = mock 'Renderer'
renderer.expects(:prepare).with(collection, instance_of(Hash), self)
renderer.expects(:to_html).returns('<PAGES>')
expect(will_paginate(collection, :renderer => renderer)).to eq('<PAGES>')
end
it "should return nil for single-page collections" do
collection = mock 'Collection', :total_pages => 1
expect(will_paginate(collection)).to be_nil
end
it "should call html_safe on result" do
collection = WillPaginate::Collection.new(1, 2, 4)
html = mock 'HTML'
html.expects(:html_safe).returns(html)
renderer = mock 'Renderer'
renderer.stubs(:prepare)
renderer.expects(:to_html).returns(html)
expect(will_paginate(collection, :renderer => renderer)).to eql(html)
end
end
describe "pagination_options" do
let(:pagination_options) { WillPaginate::ViewHelpers.pagination_options }
it "deprecates setting :renderer" do
begin
expect {
pagination_options[:renderer] = 'test'
}.to have_deprecation("pagination_options[:renderer] shouldn't be set")
ensure
pagination_options.delete :renderer
end
end
end
describe "page_entries_info" do
before :all do
@array = ('a'..'z').to_a
end
def info(params, options = {})
collection = Hash === params ? @array.paginate(params) : params
page_entries_info collection, {:html => false}.merge(options)
end
it "should display middle results and total count" do
expect(info(:page => 2, :per_page => 5)).to eq("Displaying strings 6 - 10 of 26 in total")
end
it "uses translation if available" do
translation :will_paginate => {
:page_entries_info => {:multi_page => 'Showing %{from} - %{to}'}
}
expect(info(:page => 2, :per_page => 5)).to eq("Showing 6 - 10")
end
it "uses specific translation if available" do
translation :will_paginate => {
:page_entries_info => {:multi_page => 'Showing %{from} - %{to}'},
:string => { :page_entries_info => {:multi_page => 'Strings %{from} to %{to}'} }
}
expect(info(:page => 2, :per_page => 5)).to eq("Strings 6 to 10")
end
it "should output HTML by default" do
expect(info({ :page => 2, :per_page => 5 }, :html => true)).to eq(
"Displaying strings <b>6 - 10</b> of <b>26</b> in total"
)
end
it "should display shortened end results" do
expect(info(:page => 7, :per_page => 4)).to include_phrase('strings 25 - 26')
end
it "should handle longer class names" do
collection = @array.paginate(:page => 2, :per_page => 5)
model = stub('Class', :name => 'ProjectType', :to_s => 'ProjectType')
collection.first.stubs(:class).returns(model)
expect(info(collection)).to include_phrase('project types')
end
it "should adjust output for single-page collections" do
expect(info(('a'..'d').to_a.paginate(:page => 1, :per_page => 5))).to eq("Displaying all 4 strings")
expect(info(['a'].paginate(:page => 1, :per_page => 5))).to eq("Displaying 1 string")
end
it "should display 'no entries found' for empty collections" do
expect(info([].paginate(:page => 1, :per_page => 5))).to eq("No entries found")
end
it "uses model_name.human when available" do
name = stub('model name', :i18n_key => :flower_key)
name.expects(:human).with(:count => 1).returns('flower')
model = stub('Class', :model_name => name)
collection = [1].paginate(:page => 1)
expect(info(collection, :model => model)).to eq("Displaying 1 flower")
end
it "uses custom translation instead of model_name.human" do
name = stub('model name', :i18n_key => :flower_key)
name.expects(:human).never
model = stub('Class', :model_name => name)
translation :will_paginate => {:models => {:flower_key => 'tulip'}}
collection = [1].paginate(:page => 1)
expect(info(collection, :model => model)).to eq("Displaying 1 tulip")
end
private
def translation(data)
I18n.backend.store_translations(:en, data)
end
end
end
| ruby | MIT | 50017c3eb0712e7b3a53268a81e81a184b7a49f6 | 2026-01-04T15:42:46.511340Z | false |
mislav/will_paginate | https://github.com/mislav/will_paginate/blob/50017c3eb0712e7b3a53268a81e81a184b7a49f6/spec/view_helpers/link_renderer_base_spec.rb | spec/view_helpers/link_renderer_base_spec.rb | require 'spec_helper'
require 'will_paginate/view_helpers/link_renderer_base'
require 'will_paginate/collection'
RSpec.describe WillPaginate::ViewHelpers::LinkRendererBase do
before do
@renderer = described_class.new
end
it "should raise error when unprepared" do
expect {
@renderer.pagination
}.to raise_error(NoMethodError)
end
it "should prepare with collection and options" do
prepare({})
expect(@renderer.send(:current_page)).to eq(1)
end
it "should have total_pages accessor" do
prepare :total_pages => 42
expect(@renderer.send(:total_pages)).to eq(42)
end
it "should clear old cached values when prepared" do
prepare(:total_pages => 1)
expect(@renderer.send(:total_pages)).to eq(1)
# prepare with different object:
prepare(:total_pages => 2)
expect(@renderer.send(:total_pages)).to eq(2)
end
it "should have pagination definition" do
prepare({ :total_pages => 1 }, :page_links => true)
expect(@renderer.pagination).to eq([:previous_page, 1, :next_page])
end
describe "visible page numbers" do
it "should calculate windowed visible links" do
prepare({ :page => 6, :total_pages => 11 }, :inner_window => 1, :outer_window => 1)
showing_pages 1, 2, :gap, 5, 6, 7, :gap, 10, 11
end
it "should eliminate small gaps" do
prepare({ :page => 6, :total_pages => 11 }, :inner_window => 2, :outer_window => 1)
# pages 4 and 8 appear instead of the gap
showing_pages 1..11
end
it "should support having no windows at all" do
prepare({ :page => 4, :total_pages => 7 }, :inner_window => 0, :outer_window => 0)
showing_pages 1, :gap, 4, :gap, 7
end
it "should adjust upper limit if lower is out of bounds" do
prepare({ :page => 1, :total_pages => 10 }, :inner_window => 2, :outer_window => 1)
showing_pages 1, 2, 3, 4, 5, :gap, 9, 10
end
it "should adjust lower limit if upper is out of bounds" do
prepare({ :page => 10, :total_pages => 10 }, :inner_window => 2, :outer_window => 1)
showing_pages 1, 2, :gap, 6, 7, 8, 9, 10
end
def showing_pages(*pages)
pages = pages.first.to_a if Array === pages.first or Range === pages.first
expect(@renderer.send(:windowed_page_numbers)).to eq(pages)
end
end
protected
def collection(params = {})
if params[:total_pages]
params[:per_page] = 1
params[:total_entries] = params[:total_pages]
end
WillPaginate::Collection.new(params[:page] || 1, params[:per_page] || 30, params[:total_entries])
end
def prepare(collection_options, options = {})
@renderer.prepare(collection(collection_options), options)
end
end
| ruby | MIT | 50017c3eb0712e7b3a53268a81e81a184b7a49f6 | 2026-01-04T15:42:46.511340Z | false |
mislav/will_paginate | https://github.com/mislav/will_paginate/blob/50017c3eb0712e7b3a53268a81e81a184b7a49f6/spec/matchers/query_count_matcher.rb | spec/matchers/query_count_matcher.rb | RSpec::Matchers.define :execute do |expected_count|
match do |block|
run(block)
if expected_count.respond_to? :include?
expected_count.include? @count
else
@count == expected_count
end
end
def run(block)
$query_count = 0
$query_sql = []
block.call
ensure
@queries = $query_sql.dup
@count = $query_count
end
chain(:queries) {}
supports_block_expectations
failure_message do
"expected #{expected_count} queries, got #{@count}\n#{@queries.join("\n")}"
end
failure_message_when_negated do
"expected query count not to be #{expected_count}"
end
end
| ruby | MIT | 50017c3eb0712e7b3a53268a81e81a184b7a49f6 | 2026-01-04T15:42:46.511340Z | false |
mislav/will_paginate | https://github.com/mislav/will_paginate/blob/50017c3eb0712e7b3a53268a81e81a184b7a49f6/spec-non-rails/sequel_spec.rb | spec-non-rails/sequel_spec.rb | require_relative './spec_helper'
require 'sequel'
require 'will_paginate/sequel'
Sequel.sqlite.create_table :cars do
primary_key :id, :integer, :auto_increment => true
column :name, :text
column :notes, :text
end
RSpec.describe Sequel::Dataset::Pagination, 'extension' do
class Car < Sequel::Model
self.dataset = dataset.extension(:pagination)
end
it "should have the #paginate method" do
expect(Car.dataset).to respond_to(:paginate)
end
it "should NOT have the #paginate_by_sql method" do
expect(Car.dataset).not_to respond_to(:paginate_by_sql)
end
describe 'pagination' do
before(:all) do
Car.create(:name => 'Shelby', :notes => "Man's best friend")
Car.create(:name => 'Aston Martin', :notes => "Woman's best friend")
Car.create(:name => 'Corvette', :notes => 'King of the Jungle')
end
it "should imitate WillPaginate::Collection" do
result = Car.dataset.paginate(1, 2)
expect(result).not_to be_empty
expect(result.size).to eq(2)
expect(result.length).to eq(2)
expect(result.total_entries).to eq(3)
expect(result.total_pages).to eq(2)
expect(result.per_page).to eq(2)
expect(result.current_page).to eq(1)
end
it "should perform" do
expect(Car.dataset.paginate(1, 2).all).to eq([Car[1], Car[2]])
end
it "should be empty" do
result = Car.dataset.paginate(3, 2)
expect(result).to be_empty
end
it "should perform with #select and #order" do
result = Car.select(Sequel.lit("name as foo")).order(:name).paginate(1, 2).all
expect(result.size).to eq(2)
expect(result.first.values[:foo]).to eq("Aston Martin")
end
it "should perform with #filter" do
results = Car.filter(:name => 'Shelby').paginate(1, 2).all
expect(results.size).to eq(1)
expect(results.first).to eq(Car.find(:name => 'Shelby'))
end
end
end
| ruby | MIT | 50017c3eb0712e7b3a53268a81e81a184b7a49f6 | 2026-01-04T15:42:46.511340Z | false |
mislav/will_paginate | https://github.com/mislav/will_paginate/blob/50017c3eb0712e7b3a53268a81e81a184b7a49f6/spec-non-rails/mongoid_spec.rb | spec-non-rails/mongoid_spec.rb | require_relative './spec_helper'
require 'will_paginate/mongoid'
RSpec.describe WillPaginate::Mongoid do
class MongoidModel
include Mongoid::Document
end
before(:all) do
Mongoid.configure do |config|
mongodb_host = ENV["MONGODB_HOST"] || "localhost"
mongodb_port = ENV["MONGODB_PORT"] || "27017"
config.clients.default = {
hosts: ["#{mongodb_host}:#{mongodb_port}"],
database: "will_paginate_test",
}
config.log_level = :warn
end
MongoidModel.delete_all
4.times { MongoidModel.create! }
end
let(:criteria) { MongoidModel.criteria }
describe "#page" do
it "should forward to the paginate method" do
criteria.expects(:paginate).with(:page => 2).returns("itself")
expect(criteria.page(2)).to eq("itself")
end
it "should not override per_page if set earlier in the chain" do
expect(criteria.paginate(:per_page => 10).page(1).per_page).to eq(10)
expect(criteria.paginate(:per_page => 20).page(1).per_page).to eq(20)
end
end
describe "#per_page" do
it "should set the limit if given an argument" do
expect(criteria.per_page(10).options[:limit]).to eq(10)
end
it "should return the current limit if no argument is given" do
expect(criteria.per_page).to eq(nil)
expect(criteria.per_page(10).per_page).to eq(10)
end
it "should be interchangable with limit" do
expect(criteria.limit(15).per_page).to eq(15)
end
it "should be nil'able" do
expect(criteria.per_page(nil).per_page).to be_nil
end
end
describe "#paginate" do
it "should use criteria" do
expect(criteria.paginate).to be_instance_of(::Mongoid::Criteria)
end
it "should not override page number if set earlier in the chain" do
expect(criteria.page(3).paginate.current_page).to eq(3)
end
it "should limit according to per_page parameter" do
expect(criteria.paginate(:per_page => 10).options).to include(:limit => 10)
end
it "should skip according to page and per_page parameters" do
expect(criteria.paginate(:page => 2, :per_page => 5).options).to include(:skip => 5)
end
specify "first fallback value for per_page option is the current limit" do
expect(criteria.limit(12).paginate.options).to include(:limit => 12)
end
specify "second fallback value for per_page option is WillPaginate.per_page" do
expect(criteria.paginate.options).to include(:limit => WillPaginate.per_page)
end
specify "page should default to 1" do
expect(criteria.paginate.options).to include(:skip => 0)
end
it "should convert strings to integers" do
expect(criteria.paginate(:page => "2", :per_page => "3").options).to include(:limit => 3)
end
describe "collection compatibility" do
describe "#total_count" do
it "should be calculated correctly" do
expect(criteria.paginate(:per_page => 1).total_entries).to eq(4)
expect(criteria.paginate(:per_page => 3).total_entries).to eq(4)
end
it "should be cached" do
criteria.expects(:count).once.returns(123)
criteria.paginate
2.times { expect(criteria.total_entries).to eq(123) }
end
end
it "should calculate total_pages" do
expect(criteria.paginate(:per_page => 1).total_pages).to eq(4)
expect(criteria.paginate(:per_page => 3).total_pages).to eq(2)
expect(criteria.paginate(:per_page => 10).total_pages).to eq(1)
end
it "should return per_page" do
expect(criteria.paginate(:per_page => 1).per_page).to eq(1)
expect(criteria.paginate(:per_page => 5).per_page).to eq(5)
end
describe "#current_page" do
it "should return current_page" do
expect(criteria.paginate(:page => 1).current_page).to eq(1)
expect(criteria.paginate(:page => 3).current_page).to eq(3)
end
it "should be casted to PageNumber" do
page = criteria.paginate(:page => 1).current_page
expect(page.instance_of? WillPaginate::PageNumber).to be
end
end
it "should return offset" do
expect(criteria.paginate(:page => 1).offset).to eq(0)
expect(criteria.paginate(:page => 2, :per_page => 5).offset).to eq(5)
expect(criteria.paginate(:page => 3, :per_page => 10).offset).to eq(20)
end
it "should not pollute plain mongoid criterias" do
%w(total_entries total_pages current_page).each do |method|
expect(criteria).not_to respond_to(method)
end
end
end
end
end
| ruby | MIT | 50017c3eb0712e7b3a53268a81e81a184b7a49f6 | 2026-01-04T15:42:46.511340Z | false |
mislav/will_paginate | https://github.com/mislav/will_paginate/blob/50017c3eb0712e7b3a53268a81e81a184b7a49f6/spec-non-rails/spec_helper.rb | spec-non-rails/spec_helper.rb | require 'rspec'
RSpec.configure do |config|
config.mock_with :mocha
config.expose_dsl_globally = false
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
config.shared_context_metadata_behavior = :apply_to_host_groups
config.disable_monkey_patching!
end
| ruby | MIT | 50017c3eb0712e7b3a53268a81e81a184b7a49f6 | 2026-01-04T15:42:46.511340Z | false |
mislav/will_paginate | https://github.com/mislav/will_paginate/blob/50017c3eb0712e7b3a53268a81e81a184b7a49f6/lib/will_paginate.rb | lib/will_paginate.rb | # You will paginate!
module WillPaginate
end
if defined?(Rails::Railtie)
require 'will_paginate/railtie'
elsif defined?(Rails::Initializer)
raise "will_paginate 3.0 is not compatible with Rails 2.3 or older"
end
if defined?(Sinatra) and Sinatra.respond_to? :register
require 'will_paginate/view_helpers/sinatra'
end
| ruby | MIT | 50017c3eb0712e7b3a53268a81e81a184b7a49f6 | 2026-01-04T15:42:46.511340Z | false |
mislav/will_paginate | https://github.com/mislav/will_paginate/blob/50017c3eb0712e7b3a53268a81e81a184b7a49f6/lib/will_paginate/page_number.rb | lib/will_paginate/page_number.rb | require 'forwardable'
module WillPaginate
# a module that page number exceptions are tagged with
module InvalidPage; end
# integer representing a page number
class PageNumber < Numeric
# a value larger than this is not supported in SQL queries
BIGINT = 9223372036854775807
extend Forwardable
def initialize(value, name)
value = Integer(value)
if 'offset' == name ? (value < 0 or value > BIGINT) : value < 1
raise RangeError, "invalid #{name}: #{value.inspect}"
end
@name = name
@value = value
rescue ArgumentError, TypeError, RangeError => error
error.extend InvalidPage
raise error
end
def to_i
@value
end
def_delegators :@value, :coerce, :==, :<=>, :to_s, :+, :-, :*, :/, :to_json
def inspect
"#{@name} #{to_i}"
end
def to_offset(per_page)
PageNumber.new((to_i - 1) * per_page.to_i, 'offset')
end
def kind_of?(klass)
super || to_i.kind_of?(klass)
end
alias is_a? kind_of?
end
# An idemptotent coercion method
def self.PageNumber(value, name = 'page')
case value
when PageNumber then value
else PageNumber.new(value, name)
end
end
end
| ruby | MIT | 50017c3eb0712e7b3a53268a81e81a184b7a49f6 | 2026-01-04T15:42:46.511340Z | false |
mislav/will_paginate | https://github.com/mislav/will_paginate/blob/50017c3eb0712e7b3a53268a81e81a184b7a49f6/lib/will_paginate/active_record.rb | lib/will_paginate/active_record.rb | require 'will_paginate/per_page'
require 'will_paginate/page_number'
require 'will_paginate/collection'
require 'active_record'
module WillPaginate
# = Paginating finders for ActiveRecord models
#
# WillPaginate adds +paginate+, +per_page+ and other methods to
# ActiveRecord::Base class methods and associations.
#
# In short, paginating finders are equivalent to ActiveRecord finders; the
# only difference is that we start with "paginate" instead of "find" and
# that <tt>:page</tt> is required parameter:
#
# @posts = Post.paginate :all, :page => params[:page], :order => 'created_at DESC'
#
module ActiveRecord
# makes a Relation look like WillPaginate::Collection
module RelationMethods
include WillPaginate::CollectionMethods
attr_accessor :current_page
attr_writer :total_entries
def per_page(value = nil)
if value.nil? then limit_value
else limit(value)
end
end
# TODO: solve with less relation clones and code dups
def limit(num)
rel = super
if rel.current_page
rel.offset rel.current_page.to_offset(rel.limit_value).to_i
else
rel
end
end
# dirty hack to enable `first` after `limit` behavior above
def first(*args)
if current_page
rel = clone
rel.current_page = nil
rel.first(*args)
else
super
end
end
# fix for Rails 3.0
def find_last(*args)
if !loaded? && args.empty? && (offset_value || limit_value)
@last ||= to_a.last
else
super
end
end
def offset(value = nil)
if value.nil? then offset_value
else super(value)
end
end
def total_entries
@total_entries ||= begin
if loaded? and size < limit_value and (current_page == 1 or size > 0)
offset_value + size
else
@total_entries_queried = true
result = count
result = result.size if result.respond_to?(:size) and !result.is_a?(Integer)
result
end
end
end
def count(*args)
if limit_value
excluded = [:order, :limit, :offset, :reorder]
excluded << :includes unless eager_loading?
rel = self.except(*excluded)
column_name = if rel.select_values.present?
select = rel.select_values.join(", ")
select if select !~ /[,*]/
end || :all
rel.count(column_name)
else
super(*args)
end
end
# workaround for Active Record 3.0
def size
if !loaded? and limit_value and group_values.empty?
[super, limit_value].min
else
super
end
end
# overloaded to be pagination-aware
def empty?
if !loaded? and offset_value
total_entries <= offset_value
else
super
end
end
def clone
copy_will_paginate_data super
end
# workaround for Active Record 3.0
def scoped(options = nil)
copy_will_paginate_data super
end
def to_a
if current_page.nil? then super # workaround for Active Record 3.0
else
::WillPaginate::Collection.create(current_page, limit_value) do |col|
col.replace super
col.total_entries ||= total_entries
end
end
end
private
def copy_will_paginate_data(other)
other.current_page = current_page unless other.current_page
other.total_entries = nil if defined? @total_entries_queried
other
end
end
module Pagination
def paginate(options)
options = options.dup
pagenum = options.fetch(:page) { raise ArgumentError, ":page parameter required" }
options.delete(:page)
per_page = options.delete(:per_page) || self.per_page
total = options.delete(:total_entries)
if options.any?
raise ArgumentError, "unsupported parameters: %p" % options.keys
end
rel = limit(per_page.to_i).page(pagenum)
rel.total_entries = total.to_i unless total.blank?
rel
end
def page(num)
rel = if ::ActiveRecord::Relation === self
self
elsif !defined?(::ActiveRecord::Scoping) or ::ActiveRecord::Scoping::ClassMethods.method_defined? :with_scope
# Active Record 3
scoped
else
# Active Record 4
all
end
rel = rel.extending(RelationMethods)
pagenum = ::WillPaginate::PageNumber(num.nil? ? 1 : num)
per_page = rel.limit_value || self.per_page
rel = rel.offset(pagenum.to_offset(per_page).to_i)
rel = rel.limit(per_page) unless rel.limit_value
rel.current_page = pagenum
rel
end
end
module BaseMethods
# Wraps +find_by_sql+ by simply adding LIMIT and OFFSET to your SQL string
# based on the params otherwise used by paginating finds: +page+ and
# +per_page+.
#
# Example:
#
# @developers = Developer.paginate_by_sql ['select * from developers where salary > ?', 80000],
# :page => params[:page], :per_page => 3
#
# A query for counting rows will automatically be generated if you don't
# supply <tt>:total_entries</tt>. If you experience problems with this
# generated SQL, you might want to perform the count manually in your
# application.
#
def paginate_by_sql(sql, options)
pagenum = options.fetch(:page) { raise ArgumentError, ":page parameter required" } || 1
per_page = options[:per_page] || self.per_page
total = options[:total_entries]
WillPaginate::Collection.create(pagenum, per_page, total) do |pager|
query = sanitize_sql(sql.dup)
original_query = query.dup
oracle = self.connection.adapter_name =~ /^(oracle|oci$)/i
# add limit, offset
if oracle
query = <<-SQL
SELECT * FROM (
SELECT rownum rnum, a.* FROM (#{query}) a
WHERE rownum <= #{pager.offset + pager.per_page}
) WHERE rnum >= #{pager.offset}
SQL
elsif (self.connection.adapter_name =~ /^sqlserver/i)
query << " OFFSET #{pager.offset} ROWS FETCH NEXT #{pager.per_page} ROWS ONLY"
else
query << " LIMIT #{pager.per_page} OFFSET #{pager.offset}"
end
# perfom the find
pager.replace find_by_sql(query)
unless pager.total_entries
count_query = original_query.sub /\bORDER\s+BY\s+[\w`,\s.]+$/mi, ''
count_query = "SELECT COUNT(*) FROM (#{count_query})"
count_query << ' AS count_table' unless oracle
# perform the count query
pager.total_entries = count_by_sql(count_query)
end
end
end
end
# mix everything into Active Record
::ActiveRecord::Base.extend PerPage
::ActiveRecord::Base.extend Pagination
::ActiveRecord::Base.extend BaseMethods
klasses = [::ActiveRecord::Relation]
if defined? ::ActiveRecord::Associations::CollectionProxy
klasses << ::ActiveRecord::Associations::CollectionProxy
else
klasses << ::ActiveRecord::Associations::AssociationCollection
end
# support pagination on associations and scopes
klasses.each { |klass| klass.send(:include, Pagination) }
end
end
| ruby | MIT | 50017c3eb0712e7b3a53268a81e81a184b7a49f6 | 2026-01-04T15:42:46.511340Z | false |
mislav/will_paginate | https://github.com/mislav/will_paginate/blob/50017c3eb0712e7b3a53268a81e81a184b7a49f6/lib/will_paginate/collection.rb | lib/will_paginate/collection.rb | require 'will_paginate/per_page'
require 'will_paginate/page_number'
module WillPaginate
# Any will_paginate-compatible collection should have these methods:
#
# current_page, per_page, offset, total_entries, total_pages
#
# It can also define some of these optional methods:
#
# out_of_bounds?, previous_page, next_page
#
# This module provides few of these methods.
module CollectionMethods
def total_pages
total_entries.zero? ? 1 : (total_entries / per_page.to_f).ceil
end
# current_page - 1 or nil if there is no previous page
def previous_page
current_page > 1 ? (current_page - 1) : nil
end
# current_page + 1 or nil if there is no next page
def next_page
current_page < total_pages ? (current_page + 1) : nil
end
# Helper method that is true when someone tries to fetch a page with a
# larger number than the last page. Can be used in combination with flashes
# and redirecting.
def out_of_bounds?
current_page > total_pages
end
end
# = The key to pagination
# Arrays returned from paginating finds are, in fact, instances of this little
# class. You may think of WillPaginate::Collection as an ordinary array with
# some extra properties. Those properties are used by view helpers to generate
# correct page links.
#
# WillPaginate::Collection also assists in rolling out your own pagination
# solutions: see +create+.
#
# If you are writing a library that provides a collection which you would like
# to conform to this API, you don't have to copy these methods over; simply
# make your plugin/gem dependant on this library and do:
#
# require 'will_paginate/collection'
# # WillPaginate::Collection is now available for use
class Collection < Array
include CollectionMethods
attr_reader :current_page, :per_page, :total_entries
# Arguments to the constructor are the current page number, per-page limit
# and the total number of entries. The last argument is optional because it
# is best to do lazy counting; in other words, count *conditionally* after
# populating the collection using the +replace+ method.
def initialize(page, per_page = WillPaginate.per_page, total = nil)
@current_page = WillPaginate::PageNumber(page)
@per_page = per_page.to_i
self.total_entries = total if total
end
# Just like +new+, but yields the object after instantiation and returns it
# afterwards. This is very useful for manual pagination:
#
# @entries = WillPaginate::Collection.create(1, 10) do |pager|
# result = Post.find(:all, :limit => pager.per_page, :offset => pager.offset)
# # inject the result array into the paginated collection:
# pager.replace(result)
#
# unless pager.total_entries
# # the pager didn't manage to guess the total count, do it manually
# pager.total_entries = Post.count
# end
# end
#
# The possibilities with this are endless. For another example, here is how
# WillPaginate used to define pagination for Array instances:
#
# Array.class_eval do
# def paginate(page = 1, per_page = 15)
# WillPaginate::Collection.create(page, per_page, size) do |pager|
# pager.replace self[pager.offset, pager.per_page].to_a
# end
# end
# end
#
# The Array#paginate API has since then changed, but this still serves as a
# fine example of WillPaginate::Collection usage.
def self.create(page, per_page, total = nil)
pager = new(page, per_page, total)
yield pager
pager
end
# Current offset of the paginated collection. If we're on the first page,
# it is always 0. If we're on the 2nd page and there are 30 entries per page,
# the offset is 30. This property is useful if you want to render ordinals
# side by side with records in the view: simply start with offset + 1.
def offset
current_page.to_offset(per_page).to_i
end
def total_entries=(number)
@total_entries = number.to_i
end
# This is a magic wrapper for the original Array#replace method. It serves
# for populating the paginated collection after initialization.
#
# Why magic? Because it tries to guess the total number of entries judging
# by the size of given array. If it is shorter than +per_page+ limit, then we
# know we're on the last page. This trick is very useful for avoiding
# unnecessary hits to the database to do the counting after we fetched the
# data for the current page.
#
# However, after using +replace+ you should always test the value of
# +total_entries+ and set it to a proper value if it's +nil+. See the example
# in +create+.
def replace(array)
result = super
# The collection is shorter then page limit? Rejoice, because
# then we know that we are on the last page!
if total_entries.nil? and length < per_page and (current_page == 1 or length > 0)
self.total_entries = offset + length
end
result
end
end
end
| ruby | MIT | 50017c3eb0712e7b3a53268a81e81a184b7a49f6 | 2026-01-04T15:42:46.511340Z | false |
mislav/will_paginate | https://github.com/mislav/will_paginate/blob/50017c3eb0712e7b3a53268a81e81a184b7a49f6/lib/will_paginate/deprecation.rb | lib/will_paginate/deprecation.rb | module WillPaginate::Deprecation
class << self
def warn(message, stack = caller)
offending_line = origin_of_call(stack)
full_message = "DEPRECATION WARNING: #{message} (called from #{offending_line})"
logger = rails_logger || Kernel
logger.warn full_message
end
private
def rails_logger
defined?(Rails.logger) && Rails.logger
end
def origin_of_call(stack)
lib_root = File.expand_path('../../..', __FILE__)
stack.find { |line| line.index(lib_root) != 0 } || stack.first
end
end
class Hash < ::Hash
def initialize(values = {})
super()
update values
@deprecated = {}
end
def []=(key, value)
check_deprecated(key, value)
super
end
def deprecate_key(*keys, &block)
message = block_given? ? block : keys.pop
Array(keys).each { |key| @deprecated[key] = message }
end
def merge(another)
to_hash.update(another)
end
def to_hash
::Hash.new.update(self)
end
private
def check_deprecated(key, value)
if msg = @deprecated[key] and (!msg.respond_to?(:call) or (msg = msg.call(key, value)))
WillPaginate::Deprecation.warn(msg)
end
end
end
end
| ruby | MIT | 50017c3eb0712e7b3a53268a81e81a184b7a49f6 | 2026-01-04T15:42:46.511340Z | false |
mislav/will_paginate | https://github.com/mislav/will_paginate/blob/50017c3eb0712e7b3a53268a81e81a184b7a49f6/lib/will_paginate/version.rb | lib/will_paginate/version.rb | module WillPaginate #:nodoc:
module VERSION #:nodoc:
MAJOR = 4
MINOR = 0
TINY = 1
STRING = [MAJOR, MINOR, TINY].join('.')
end
end
| ruby | MIT | 50017c3eb0712e7b3a53268a81e81a184b7a49f6 | 2026-01-04T15:42:46.511340Z | false |
mislav/will_paginate | https://github.com/mislav/will_paginate/blob/50017c3eb0712e7b3a53268a81e81a184b7a49f6/lib/will_paginate/core_ext.rb | lib/will_paginate/core_ext.rb | require 'set'
# copied from ActiveSupport so we don't depend on it
unless Hash.method_defined? :except
Hash.class_eval do
# Returns a new hash without the given keys.
def except(*keys)
rejected = Set.new(respond_to?(:convert_key) ? keys.map { |key| convert_key(key) } : keys)
reject { |key,| rejected.include?(key) }
end
# Replaces the hash without only the given keys.
def except!(*keys)
replace(except(*keys))
end
end
end
unless String.method_defined? :underscore
String.class_eval do
def underscore
self.to_s.gsub(/::/, '/').
gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
gsub(/([a-z\d])([A-Z])/,'\1_\2').
tr("-", "_").
downcase
end
end
end
| ruby | MIT | 50017c3eb0712e7b3a53268a81e81a184b7a49f6 | 2026-01-04T15:42:46.511340Z | false |
mislav/will_paginate | https://github.com/mislav/will_paginate/blob/50017c3eb0712e7b3a53268a81e81a184b7a49f6/lib/will_paginate/sequel.rb | lib/will_paginate/sequel.rb | require 'sequel'
require 'sequel/extensions/pagination'
require 'will_paginate/collection'
module WillPaginate
# Sequel already supports pagination; we only need to make the
# resulting dataset look a bit more like WillPaginate::Collection
module SequelMethods
include WillPaginate::CollectionMethods
def total_pages
page_count
end
def per_page
page_size
end
def size
current_page_record_count
end
alias length size
def total_entries
pagination_record_count
end
def out_of_bounds?
current_page > total_pages
end
# Current offset of the paginated collection
def offset
(current_page - 1) * per_page
end
end
Sequel::Dataset::Pagination.send(:include, SequelMethods)
end
| ruby | MIT | 50017c3eb0712e7b3a53268a81e81a184b7a49f6 | 2026-01-04T15:42:46.511340Z | false |
mislav/will_paginate | https://github.com/mislav/will_paginate/blob/50017c3eb0712e7b3a53268a81e81a184b7a49f6/lib/will_paginate/view_helpers.rb | lib/will_paginate/view_helpers.rb | # encoding: utf-8
require 'will_paginate/core_ext'
require 'will_paginate/i18n'
require 'will_paginate/deprecation'
module WillPaginate
# = Will Paginate view helpers
#
# The main view helper is +will_paginate+. It renders the pagination links
# for the given collection. The helper itself is lightweight and serves only
# as a wrapper around LinkRenderer instantiation; the renderer then does
# all the hard work of generating the HTML.
module ViewHelpers
class << self
# Write to this hash to override default options on the global level:
#
# WillPaginate::ViewHelpers.pagination_options[:page_links] = false
#
attr_accessor :pagination_options
end
# default view options
self.pagination_options = Deprecation::Hash.new \
:class => 'pagination',
:previous_label => nil,
:next_label => nil,
:inner_window => 4, # links around the current page
:outer_window => 1, # links around beginning and end
:link_separator => ' ', # single space is friendly to spiders and non-graphic browsers
:param_name => :page,
:params => nil,
:page_links => true,
:container => true
label_deprecation = Proc.new { |key, value|
"set the 'will_paginate.#{key}' key in your i18n locale instead of editing pagination_options" if defined? Rails
}
pagination_options.deprecate_key(:previous_label, :next_label, &label_deprecation)
pagination_options.deprecate_key(:renderer) { |key, _| "pagination_options[#{key.inspect}] shouldn't be set globally" }
include WillPaginate::I18n
# Returns HTML representing page links for a WillPaginate::Collection-like object.
# In case there is no more than one page in total, nil is returned.
#
# ==== Options
# * <tt>:class</tt> -- CSS class name for the generated DIV (default: "pagination")
# * <tt>:previous_label</tt> -- default: "« Previous"
# * <tt>:next_label</tt> -- default: "Next »"
# * <tt>:inner_window</tt> -- how many links are shown around the current page (default: 4)
# * <tt>:outer_window</tt> -- how many links are around the first and the last page (default: 1)
# * <tt>:link_separator</tt> -- string separator for page HTML elements (default: single space)
# * <tt>:param_name</tt> -- parameter name for page number in URLs (default: <tt>:page</tt>)
# * <tt>:params</tt> -- additional parameters when generating pagination links
# (eg. <tt>:controller => "foo", :action => nil</tt>)
# * <tt>:renderer</tt> -- class name, class or instance of a link renderer (default in Rails:
# <tt>WillPaginate::ActionView::LinkRenderer</tt>)
# * <tt>:page_links</tt> -- when false, only previous/next links are rendered (default: true)
# * <tt>:container</tt> -- toggles rendering of the DIV container for pagination links, set to
# false only when you are rendering your own pagination markup (default: true)
#
# All options not recognized by will_paginate will become HTML attributes on the container
# element for pagination links (the DIV). For example:
#
# <%= will_paginate @posts, :style => 'color:blue' %>
#
# will result in:
#
# <div class="pagination" style="color:blue"> ... </div>
#
def will_paginate(collection, options = {})
# early exit if there is nothing to render
return nil unless collection.total_pages > 1
options = WillPaginate::ViewHelpers.pagination_options.merge(options)
options[:previous_label] ||= will_paginate_translate(:previous_label) { '← Previous' }
options[:next_label] ||= will_paginate_translate(:next_label) { 'Next →' }
# get the renderer instance
renderer = case options[:renderer]
when nil
raise ArgumentError, ":renderer not specified"
when String
klass = if options[:renderer].respond_to? :constantize then options[:renderer].constantize
else Object.const_get(options[:renderer]) # poor man's constantize
end
klass.new
when Class then options[:renderer].new
else options[:renderer]
end
# render HTML for pagination
renderer.prepare collection, options, self
output = renderer.to_html
output = output.html_safe if output.respond_to?(:html_safe)
output
end
# Renders a message containing number of displayed vs. total entries.
#
# <%= page_entries_info @posts %>
# #-> Displaying posts 6 - 12 of 26 in total
#
# The default output contains HTML. Use ":html => false" for plain text.
def page_entries_info(collection, options = {})
model = options[:model]
model = collection.first.class unless model or collection.empty?
model ||= 'entry'
model_key = if model.respond_to? :model_name
model.model_name.i18n_key # ActiveModel::Naming
else
model.to_s.underscore
end
if options.fetch(:html, true)
b, eb = '<b>', '</b>'
sp = ' '
html_key = '_html'
else
b = eb = html_key = ''
sp = ' '
end
model_count = collection.total_pages > 1 ? 5 : collection.size
defaults = ["models.#{model_key}"]
defaults << Proc.new { |_, opts|
if model.respond_to? :model_name
model.model_name.human(:count => opts[:count])
else
name = model_key.to_s.tr('_', ' ')
raise "can't pluralize model name: #{model.inspect}" unless name.respond_to? :pluralize
opts[:count] == 1 ? name : name.pluralize
end
}
model_name = will_paginate_translate defaults, :count => model_count
if collection.total_pages < 2
i18n_key = :"page_entries_info.single_page#{html_key}"
keys = [:"#{model_key}.#{i18n_key}", i18n_key]
will_paginate_translate keys, :count => collection.total_entries, :model => model_name do |_, opts|
case opts[:count]
when 0; "No #{opts[:model]} found"
when 1; "Displaying #{b}1#{eb} #{opts[:model]}"
else "Displaying #{b}all#{sp}#{opts[:count]}#{eb} #{opts[:model]}"
end
end
else
i18n_key = :"page_entries_info.multi_page#{html_key}"
keys = [:"#{model_key}.#{i18n_key}", i18n_key]
params = {
:model => model_name, :count => collection.total_entries,
:from => collection.offset + 1, :to => collection.offset + collection.length
}
will_paginate_translate keys, params do |_, opts|
%{Displaying %s #{b}%d#{sp}-#{sp}%d#{eb} of #{b}%d#{eb} in total} %
[ opts[:model], opts[:from], opts[:to], opts[:count] ]
end
end
end
end
end
| ruby | MIT | 50017c3eb0712e7b3a53268a81e81a184b7a49f6 | 2026-01-04T15:42:46.511340Z | false |
mislav/will_paginate | https://github.com/mislav/will_paginate/blob/50017c3eb0712e7b3a53268a81e81a184b7a49f6/lib/will_paginate/array.rb | lib/will_paginate/array.rb | require 'will_paginate/collection'
class Array
# Paginates a static array (extracting a subset of it). The result is a
# WillPaginate::Collection instance, which is an array with a few more
# properties about its paginated state.
#
# Parameters:
# * <tt>:page</tt> - current page, defaults to 1
# * <tt>:per_page</tt> - limit of items per page, defaults to 30
# * <tt>:total_entries</tt> - total number of items in the array, defaults to
# <tt>array.length</tt> (obviously)
#
# Example:
# arr = ['a', 'b', 'c', 'd', 'e']
# paged = arr.paginate(:per_page => 2) #-> ['a', 'b']
# paged.total_entries #-> 5
# arr.paginate(:page => 2, :per_page => 2) #-> ['c', 'd']
# arr.paginate(:page => 3, :per_page => 2) #-> ['e']
#
# This method was originally {suggested by Desi
# McAdam}[http://www.desimcadam.com/archives/8] and later proved to be the
# most useful method of will_paginate library.
def paginate(options = {})
page = options[:page] || 1
per_page = options[:per_page] || WillPaginate.per_page
total = options[:total_entries] || self.length
WillPaginate::Collection.create(page, per_page, total) do |pager|
pager.replace self[pager.offset, pager.per_page].to_a
end
end
end
| ruby | MIT | 50017c3eb0712e7b3a53268a81e81a184b7a49f6 | 2026-01-04T15:42:46.511340Z | false |
mislav/will_paginate | https://github.com/mislav/will_paginate/blob/50017c3eb0712e7b3a53268a81e81a184b7a49f6/lib/will_paginate/mongoid.rb | lib/will_paginate/mongoid.rb | require 'mongoid'
require 'will_paginate/collection'
module WillPaginate
module Mongoid
module CriteriaMethods
def paginate(options = {})
extend CollectionMethods
@current_page = WillPaginate::PageNumber(options[:page] || @current_page || 1)
@page_multiplier = current_page - 1
@total_entries = options.delete(:total_entries)
pp = (options[:per_page] || per_page || WillPaginate.per_page).to_i
limit(pp).skip(@page_multiplier * pp)
end
def per_page(value = :non_given)
if value == :non_given
options[:limit] == 0 ? nil : options[:limit] # in new Mongoid versions a nil limit is saved as 0
else
limit(value)
end
end
def page(page)
paginate(:page => page)
end
end
module CollectionMethods
attr_reader :current_page
def total_entries
@total_entries ||= count
end
def total_pages
(total_entries / per_page.to_f).ceil
end
def offset
@page_multiplier * per_page
end
end
::Mongoid::Criteria.send(:include, CriteriaMethods)
end
end
| ruby | MIT | 50017c3eb0712e7b3a53268a81e81a184b7a49f6 | 2026-01-04T15:42:46.511340Z | false |
mislav/will_paginate | https://github.com/mislav/will_paginate/blob/50017c3eb0712e7b3a53268a81e81a184b7a49f6/lib/will_paginate/railtie.rb | lib/will_paginate/railtie.rb | require 'will_paginate/page_number'
require 'will_paginate/collection'
require 'will_paginate/i18n'
module WillPaginate
class Railtie < Rails::Railtie
initializer "will_paginate" do |app|
ActiveSupport.on_load :active_record do
require 'will_paginate/active_record'
end
ActiveSupport.on_load :action_controller do
WillPaginate::Railtie.setup_actioncontroller
end
ActiveSupport.on_load :action_view do
require 'will_paginate/view_helpers/action_view'
end
# early access to ViewHelpers.pagination_options
require 'will_paginate/view_helpers'
end
def self.setup_actioncontroller
( defined?(ActionDispatch::ExceptionWrapper) ?
ActionDispatch::ExceptionWrapper : ActionDispatch::ShowExceptions
).send :include, ShowExceptionsPatch
ActionController::Base.extend ControllerRescuePatch
end
# Extending the exception handler middleware so it properly detects
# WillPaginate::InvalidPage regardless of it being a tag module.
module ShowExceptionsPatch
extend ActiveSupport::Concern
included do
alias_method :status_code_without_paginate, :status_code
alias_method :status_code, :status_code_with_paginate
end
def status_code_with_paginate(exception = @exception)
actual_exception = if exception.respond_to?(:cause)
exception.cause || exception
elsif exception.respond_to?(:original_exception)
exception.original_exception
else
exception
end
if actual_exception.is_a?(WillPaginate::InvalidPage)
Rack::Utils.status_code(:not_found)
else
original_method = method(:status_code_without_paginate)
if original_method.arity != 0
original_method.call(exception)
else
original_method.call()
end
end
end
end
module ControllerRescuePatch
def rescue_from(*args, **kwargs, &block)
if idx = args.index(WillPaginate::InvalidPage)
args[idx] = args[idx].name
end
super(*args, **kwargs, &block)
end
end
end
end
ActiveSupport.on_load :i18n do
I18n.load_path.concat(WillPaginate::I18n.load_path)
end
| ruby | MIT | 50017c3eb0712e7b3a53268a81e81a184b7a49f6 | 2026-01-04T15:42:46.511340Z | false |
mislav/will_paginate | https://github.com/mislav/will_paginate/blob/50017c3eb0712e7b3a53268a81e81a184b7a49f6/lib/will_paginate/i18n.rb | lib/will_paginate/i18n.rb | module WillPaginate
module I18n
def self.locale_dir
File.expand_path('../locale', __FILE__)
end
def self.load_path
Dir["#{locale_dir}/*.{rb,yml}"]
end
def will_paginate_translate(keys, options = {}, &block)
if defined? ::I18n
defaults = Array(keys).dup
defaults << block if block_given?
::I18n.translate(defaults.shift, **options.merge(:default => defaults, :scope => :will_paginate))
else
key = Array === keys ? keys.first : keys
yield key, options
end
end
end
end
| ruby | MIT | 50017c3eb0712e7b3a53268a81e81a184b7a49f6 | 2026-01-04T15:42:46.511340Z | false |
mislav/will_paginate | https://github.com/mislav/will_paginate/blob/50017c3eb0712e7b3a53268a81e81a184b7a49f6/lib/will_paginate/per_page.rb | lib/will_paginate/per_page.rb | module WillPaginate
module PerPage
def per_page
defined?(@per_page) ? @per_page : WillPaginate.per_page
end
def per_page=(limit)
@per_page = limit.to_i
end
def self.extended(base)
base.extend Inheritance if base.is_a? Class
end
module Inheritance
def inherited(subclass)
super
subclass.per_page = self.per_page
end
end
end
extend PerPage
# default number of items per page
self.per_page = 30
end
| ruby | MIT | 50017c3eb0712e7b3a53268a81e81a184b7a49f6 | 2026-01-04T15:42:46.511340Z | false |
mislav/will_paginate | https://github.com/mislav/will_paginate/blob/50017c3eb0712e7b3a53268a81e81a184b7a49f6/lib/will_paginate/view_helpers/sinatra.rb | lib/will_paginate/view_helpers/sinatra.rb | require 'sinatra/base'
require 'will_paginate/view_helpers'
require 'will_paginate/view_helpers/link_renderer'
module WillPaginate
module Sinatra
module Helpers
include ViewHelpers
def will_paginate(collection, options = {}) #:nodoc:
options = options.merge(:renderer => LinkRenderer) unless options[:renderer]
super(collection, options)
end
end
class LinkRenderer < ViewHelpers::LinkRenderer
protected
def url(page)
str = File.join(request.script_name.to_s, request.path_info)
params = request.GET.merge(param_name.to_s => page.to_s)
params.update @options[:params] if @options[:params]
str << '?' << build_query(params)
end
def request
@template.request
end
def build_query(params)
Rack::Utils.build_nested_query params
end
end
def self.registered(app)
app.helpers Helpers
end
::Sinatra.register self
end
end
| ruby | MIT | 50017c3eb0712e7b3a53268a81e81a184b7a49f6 | 2026-01-04T15:42:46.511340Z | false |
mislav/will_paginate | https://github.com/mislav/will_paginate/blob/50017c3eb0712e7b3a53268a81e81a184b7a49f6/lib/will_paginate/view_helpers/action_view.rb | lib/will_paginate/view_helpers/action_view.rb | require 'will_paginate/view_helpers'
require 'will_paginate/view_helpers/link_renderer'
module WillPaginate
# = ActionView helpers
#
# This module serves for availability in ActionView templates. It also adds a new
# view helper: +paginated_section+.
#
# == Using the helper without arguments
# If the helper is called without passing in the collection object, it will
# try to read from the instance variable inferred by the controller name.
# For example, calling +will_paginate+ while the current controller is
# PostsController will result in trying to read from the <tt>@posts</tt>
# variable. Example:
#
# <%= will_paginate :id => true %>
#
# ... will result in <tt>@post</tt> collection getting paginated:
#
# <div class="pagination" id="posts_pagination"> ... </div>
#
module ActionView
include ViewHelpers
def will_paginate(collection = nil, options = {}) #:nodoc:
options, collection = collection, nil if collection.is_a? Hash
collection ||= infer_collection_from_controller
options = options.symbolize_keys
options[:renderer] ||= LinkRenderer
super(collection, options)
end
def page_entries_info(collection = nil, options = {}) #:nodoc:
options, collection = collection, nil if collection.is_a? Hash
collection ||= infer_collection_from_controller
super(collection, options.symbolize_keys)
end
# Wrapper for rendering pagination links at both top and bottom of a block
# of content.
#
# <%= paginated_section @posts do %>
# <ol id="posts">
# <% for post in @posts %>
# <li> ... </li>
# <% end %>
# </ol>
# <% end %>
#
# will result in:
#
# <div class="pagination"> ... </div>
# <ol id="posts">
# ...
# </ol>
# <div class="pagination"> ... </div>
#
# Arguments are passed to a <tt>will_paginate</tt> call, so the same options
# apply. Don't use the <tt>:id</tt> option; otherwise you'll finish with two
# blocks of pagination links sharing the same ID (which is invalid HTML).
def paginated_section(*args, &block)
pagination = will_paginate(*args)
if pagination
pagination + capture(&block) + pagination
else
capture(&block)
end
end
def will_paginate_translate(keys, options = {})
if respond_to? :translate
if Array === keys
defaults = keys.dup
key = defaults.shift
else
defaults = nil
key = keys
end
translate(key, **options.merge(:default => defaults, :scope => :will_paginate))
else
super
end
end
protected
def infer_collection_from_controller
collection_name = "@#{controller.controller_name}"
collection = instance_variable_get(collection_name)
raise ArgumentError, "The #{collection_name} variable appears to be empty. Did you " +
"forget to pass the collection object for will_paginate?" if collection.nil?
collection
end
class LinkRenderer < ViewHelpers::LinkRenderer
protected
GET_PARAMS_BLACKLIST = [:script_name, :original_script_name]
def default_url_params
{}
end
def url(page)
@base_url_params ||= begin
url_params = merge_get_params(default_url_params)
url_params[:only_path] = true
merge_optional_params(url_params)
end
url_params = @base_url_params.dup
add_current_page_param(url_params, page)
@template.url_for(url_params)
end
def merge_get_params(url_params)
if @template.respond_to?(:request) and @template.request
if @template.request.get?
symbolized_update(url_params, @template.params, GET_PARAMS_BLACKLIST)
elsif @template.request.respond_to?(:query_parameters)
symbolized_update(url_params, @template.request.query_parameters, GET_PARAMS_BLACKLIST)
end
end
url_params
end
def merge_optional_params(url_params)
symbolized_update(url_params, @options[:params]) if @options[:params]
url_params
end
def add_current_page_param(url_params, page)
unless param_name.index(/[^\w-]/)
url_params[param_name.to_sym] = page
else
page_param = parse_query_parameters("#{param_name}=#{page}")
symbolized_update(url_params, page_param)
end
end
private
def parse_query_parameters(params)
Rack::Utils.parse_nested_query(params)
end
end
::ActionView::Base.send :include, self
end
end
| ruby | MIT | 50017c3eb0712e7b3a53268a81e81a184b7a49f6 | 2026-01-04T15:42:46.511340Z | false |
mislav/will_paginate | https://github.com/mislav/will_paginate/blob/50017c3eb0712e7b3a53268a81e81a184b7a49f6/lib/will_paginate/view_helpers/link_renderer.rb | lib/will_paginate/view_helpers/link_renderer.rb | require 'cgi'
require 'will_paginate/core_ext'
require 'will_paginate/view_helpers'
require 'will_paginate/view_helpers/link_renderer_base'
module WillPaginate
module ViewHelpers
# This class does the heavy lifting of actually building the pagination
# links. It is used by +will_paginate+ helper internally.
class LinkRenderer < LinkRendererBase
# * +collection+ is a WillPaginate::Collection instance or any other object
# that conforms to that API
# * +options+ are forwarded from +will_paginate+ view helper
# * +template+ is the reference to the template being rendered
def prepare(collection, options, template)
super(collection, options)
@template = template
@container_attributes = @base_url_params = nil
end
# Process it! This method returns the complete HTML string which contains
# pagination links. Feel free to subclass LinkRenderer and change this
# method as you see fit.
def to_html
html = pagination.map do |item|
item.is_a?(Integer) ?
page_number(item) :
send(item)
end.join(@options[:link_separator])
@options[:container] ? html_container(html) : html
end
# Returns the subset of +options+ this instance was initialized with that
# represent HTML attributes for the container element of pagination links.
def container_attributes
@container_attributes ||= {
:role => 'navigation',
:"aria-label" => @template.will_paginate_translate(:container_aria_label) { 'Pagination' }
}.update @options.except(*(ViewHelpers.pagination_options.keys + [:renderer] - [:class]))
end
protected
def page_number(page)
aria_label = @template.will_paginate_translate(:page_aria_label, :page => page.to_i) { "Page #{page}" }
if page == current_page
tag(:em, page, :class => 'current', :"aria-label" => aria_label, :"aria-current" => 'page')
else
link(page, page, :rel => rel_value(page), :"aria-label" => aria_label)
end
end
def gap
text = @template.will_paginate_translate(:page_gap) { '…' }
%(<span class="gap">#{text}</span>)
end
def previous_page
num = @collection.current_page > 1 && @collection.current_page - 1
aria_label = @template.will_paginate_translate(:previous_aria_label) { "Previous page" }
previous_or_next_page(num, @options[:previous_label], 'previous_page', aria_label)
end
def next_page
num = @collection.current_page < total_pages && @collection.current_page + 1
aria_label = @template.will_paginate_translate(:next_aria_label) { "Next page" }
previous_or_next_page(num, @options[:next_label], 'next_page', aria_label)
end
def previous_or_next_page(page, text, classname, aria_label = nil)
if page
link(text, page, :class => classname, :'aria-label' => aria_label)
else
tag(:span, text, :class => classname + ' disabled', :'aria-label' => aria_label)
end
end
def html_container(html)
tag(:div, html, container_attributes)
end
# Returns URL params for +page_link_or_span+, taking the current GET params
# and <tt>:params</tt> option into account.
def url(page)
raise NotImplementedError
end
private
def param_name
@options[:param_name].to_s
end
def link(text, target, attributes = {})
if target.is_a?(Integer)
attributes[:rel] = rel_value(target)
target = url(target)
end
attributes[:href] = target
tag(:a, text, attributes)
end
def tag(name, value, attributes = {})
string_attributes = attributes.map do |pair|
unless pair.last.nil?
%( #{pair.first}="#{CGI::escapeHTML(pair.last.to_s)}")
end
end
"<#{name}#{string_attributes.compact.join("")}>#{value}</#{name}>"
end
def rel_value(page)
case page
when @collection.current_page - 1; 'prev'
when @collection.current_page + 1; 'next'
end
end
def symbolized_update(target, other, blacklist = nil)
other.each_pair do |key, value|
key = key.to_sym
existing = target[key]
next if blacklist && blacklist.include?(key)
if value.respond_to?(:each_pair) and (existing.is_a?(Hash) or existing.nil?)
symbolized_update(existing || (target[key] = {}), value)
else
target[key] = value
end
end
end
end
end
end
| ruby | MIT | 50017c3eb0712e7b3a53268a81e81a184b7a49f6 | 2026-01-04T15:42:46.511340Z | false |
mislav/will_paginate | https://github.com/mislav/will_paginate/blob/50017c3eb0712e7b3a53268a81e81a184b7a49f6/lib/will_paginate/view_helpers/link_renderer_base.rb | lib/will_paginate/view_helpers/link_renderer_base.rb | module WillPaginate
module ViewHelpers
# This class does the heavy lifting of actually building the pagination
# links. It is used by +will_paginate+ helper internally.
class LinkRendererBase
# * +collection+ is a WillPaginate::Collection instance or any other object
# that conforms to that API
# * +options+ are forwarded from +will_paginate+ view helper
def prepare(collection, options)
@collection = collection
@options = options
# reset values in case we're re-using this instance
@total_pages = nil
end
def pagination
items = @options[:page_links] ? windowed_page_numbers : []
items.unshift :previous_page
items.push :next_page
end
protected
# Calculates visible page numbers using the <tt>:inner_window</tt> and
# <tt>:outer_window</tt> options.
def windowed_page_numbers
inner_window, outer_window = @options[:inner_window].to_i, @options[:outer_window].to_i
window_from = current_page - inner_window
window_to = current_page + inner_window
# adjust lower or upper limit if either is out of bounds
if window_to > total_pages
window_from -= window_to - total_pages
window_to = total_pages
end
if window_from < 1
window_to += 1 - window_from
window_from = 1
window_to = total_pages if window_to > total_pages
end
# these are always visible
middle = window_from..window_to
# left window
if outer_window + 3 < middle.first # there's a gap
left = (1..(outer_window + 1)).to_a
left << :gap
else # runs into visible pages
left = 1...middle.first
end
# right window
if total_pages - outer_window - 2 > middle.last # again, gap
right = ((total_pages - outer_window)..total_pages).to_a
right.unshift :gap
else # runs into visible pages
right = (middle.last + 1)..total_pages
end
left.to_a + middle.to_a + right.to_a
end
private
def current_page
@collection.current_page
end
def total_pages
@total_pages ||= @collection.total_pages
end
end
end
end
| ruby | MIT | 50017c3eb0712e7b3a53268a81e81a184b7a49f6 | 2026-01-04T15:42:46.511340Z | false |
mislav/will_paginate | https://github.com/mislav/will_paginate/blob/50017c3eb0712e7b3a53268a81e81a184b7a49f6/lib/will_paginate/view_helpers/hanami.rb | lib/will_paginate/view_helpers/hanami.rb | require 'hanami/view'
require 'will_paginate/view_helpers'
require 'will_paginate/view_helpers/link_renderer'
module WillPaginate
module Hanami
module Helpers
include ViewHelpers
def will_paginate(collection, options = {}) #:nodoc:
options = options.merge(:renderer => LinkRenderer) unless options[:renderer]
str = super(collection, options)
str && raw(str)
end
end
class LinkRenderer < ViewHelpers::LinkRenderer
protected
def url(page)
str = File.join(request_env['SCRIPT_NAME'].to_s, request_env['PATH_INFO'])
params = request_env['rack.request.query_hash'].merge(param_name.to_s => page.to_s)
params.update @options[:params] if @options[:params]
str << '?' << build_query(params)
end
def request_env
@template.params.env
end
def build_query(params)
Rack::Utils.build_nested_query params
end
end
def self.included(base)
base.include Helpers
end
end
end
| ruby | MIT | 50017c3eb0712e7b3a53268a81e81a184b7a49f6 | 2026-01-04T15:42:46.511340Z | false |
mislav/will_paginate | https://github.com/mislav/will_paginate/blob/50017c3eb0712e7b3a53268a81e81a184b7a49f6/environments/Gemfile.non-rails.rb | environments/Gemfile.non-rails.rb | source 'https://rubygems.org'
gem 'rspec', '~> 3.12'
gem 'mocha', '~> 2.0'
gem 'sqlite3', '~> 1.4.0'
gem 'sequel', '~> 5.29'
gem 'mongoid', '~> 7.2.0'
| ruby | MIT | 50017c3eb0712e7b3a53268a81e81a184b7a49f6 | 2026-01-04T15:42:46.511340Z | false |
mislav/will_paginate | https://github.com/mislav/will_paginate/blob/50017c3eb0712e7b3a53268a81e81a184b7a49f6/environments/Gemfile.rails6.1.rb | environments/Gemfile.rails6.1.rb | source 'https://rubygems.org'
rails_version = '~> 6.1.0'
gem 'activerecord', rails_version
gem 'actionpack', rails_version
gem 'rspec', '~> 3.12'
gem 'mocha', '~> 2.0'
gem 'sqlite3', '~> 1.4.0'
gem 'mysql2', '~> 0.5.2', :group => :mysql
gem 'pg', '~> 1.2', :group => :pg
| ruby | MIT | 50017c3eb0712e7b3a53268a81e81a184b7a49f6 | 2026-01-04T15:42:46.511340Z | false |
mislav/will_paginate | https://github.com/mislav/will_paginate/blob/50017c3eb0712e7b3a53268a81e81a184b7a49f6/environments/Gemfile.rails5.2.rb | environments/Gemfile.rails5.2.rb | source 'https://rubygems.org'
rails_version = '~> 5.2.4'
gem 'activerecord', rails_version
gem 'actionpack', rails_version
gem 'rspec', '~> 3.12'
gem 'mocha', '~> 2.0'
gem 'sqlite3', '~> 1.3.6'
gem 'mysql2', '~> 0.5.2', :group => :mysql
gem 'pg', '~> 1.2.3', :group => :pg
# ruby 2.4 compat re: nokogiri
gem 'loofah', '< 2.21.0'
| ruby | MIT | 50017c3eb0712e7b3a53268a81e81a184b7a49f6 | 2026-01-04T15:42:46.511340Z | false |
mislav/will_paginate | https://github.com/mislav/will_paginate/blob/50017c3eb0712e7b3a53268a81e81a184b7a49f6/environments/Gemfile.rails7.0.rb | environments/Gemfile.rails7.0.rb | source 'https://rubygems.org'
# We test against other Rails versions, too. See `environments/`
rails_version = '~> 7.0.2'
gem 'activerecord', rails_version
gem 'actionpack', rails_version
gem 'rspec', '~> 3.12'
gem 'mocha', '~> 2.0'
gem 'sqlite3', '~> 1.5.0'
gem 'mysql2', '~> 0.5.2', :group => :mysql
gem 'pg', '~> 1.2', :group => :pg
| ruby | MIT | 50017c3eb0712e7b3a53268a81e81a184b7a49f6 | 2026-01-04T15:42:46.511340Z | false |
mislav/will_paginate | https://github.com/mislav/will_paginate/blob/50017c3eb0712e7b3a53268a81e81a184b7a49f6/environments/Gemfile.rails5.0.rb | environments/Gemfile.rails5.0.rb | source 'https://rubygems.org'
rails_version = '~> 5.0.7'
gem 'activerecord', rails_version
gem 'actionpack', rails_version
gem 'rails-dom-testing'
gem 'rspec', '~> 3.12'
gem 'mocha', '~> 2.0'
gem 'sqlite3', '~> 1.3.6'
gem 'mysql2', '~> 0.5.2', :group => :mysql
gem 'pg', '~> 1.2.3', :group => :pg
# ruby 2.4 compat re: nokogiri
gem 'loofah', '< 2.21.0'
| ruby | MIT | 50017c3eb0712e7b3a53268a81e81a184b7a49f6 | 2026-01-04T15:42:46.511340Z | false |
mislav/will_paginate | https://github.com/mislav/will_paginate/blob/50017c3eb0712e7b3a53268a81e81a184b7a49f6/environments/Gemfile.rails-edge.rb | environments/Gemfile.rails-edge.rb | source 'https://rubygems.org'
gem 'activerecord', git: 'https://github.com/rails/rails.git', branch: 'main'
gem 'actionpack', git: 'https://github.com/rails/rails.git', branch: 'main'
gem 'thread_safe'
gem 'rspec', '~> 3.12'
gem 'mocha', '~> 2.0'
gem 'sqlite3', '~> 1.4.0'
gem 'mysql2', '~> 0.5.2', :group => :mysql
gem 'pg', '~> 1.2', :group => :pg
| ruby | MIT | 50017c3eb0712e7b3a53268a81e81a184b7a49f6 | 2026-01-04T15:42:46.511340Z | false |
mislav/will_paginate | https://github.com/mislav/will_paginate/blob/50017c3eb0712e7b3a53268a81e81a184b7a49f6/environments/Gemfile.rails5.1.rb | environments/Gemfile.rails5.1.rb | source 'https://rubygems.org'
rails_version = '~> 5.1.7'
gem 'activerecord', rails_version
gem 'actionpack', rails_version
gem 'rspec', '~> 3.12'
gem 'mocha', '~> 2.0'
gem 'sqlite3', '~> 1.3.6'
gem 'mysql2', '~> 0.5.2', :group => :mysql
gem 'pg', '~> 1.2.3', :group => :pg
# ruby 2.4 compat re: nokogiri
gem 'loofah', '< 2.21.0'
| ruby | MIT | 50017c3eb0712e7b3a53268a81e81a184b7a49f6 | 2026-01-04T15:42:46.511340Z | false |
mislav/will_paginate | https://github.com/mislav/will_paginate/blob/50017c3eb0712e7b3a53268a81e81a184b7a49f6/environments/Gemfile.rails6.0.rb | environments/Gemfile.rails6.0.rb | source 'https://rubygems.org'
rails_version = '~> 6.0.0'
gem 'activerecord', rails_version
gem 'actionpack', rails_version
gem 'rspec', '~> 3.12'
gem 'mocha', '~> 2.0'
gem 'sqlite3', '~> 1.4.0'
gem 'mysql2', '~> 0.5.2', :group => :mysql
gem 'pg', '~> 1.2', :group => :pg
| ruby | MIT | 50017c3eb0712e7b3a53268a81e81a184b7a49f6 | 2026-01-04T15:42:46.511340Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/spec/rack_attack_path_normalizer_spec.rb | spec/rack_attack_path_normalizer_spec.rb | # frozen_string_literal: true
require_relative 'spec_helper'
describe Rack::Attack::PathNormalizer do
subject { Rack::Attack::PathNormalizer }
it 'should have a normalize_path method' do
_(subject.normalize_path('/foo')).must_equal '/foo'
end
describe 'FallbackNormalizer' do
subject { Rack::Attack::FallbackPathNormalizer }
it '#normalize_path does not change the path' do
_(subject.normalize_path('')).must_equal ''
end
end
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/spec/rack_attack_dalli_proxy_spec.rb | spec/rack_attack_dalli_proxy_spec.rb | # frozen_string_literal: true
require_relative 'spec_helper'
describe Rack::Attack::StoreProxy::DalliProxy do
it 'should stub Dalli::Client#with on older clients' do
proxy = Rack::Attack::StoreProxy::DalliProxy.new(Class.new)
proxy.with {} # will not raise an error
end
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/spec/configuration_spec.rb | spec/configuration_spec.rb | # frozen_string_literal: true
require_relative "spec_helper"
describe Rack::Attack::Configuration do
subject { Rack::Attack::Configuration.new }
describe 'attributes' do
it 'exposes the safelists attribute' do
_(subject.safelists).must_equal({})
end
it 'exposes the blocklists attribute' do
_(subject.blocklists).must_equal({})
end
it 'exposes the throttles attribute' do
_(subject.throttles).must_equal({})
end
it 'exposes the tracks attribute' do
_(subject.tracks).must_equal({})
end
it 'exposes the anonymous_blocklists attribute' do
_(subject.anonymous_blocklists).must_equal([])
end
it 'exposes the anonymous_safelists attribute' do
_(subject.anonymous_safelists).must_equal([])
end
end
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/spec/rack_attack_spec.rb | spec/rack_attack_spec.rb | # frozen_string_literal: true
require_relative 'spec_helper'
describe 'Rack::Attack' do
it_allows_ok_requests
describe 'normalizing paths' do
before do
Rack::Attack.blocklist("banned_path") { |req| req.path == '/foo' }
end
it 'blocks requests with trailing slash' do
if Rack::Attack::PathNormalizer == Rack::Attack::FallbackPathNormalizer
skip "Normalization is only present on Rails"
end
get '/foo/'
_(last_response.status).must_equal 403
end
end
describe 'blocklist' do
before do
@bad_ip = '1.2.3.4'
Rack::Attack.blocklist("ip #{@bad_ip}") { |req| req.ip == @bad_ip }
end
it 'has a blocklist' do
_(Rack::Attack.blocklists.key?("ip #{@bad_ip}")).must_equal true
end
describe "a bad request" do
before { get '/', {}, 'REMOTE_ADDR' => @bad_ip }
it "should return a blocklist response" do
_(last_response.status).must_equal 403
_(last_response.body).must_equal "Forbidden\n"
end
it "should tag the env" do
_(last_request.env['rack.attack.matched']).must_equal "ip #{@bad_ip}"
_(last_request.env['rack.attack.match_type']).must_equal :blocklist
end
it_allows_ok_requests
end
describe "and safelist" do
before do
@good_ua = 'GoodUA'
Rack::Attack.safelist("good ua") { |req| req.user_agent == @good_ua }
end
it('has a safelist') { Rack::Attack.safelists.key?("good ua") }
describe "with a request match both safelist & blocklist" do
before { get '/', {}, 'REMOTE_ADDR' => @bad_ip, 'HTTP_USER_AGENT' => @good_ua }
it "should allow safelists before blocklists" do
_(last_response.status).must_equal 200
end
it "should tag the env" do
_(last_request.env['rack.attack.matched']).must_equal 'good ua'
_(last_request.env['rack.attack.match_type']).must_equal :safelist
end
end
end
describe '#blocklisted_responder' do
it 'should exist' do
_(Rack::Attack.blocklisted_responder).must_respond_to :call
end
end
describe '#throttled_responder' do
it 'should exist' do
_(Rack::Attack.throttled_responder).must_respond_to :call
end
end
end
describe 'enabled' do
it 'should be enabled by default' do
_(Rack::Attack.enabled).must_equal true
end
it 'should directly pass request when disabled' do
bad_ip = '1.2.3.4'
Rack::Attack.blocklist("ip #{bad_ip}") { |req| req.ip == bad_ip }
get '/', {}, 'REMOTE_ADDR' => bad_ip
_(last_response.status).must_equal 403
prev_enabled = Rack::Attack.enabled
begin
Rack::Attack.enabled = false
get '/', {}, 'REMOTE_ADDR' => bad_ip
_(last_response.status).must_equal 200
ensure
Rack::Attack.enabled = prev_enabled
end
end
end
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/spec/rack_attack_reset_spec.rb | spec/rack_attack_reset_spec.rb | # frozen_string_literal: true
require_relative "spec_helper"
describe "Rack::Attack.reset!" do
it "raises an error when is not supported by cache store" do
Rack::Attack.cache.store = Class.new
assert_raises(Rack::Attack::IncompatibleStoreError) do
Rack::Attack.reset!
end
end
if defined?(Redis)
it "should delete rack attack keys" do
redis = Redis.new
redis.set("key", "value")
redis.set("#{Rack::Attack.cache.prefix}::key", "value")
Rack::Attack.cache.store = redis
Rack::Attack.reset!
_(redis.get("key")).must_equal "value"
_(redis.get("#{Rack::Attack.cache.prefix}::key")).must_be_nil
end
end
if defined?(Redis::Store)
it "should delete rack attack keys" do
redis_store = Redis::Store.new
redis_store.set("key", "value")
redis_store.set("#{Rack::Attack.cache.prefix}::key", "value")
Rack::Attack.cache.store = redis_store
Rack::Attack.reset!
_(redis_store.get("key")).must_equal "value"
_(redis_store.get("#{Rack::Attack.cache.prefix}::key")).must_be_nil
end
end
if defined?(Redis) && defined?(ActiveSupport::Cache::RedisCacheStore)
it "should delete rack attack keys" do
redis_cache_store = ActiveSupport::Cache::RedisCacheStore.new
redis_cache_store.write("key", "value")
redis_cache_store.write("#{Rack::Attack.cache.prefix}::key", "value")
Rack::Attack.cache.store = redis_cache_store
Rack::Attack.reset!
_(redis_cache_store.read("key")).must_equal "value"
_(redis_cache_store.read("#{Rack::Attack.cache.prefix}::key")).must_be_nil
end
describe "with a namespaced cache" do
it "should delete rack attack keys" do
redis_cache_store = ActiveSupport::Cache::RedisCacheStore.new(namespace: "ns")
redis_cache_store.write("key", "value")
redis_cache_store.write("#{Rack::Attack.cache.prefix}::key", "value")
Rack::Attack.cache.store = redis_cache_store
Rack::Attack.reset!
_(redis_cache_store.read("key")).must_equal "value"
_(redis_cache_store.read("#{Rack::Attack.cache.prefix}::key")).must_be_nil
end
end
end
if defined?(ActiveSupport::Cache::MemoryStore)
it "should delete rack attack keys" do
memory_store = ActiveSupport::Cache::MemoryStore.new
memory_store.write("key", "value")
memory_store.write("#{Rack::Attack.cache.prefix}::key", "value")
Rack::Attack.cache.store = memory_store
Rack::Attack.reset!
_(memory_store.read("key")).must_equal "value"
_(memory_store.read("#{Rack::Attack.cache.prefix}::key")).must_be_nil
end
describe "with a namespaced cache" do
it "should delete rack attack keys" do
memory_store = ActiveSupport::Cache::MemoryStore.new(namespace: "ns")
memory_store.write("key", "value")
memory_store.write("#{Rack::Attack.cache.prefix}::key", "value")
Rack::Attack.cache.store = memory_store
Rack::Attack.reset!
_(memory_store.read("key")).must_equal "value"
_(memory_store.read("#{Rack::Attack.cache.prefix}::key")).must_be_nil
end
end
end
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/spec/allow2ban_spec.rb | spec/allow2ban_spec.rb | # frozen_string_literal: true
require_relative 'spec_helper'
describe 'Rack::Attack.Allow2Ban' do
before do
# Use a long findtime; failures due to cache key rotation less likely
@cache = Rack::Attack.cache
@findtime = 60
@bantime = 60
Rack::Attack.cache.store = ActiveSupport::Cache::MemoryStore.new
@f2b_options = { bantime: @bantime, findtime: @findtime, maxretry: 2 }
Rack::Attack.blocklist('pentest') do |req|
Rack::Attack::Allow2Ban.filter(req.ip, @f2b_options) { req.query_string =~ /OMGHAX/ }
end
end
describe 'discriminator has not been banned' do
describe 'making ok request' do
it 'succeeds' do
get '/', {}, 'REMOTE_ADDR' => '1.2.3.4'
_(last_response.status).must_equal 200
end
end
describe 'making qualifying request' do
describe 'when not at maxretry' do
before { get '/?foo=OMGHAX', {}, 'REMOTE_ADDR' => '1.2.3.4' }
it 'succeeds' do
_(last_response.status).must_equal 200
end
it 'increases fail count' do
key = "rack::attack:#{Time.now.to_i / @findtime}:allow2ban:count:1.2.3.4"
_(@cache.store.read(key)).must_equal 1
end
it 'is not banned' do
key = "rack::attack:allow2ban:1.2.3.4"
_(@cache.store.read(key)).must_be_nil
end
end
describe 'when at maxretry' do
before do
# maxretry is 2 - so hit with an extra failed request first
get '/?test=OMGHAX', {}, 'REMOTE_ADDR' => '1.2.3.4'
get '/?foo=OMGHAX', {}, 'REMOTE_ADDR' => '1.2.3.4'
end
it 'succeeds' do
_(last_response.status).must_equal 200
end
it 'increases fail count' do
key = "rack::attack:#{Time.now.to_i / @findtime}:allow2ban:count:1.2.3.4"
_(@cache.store.read(key)).must_equal 2
end
it 'is banned' do
key = "rack::attack:allow2ban:ban:1.2.3.4"
_(@cache.store.read(key)).must_equal 1
end
end
end
end
describe 'discriminator has been banned' do
before do
# maxretry is 2 - so hit enough times to get banned
get '/?test=OMGHAX', {}, 'REMOTE_ADDR' => '1.2.3.4'
get '/?foo=OMGHAX', {}, 'REMOTE_ADDR' => '1.2.3.4'
end
describe 'making request for other discriminator' do
it 'succeeds' do
get '/', {}, 'REMOTE_ADDR' => '2.2.3.4'
_(last_response.status).must_equal 200
end
end
describe 'making ok request' do
before do
get '/', {}, 'REMOTE_ADDR' => '1.2.3.4'
end
it 'fails' do
_(last_response.status).must_equal 403
end
it 'does not increase fail count' do
key = "rack::attack:#{Time.now.to_i / @findtime}:allow2ban:count:1.2.3.4"
_(@cache.store.read(key)).must_equal 2
end
it 'is still banned' do
key = "rack::attack:allow2ban:ban:1.2.3.4"
_(@cache.store.read(key)).must_equal 1
end
end
describe 'making failing request' do
before do
get '/?foo=OMGHAX', {}, 'REMOTE_ADDR' => '1.2.3.4'
end
it 'fails' do
_(last_response.status).must_equal 403
end
it 'does not increase fail count' do
key = "rack::attack:#{Time.now.to_i / @findtime}:allow2ban:count:1.2.3.4"
_(@cache.store.read(key)).must_equal 2
end
it 'is still banned' do
key = "rack::attack:allow2ban:ban:1.2.3.4"
_(@cache.store.read(key)).must_equal 1
end
end
end
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/spec/fail2ban_spec.rb | spec/fail2ban_spec.rb | # frozen_string_literal: true
require_relative 'spec_helper'
describe 'Rack::Attack.Fail2Ban' do
before do
# Use a long findtime; failures due to cache key rotation less likely
@cache = Rack::Attack.cache
@findtime = 60
@bantime = 60
Rack::Attack.cache.store = ActiveSupport::Cache::MemoryStore.new
@f2b_options = { bantime: @bantime, findtime: @findtime, maxretry: 2 }
Rack::Attack.blocklist('pentest') do |req|
Rack::Attack::Fail2Ban.filter(req.ip, @f2b_options) { req.query_string =~ /OMGHAX/ }
end
end
describe 'discriminator has not been banned' do
describe 'making ok request' do
it 'succeeds' do
get '/', {}, 'REMOTE_ADDR' => '1.2.3.4'
_(last_response.status).must_equal 200
end
end
describe 'making failing request' do
describe 'when not at maxretry' do
before { get '/?foo=OMGHAX', {}, 'REMOTE_ADDR' => '1.2.3.4' }
it 'fails' do
_(last_response.status).must_equal 403
end
it 'increases fail count' do
key = "rack::attack:#{Time.now.to_i / @findtime}:fail2ban:count:1.2.3.4"
_(@cache.store.read(key)).must_equal 1
end
it 'is not banned' do
key = "rack::attack:fail2ban:1.2.3.4"
_(@cache.store.read(key)).must_be_nil
end
end
describe 'when at maxretry' do
before do
# maxretry is 2 - so hit with an extra failed request first
get '/?test=OMGHAX', {}, 'REMOTE_ADDR' => '1.2.3.4'
get '/?foo=OMGHAX', {}, 'REMOTE_ADDR' => '1.2.3.4'
end
it 'fails' do
_(last_response.status).must_equal 403
end
it 'increases fail count' do
key = "rack::attack:#{Time.now.to_i / @findtime}:fail2ban:count:1.2.3.4"
_(@cache.store.read(key)).must_equal 2
end
it 'is banned' do
key = "rack::attack:fail2ban:ban:1.2.3.4"
_(@cache.store.read(key)).must_equal 1
end
end
describe 'reset after success' do
before do
get '/?test=OMGHAX', {}, 'REMOTE_ADDR' => '1.2.3.4'
Rack::Attack::Fail2Ban.reset('1.2.3.4', @f2b_options)
get '/', {}, 'REMOTE_ADDR' => '1.2.3.4'
end
it 'succeeds' do
_(last_response.status).must_equal 200
end
it 'resets fail count' do
key = "rack::attack:#{Time.now.to_i / @findtime}:fail2ban:count:1.2.3.4"
assert_nil @cache.store.read(key)
end
it 'IP is not banned' do
_(Rack::Attack::Fail2Ban.banned?('1.2.3.4')).must_equal false
end
end
end
end
describe 'discriminator has been banned' do
before do
# maxretry is 2 - so hit enough times to get banned
get '/?test=OMGHAX', {}, 'REMOTE_ADDR' => '1.2.3.4'
get '/?foo=OMGHAX', {}, 'REMOTE_ADDR' => '1.2.3.4'
end
describe 'making request for other discriminator' do
it 'succeeds' do
get '/', {}, 'REMOTE_ADDR' => '2.2.3.4'
_(last_response.status).must_equal 200
end
end
describe 'making ok request' do
before do
get '/', {}, 'REMOTE_ADDR' => '1.2.3.4'
end
it 'fails' do
_(last_response.status).must_equal 403
end
it 'does not increase fail count' do
key = "rack::attack:#{Time.now.to_i / @findtime}:fail2ban:count:1.2.3.4"
_(@cache.store.read(key)).must_equal 2
end
it 'is still banned' do
key = "rack::attack:fail2ban:ban:1.2.3.4"
_(@cache.store.read(key)).must_equal 1
end
end
describe 'making failing request' do
before do
get '/?foo=OMGHAX', {}, 'REMOTE_ADDR' => '1.2.3.4'
end
it 'fails' do
_(last_response.status).must_equal 403
end
it 'does not increase fail count' do
key = "rack::attack:#{Time.now.to_i / @findtime}:fail2ban:count:1.2.3.4"
_(@cache.store.read(key)).must_equal 2
end
it 'is still banned' do
key = "rack::attack:fail2ban:ban:1.2.3.4"
_(@cache.store.read(key)).must_equal 1
end
end
end
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/spec/rack_attack_request_spec.rb | spec/rack_attack_request_spec.rb | # frozen_string_literal: true
require_relative 'spec_helper'
describe 'Rack::Attack' do
describe 'helpers' do
before do
Rack::Attack::Request.define_method :remote_ip do
ip
end
Rack::Attack.safelist('valid IP') do |req|
req.remote_ip == "127.0.0.1"
end
end
it_allows_ok_requests
end
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/spec/rack_attack_track_spec.rb | spec/rack_attack_track_spec.rb | # frozen_string_literal: true
require_relative 'spec_helper'
describe 'Rack::Attack.track' do
let(:notifications) { [] }
before do
Rack::Attack.track("everything") { |_req| true }
end
it_allows_ok_requests
it "should tag the env" do
get '/'
_(last_request.env['rack.attack.matched']).must_equal 'everything'
_(last_request.env['rack.attack.match_type']).must_equal :track
end
describe "with a notification subscriber and two tracks" do
before do
# A second track
Rack::Attack.track("homepage") { |req| req.path == "/" }
ActiveSupport::Notifications.subscribe("track.rack_attack") do |_name, _start, _finish, _id, payload|
notifications.push(payload)
end
get "/"
end
it "should notify twice" do
_(notifications.size).must_equal 2
end
end
describe "without limit and period options" do
it "should assign the track filter to a Check instance" do
track = Rack::Attack.track("homepage") { |req| req.path == "/" }
_(track.filter.class).must_equal Rack::Attack::Check
end
end
describe "with limit and period options" do
it "should assign the track filter to a Throttle instance" do
track = Rack::Attack.track("homepage", limit: 10, period: 10) { |req| req.path == "/" }
_(track.filter.class).must_equal Rack::Attack::Throttle
end
end
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/spec/rack_attack_throttle_spec.rb | spec/rack_attack_throttle_spec.rb | # frozen_string_literal: true
require_relative 'spec_helper'
require_relative 'support/freeze_time_helper'
describe 'Rack::Attack.throttle' do
before do
@period = 60
Rack::Attack.cache.store = ActiveSupport::Cache::MemoryStore.new
Rack::Attack.throttle('ip/sec', limit: 1, period: @period) { |req| req.ip }
end
it('should have a throttle') { Rack::Attack.throttles.key?('ip/sec') }
it_allows_ok_requests
describe 'a single request' do
it 'should set the counter for one request' do
within_same_period do
get '/', {}, 'REMOTE_ADDR' => '1.2.3.4'
key = "rack::attack:#{Time.now.to_i / @period}:ip/sec:1.2.3.4"
_(Rack::Attack.cache.store.read(key)).must_equal 1
end
end
it 'should populate throttle data' do
get '/', {}, 'REMOTE_ADDR' => '1.2.3.4'
data = {
count: 1,
limit: 1,
period: @period,
epoch_time: Rack::Attack.cache.last_epoch_time.to_i,
discriminator: "1.2.3.4"
}
_(last_request.env['rack.attack.throttle_data']['ip/sec']).must_equal data
end
end
describe "with 2 requests" do
before do
within_same_period do
2.times { get '/', {}, 'REMOTE_ADDR' => '1.2.3.4' }
end
end
it 'should block the last request' do
_(last_response.status).must_equal 429
end
it 'should tag the env' do
_(last_request.env['rack.attack.matched']).must_equal 'ip/sec'
_(last_request.env['rack.attack.match_type']).must_equal :throttle
_(last_request.env['rack.attack.match_data']).must_equal(
count: 2,
limit: 1,
period: @period,
epoch_time: Rack::Attack.cache.last_epoch_time.to_i,
discriminator: "1.2.3.4"
)
_(last_request.env['rack.attack.match_discriminator']).must_equal('1.2.3.4')
end
end
end
describe 'Rack::Attack.throttle with limit as proc' do
before do
@period = 60
Rack::Attack.cache.store = ActiveSupport::Cache::MemoryStore.new
Rack::Attack.throttle('ip/sec', limit: lambda { |_req| 1 }, period: @period) { |req| req.ip }
end
it_allows_ok_requests
describe 'a single request' do
it 'should set the counter for one request' do
within_same_period do
get '/', {}, 'REMOTE_ADDR' => '1.2.3.4'
key = "rack::attack:#{Time.now.to_i / @period}:ip/sec:1.2.3.4"
_(Rack::Attack.cache.store.read(key)).must_equal 1
end
end
it 'should populate throttle data' do
get '/', {}, 'REMOTE_ADDR' => '1.2.3.4'
data = {
count: 1,
limit: 1,
period: @period,
epoch_time: Rack::Attack.cache.last_epoch_time.to_i,
discriminator: "1.2.3.4"
}
_(last_request.env['rack.attack.throttle_data']['ip/sec']).must_equal data
end
end
end
describe 'Rack::Attack.throttle with period as proc' do
before do
@period = 60
Rack::Attack.cache.store = ActiveSupport::Cache::MemoryStore.new
Rack::Attack.throttle('ip/sec', limit: lambda { |_req| 1 }, period: lambda { |_req| @period }) { |req| req.ip }
end
it_allows_ok_requests
describe 'a single request' do
it 'should set the counter for one request' do
within_same_period do
get '/', {}, 'REMOTE_ADDR' => '1.2.3.4'
key = "rack::attack:#{Time.now.to_i / @period}:ip/sec:1.2.3.4"
_(Rack::Attack.cache.store.read(key)).must_equal 1
end
end
it 'should populate throttle data' do
get '/', {}, 'REMOTE_ADDR' => '1.2.3.4'
data = {
count: 1,
limit: 1,
period: @period,
epoch_time: Rack::Attack.cache.last_epoch_time.to_i,
discriminator: "1.2.3.4"
}
_(last_request.env['rack.attack.throttle_data']['ip/sec']).must_equal data
end
end
end
describe 'Rack::Attack.throttle with block returning nil' do
before do
@period = 60
Rack::Attack.cache.store = ActiveSupport::Cache::MemoryStore.new
Rack::Attack.throttle('ip/sec', limit: 1, period: @period) { |_| nil }
end
it_allows_ok_requests
describe 'a single request' do
it 'should not set the counter' do
within_same_period do
get '/', {}, 'REMOTE_ADDR' => '1.2.3.4'
key = "rack::attack:#{Time.now.to_i / @period}:ip/sec:1.2.3.4"
assert_nil Rack::Attack.cache.store.read(key)
end
end
it 'should not populate throttle data' do
get '/', {}, 'REMOTE_ADDR' => '1.2.3.4'
assert_nil last_request.env['rack.attack.throttle_data']
end
end
end
describe 'Rack::Attack.throttle with throttle_discriminator_normalizer' do
before do
@period = 60
@emails = [
"person@example.com",
"PERSON@example.com ",
" person@example.com\r\n ",
]
Rack::Attack.cache.store = ActiveSupport::Cache::MemoryStore.new
Rack::Attack.throttle('logins/email', limit: 4, period: @period) do |req|
if req.path == '/login' && req.post?
req.params['email']
end
end
end
it 'should not differentiate requests when throttle_discriminator_normalizer is enabled' do
within_same_period do
post_logins
key = "rack::attack:#{Time.now.to_i / @period}:logins/email:person@example.com"
_(Rack::Attack.cache.store.read(key)).must_equal 3
end
end
it 'should differentiate requests when throttle_discriminator_normalizer is disabled' do
begin
prev = Rack::Attack.throttle_discriminator_normalizer
Rack::Attack.throttle_discriminator_normalizer = nil
within_same_period do
post_logins
@emails.each do |email|
key = "rack::attack:#{Time.now.to_i / @period}:logins/email:#{email}"
_(Rack::Attack.cache.store.read(key)).must_equal 1
end
end
ensure
Rack::Attack.throttle_discriminator_normalizer = prev
end
end
def post_logins
@emails.each do |email|
post '/login', email: email
end
end
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/spec/rack_attack_instrumentation_spec.rb | spec/rack_attack_instrumentation_spec.rb | # frozen_string_literal: true
require_relative "spec_helper"
require 'active_support'
require 'active_support/subscriber'
class CustomSubscriber < ActiveSupport::Subscriber
@notification_count = 0
class << self
attr_accessor :notification_count
end
def throttle(_event)
self.class.notification_count += 1
end
end
describe 'Rack::Attack.instrument' do
before do
@period = 60 # Use a long period; failures due to cache key rotation less likely
Rack::Attack.cache.store = ActiveSupport::Cache::MemoryStore.new
Rack::Attack.throttle('ip/sec', limit: 1, period: @period) { |req| req.ip }
end
describe "with throttling" do
before do
ActiveSupport::Notifications.stub(:notifier, ActiveSupport::Notifications::Fanout.new) do
CustomSubscriber.attach_to("rack_attack")
2.times { get '/', {}, 'REMOTE_ADDR' => '1.2.3.4' }
end
end
it 'should instrument without error' do
_(last_response.status).must_equal 429
assert_equal 1, CustomSubscriber.notification_count
end
end
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/spec/spec_helper.rb | spec/spec_helper.rb | # frozen_string_literal: true
require "bundler/setup"
require "logger"
require "minitest/autorun"
require "minitest/pride"
require "rack/test"
require "active_support"
require "rack/attack"
if RUBY_ENGINE == "ruby"
require "byebug"
end
def safe_require(name)
require name
rescue LoadError
nil
end
safe_require "connection_pool"
safe_require "dalli"
safe_require "rails"
safe_require "redis"
safe_require "redis-store"
class Minitest::Spec
include Rack::Test::Methods
before do
if Object.const_defined?(:Rails) && Rails.respond_to?(:cache) && Rails.cache.respond_to?(:clear)
Rails.cache.clear
end
end
after do
Rack::Attack.clear_configuration
Rack::Attack.instance_variable_set(:@cache, nil)
end
def app
Rack::Builder.new do
# Use Rack::Lint to test that rack-attack is complying with the rack spec
use Rack::Lint
# Intentionally added twice to test idempotence property
use Rack::Attack
use Rack::Attack
use Rack::Lint
run lambda { |_env| [200, {}, ['Hello World']] }
end.to_app
end
def self.it_allows_ok_requests
it "must allow ok requests" do
get '/', {}, 'REMOTE_ADDR' => '127.0.0.1'
_(last_response.status).must_equal 200
_(last_response.body).must_equal 'Hello World'
end
end
end
class Minitest::SharedExamples < Module
include Minitest::Spec::DSL
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/spec/support/freeze_time_helper.rb | spec/support/freeze_time_helper.rb | # frozen_string_literal: true
require "timecop"
class Minitest::Spec
def within_same_period(&block)
Timecop.freeze(&block)
end
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/spec/support/cache_store_helper.rb | spec/support/cache_store_helper.rb | # frozen_string_literal: true
require_relative 'freeze_time_helper'
class Minitest::Spec
def self.it_works_for_cache_backed_features(options)
fetch_from_store = options.fetch(:fetch_from_store)
it "works for throttle" do
Rack::Attack.throttle("by ip", limit: 1, period: 60) do |request|
request.ip
end
within_same_period do
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 200, last_response.status
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 429, last_response.status
end
end
it "works for fail2ban" do
Rack::Attack.blocklist("fail2ban pentesters") do |request|
Rack::Attack::Fail2Ban.filter(request.ip, maxretry: 2, findtime: 30, bantime: 60) do
request.path.include?("private-place")
end
end
within_same_period do
get "/"
assert_equal 200, last_response.status
get "/private-place"
assert_equal 403, last_response.status
get "/private-place"
assert_equal 403, last_response.status
get "/"
assert_equal 403, last_response.status
end
end
it "works for allow2ban" do
Rack::Attack.blocklist("allow2ban pentesters") do |request|
Rack::Attack::Allow2Ban.filter(request.ip, maxretry: 2, findtime: 30, bantime: 60) do
request.path.include?("scarce-resource")
end
end
within_same_period do
get "/"
assert_equal 200, last_response.status
get "/scarce-resource"
assert_equal 200, last_response.status
get "/scarce-resource"
assert_equal 200, last_response.status
get "/scarce-resource"
assert_equal 403, last_response.status
get "/"
assert_equal 403, last_response.status
end
end
it "doesn't leak keys" do
Rack::Attack.throttle("by ip", limit: 1, period: 1) do |request|
request.ip
end
key = nil
within_same_period do
key = "rack::attack:#{Time.now.to_i}:by ip:1.2.3.4"
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
end
assert fetch_from_store.call(key)
sleep 2.1
assert_nil fetch_from_store.call(key)
end
end
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/spec/integration/offline_spec.rb | spec/integration/offline_spec.rb | # frozen_string_literal: true
require 'active_support/cache'
require_relative '../spec_helper'
OfflineExamples = Minitest::SharedExamples.new do
it 'should write' do
@cache.write('cache-test-key', 'foobar', 1)
end
it 'should read' do
@cache.read('cache-test-key')
end
it 'should count' do
@cache.count('cache-test-key', 1)
end
it 'should delete' do
@cache.delete('cache-test-key')
end
end
if defined?(Redis) && defined?(ActiveSupport::Cache::RedisCacheStore) && Redis::VERSION >= '4'
describe 'when Redis is offline' do
include OfflineExamples
before do
@cache = Rack::Attack::Cache.new
# Use presumably unused port for Redis client
@cache.store = ActiveSupport::Cache::RedisCacheStore.new(host: '127.0.0.1', port: 3333)
end
end
end
if defined?(::Dalli)
describe 'when Memcached is offline' do
include OfflineExamples
before do
Dalli.logger.level = Logger::FATAL
@cache = Rack::Attack::Cache.new
@cache.store = Dalli::Client.new('127.0.0.1:22122')
end
after do
Dalli.logger.level = Logger::INFO
end
end
end
if defined?(::Dalli) && defined?(::ActiveSupport::Cache::MemCacheStore)
describe 'when Memcached is offline' do
include OfflineExamples
before do
Dalli.logger.level = Logger::FATAL
@cache = Rack::Attack::Cache.new
@cache.store = ActiveSupport::Cache::MemCacheStore.new('127.0.0.1:22122')
end
after do
Dalli.logger.level = Logger::INFO
end
end
end
if defined?(Redis)
describe 'when Redis is offline' do
include OfflineExamples
before do
@cache = Rack::Attack::Cache.new
# Use presumably unused port for Redis client
@cache.store = Redis.new(host: '127.0.0.1', port: 3333)
end
end
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/spec/acceptance/cache_store_config_with_rails_spec.rb | spec/acceptance/cache_store_config_with_rails_spec.rb | # frozen_string_literal: true
require_relative "../spec_helper"
require "minitest/stub_const"
require "ostruct"
describe "Cache store config with Rails" do
before do
Rack::Attack.throttle("by ip", limit: 1, period: 60) do |request|
request.ip
end
end
unless defined?(Rails)
it "fails when Rails.cache is not set" do
Object.stub_const(:Rails, OpenStruct.new(cache: nil)) do
assert_raises(Rack::Attack::MissingStoreError) do
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
end
end
end
end
it "works when Rails.cache is set" do
Object.stub_const(:Rails, OpenStruct.new(cache: ActiveSupport::Cache::MemoryStore.new)) do
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 200, last_response.status
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 429, last_response.status
end
end
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/spec/acceptance/blocking_subnet_spec.rb | spec/acceptance/blocking_subnet_spec.rb | # frozen_string_literal: true
require_relative "../spec_helper"
describe "Blocking an IP subnet" do
let(:notifications) { [] }
before do
Rack::Attack.blocklist_ip("1.2.3.4/31")
end
it "forbids request if IP is inside the subnet" do
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 403, last_response.status
end
it "forbids request for another IP in the subnet" do
get "/", {}, "REMOTE_ADDR" => "1.2.3.5"
assert_equal 403, last_response.status
end
it "succeeds if IP is outside the subnet" do
get "/", {}, "REMOTE_ADDR" => "1.2.3.6"
assert_equal 200, last_response.status
end
it "notifies when the request is blocked" do
ActiveSupport::Notifications.subscribe("blocklist.rack_attack") do |_name, _start, _finish, _id, payload|
notifications.push(payload)
end
get "/", {}, "REMOTE_ADDR" => "5.6.7.8"
assert notifications.empty?
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 1, notifications.size
notification = notifications.pop
assert_equal :blocklist, notification[:request].env["rack.attack.match_type"]
end
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/spec/acceptance/throttling_spec.rb | spec/acceptance/throttling_spec.rb | # frozen_string_literal: true
require_relative "../spec_helper"
require "timecop"
describe "#throttle" do
let(:notifications) { [] }
before do
Rack::Attack.cache.store = ActiveSupport::Cache::MemoryStore.new
end
it "allows one request per minute by IP" do
Rack::Attack.throttle("by ip", limit: 1, period: 60) do |request|
request.ip
end
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 200, last_response.status
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 429, last_response.status
assert_nil last_response.headers["Retry-After"]
assert_equal "Retry later\n", last_response.body
get "/", {}, "REMOTE_ADDR" => "5.6.7.8"
assert_equal 200, last_response.status
Timecop.travel(60) do
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 200, last_response.status
end
end
it "returns correct Retry-After header if enabled" do
Rack::Attack.throttled_response_retry_after_header = true
Rack::Attack.throttle("by ip", limit: 1, period: 60) do |request|
request.ip
end
Timecop.freeze(Time.at(0)) do
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 200, last_response.status
end
Timecop.freeze(Time.at(25)) do
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal "35", last_response.headers["Retry-After"]
end
end
it "supports limit to be dynamic" do
# Could be used to have different rate limits for authorized
# vs general requests
limit_proc = lambda do |request|
if request.env["X-APIKey"] == "private-secret"
2
else
1
end
end
Rack::Attack.throttle("by ip", limit: limit_proc, period: 60) do |request|
request.ip
end
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 200, last_response.status
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 429, last_response.status
get "/", {}, "REMOTE_ADDR" => "5.6.7.8", "X-APIKey" => "private-secret"
assert_equal 200, last_response.status
get "/", {}, "REMOTE_ADDR" => "5.6.7.8", "X-APIKey" => "private-secret"
assert_equal 200, last_response.status
get "/", {}, "REMOTE_ADDR" => "5.6.7.8", "X-APIKey" => "private-secret"
assert_equal 429, last_response.status
end
it "supports period to be dynamic" do
# Could be used to have different rate limits for authorized
# vs general requests
period_proc = lambda do |request|
if request.env["X-APIKey"] == "private-secret"
10
else
30
end
end
Rack::Attack.throttle("by ip", limit: 1, period: period_proc) do |request|
request.ip
end
# Using Time#at to align to start/end of periods exactly
# to achieve consistenty in different test runs
Timecop.travel(Time.at(0)) do
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 200, last_response.status
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 429, last_response.status
end
Timecop.travel(Time.at(10)) do
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 429, last_response.status
end
Timecop.travel(Time.at(30)) do
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 200, last_response.status
end
Timecop.travel(Time.at(0)) do
get "/", {}, "REMOTE_ADDR" => "5.6.7.8", "X-APIKey" => "private-secret"
assert_equal 200, last_response.status
get "/", {}, "REMOTE_ADDR" => "5.6.7.8", "X-APIKey" => "private-secret"
assert_equal 429, last_response.status
end
Timecop.travel(Time.at(10)) do
get "/", {}, "REMOTE_ADDR" => "5.6.7.8", "X-APIKey" => "private-secret"
assert_equal 200, last_response.status
end
end
it "notifies when the request is throttled" do
Rack::Attack.throttle("by ip", limit: 1, period: 60) do |request|
request.ip
end
ActiveSupport::Notifications.subscribe("throttle.rack_attack") do |_name, _start, _finish, _id, payload|
notifications.push(payload)
end
get "/", {}, "REMOTE_ADDR" => "5.6.7.8"
assert_equal 200, last_response.status
assert notifications.empty?
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 200, last_response.status
assert notifications.empty?
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 429, last_response.status
assert_equal 1, notifications.size
notification = notifications.pop
assert_equal "by ip", notification[:request].env["rack.attack.matched"]
assert_equal :throttle, notification[:request].env["rack.attack.match_type"]
assert_equal 60, notification[:request].env["rack.attack.match_data"][:period]
assert_equal 1, notification[:request].env["rack.attack.match_data"][:limit]
assert_equal 2, notification[:request].env["rack.attack.match_data"][:count]
assert_equal "1.2.3.4", notification[:request].env["rack.attack.match_discriminator"]
end
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/spec/acceptance/cache_store_config_for_throttle_spec.rb | spec/acceptance/cache_store_config_for_throttle_spec.rb | # frozen_string_literal: true
require_relative "../spec_helper"
describe "Cache store config when throttling without Rails" do
before do
Rack::Attack.throttle("by ip", limit: 1, period: 60) do |request|
request.ip
end
end
unless defined?(Rails)
it "gives semantic error if no store was configured" do
assert_raises(Rack::Attack::MissingStoreError) do
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
end
end
end
it "gives semantic error if incompatible store was configured" do
Rack::Attack.cache.store = Object.new
assert_raises(Rack::Attack::MisconfiguredStoreError) do
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
end
end
it "works with any object that responds to #increment" do
basic_store_class = Class.new do
attr_accessor :counts
def initialize
@counts = {}
end
def increment(key, _count, _options)
@counts[key] ||= 0
@counts[key] += 1
end
end
Rack::Attack.cache.store = basic_store_class.new
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 200, last_response.status
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 429, last_response.status
end
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/spec/acceptance/track_spec.rb | spec/acceptance/track_spec.rb | # frozen_string_literal: true
require_relative "../spec_helper"
describe "#track" do
let(:notifications) { [] }
it "notifies when track block returns true" do
Rack::Attack.track("ip 1.2.3.4") do |request|
request.ip == "1.2.3.4"
end
ActiveSupport::Notifications.subscribe("track.rack_attack") do |_name, _start, _finish, _id, payload|
notifications.push(payload)
end
get "/", {}, "REMOTE_ADDR" => "5.6.7.8"
assert notifications.empty?
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 1, notifications.size
notification = notifications.pop
assert_equal "ip 1.2.3.4", notification[:request].env["rack.attack.matched"]
assert_equal :track, notification[:request].env["rack.attack.match_type"]
end
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/spec/acceptance/blocking_ip_spec.rb | spec/acceptance/blocking_ip_spec.rb | # frozen_string_literal: true
require_relative "../spec_helper"
describe "Blocking an IP" do
let(:notifications) { [] }
before do
Rack::Attack.blocklist_ip("1.2.3.4")
end
it "forbids request if IP matches" do
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 403, last_response.status
end
it "succeeds if IP doesn't match" do
get "/", {}, "REMOTE_ADDR" => "5.6.7.8"
assert_equal 200, last_response.status
end
it "succeeds if IP is missing" do
get "/", {}, "REMOTE_ADDR" => ""
assert_equal 200, last_response.status
end
it "notifies when the request is blocked" do
ActiveSupport::Notifications.subscribe("blocklist.rack_attack") do |_name, _start, _finish, _id, payload|
notifications.push(payload)
end
get "/", {}, "REMOTE_ADDR" => "5.6.7.8"
assert notifications.empty?
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 1, notifications.size
notification = notifications.pop
assert_equal :blocklist, notification[:request].env["rack.attack.match_type"]
end
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/spec/acceptance/cache_store_config_for_fail2ban_spec.rb | spec/acceptance/cache_store_config_for_fail2ban_spec.rb | # frozen_string_literal: true
require_relative "../spec_helper"
require "minitest/stub_const"
describe "Cache store config when using fail2ban" do
before do
Rack::Attack.blocklist("fail2ban pentesters") do |request|
Rack::Attack::Fail2Ban.filter(request.ip, maxretry: 2, findtime: 30, bantime: 60) do
request.path.include?("private-place")
end
end
end
unless defined?(Rails)
it "gives semantic error if no store was configured" do
assert_raises(Rack::Attack::MissingStoreError) do
get "/private-place"
end
end
end
it "gives semantic error if store is missing #read method" do
raised_exception = nil
fake_store_class = Class.new do
def write(key, value); end
def increment(key, count, options = {}); end
end
Object.stub_const(:FakeStore, fake_store_class) do
Rack::Attack.cache.store = FakeStore.new
raised_exception = assert_raises(Rack::Attack::MisconfiguredStoreError) do
get "/private-place"
end
end
assert_equal "Configured store FakeStore doesn't respond to #read method", raised_exception.message
end
it "gives semantic error if store is missing #write method" do
raised_exception = nil
fake_store_class = Class.new do
def read(key); end
def increment(key, count, options = {}); end
end
Object.stub_const(:FakeStore, fake_store_class) do
Rack::Attack.cache.store = FakeStore.new
raised_exception = assert_raises(Rack::Attack::MisconfiguredStoreError) do
get "/private-place"
end
end
assert_equal "Configured store FakeStore doesn't respond to #write method", raised_exception.message
end
it "gives semantic error if store is missing #increment method" do
raised_exception = nil
fake_store_class = Class.new do
def read(key); end
def write(key, value); end
end
Object.stub_const(:FakeStore, fake_store_class) do
Rack::Attack.cache.store = FakeStore.new
raised_exception = assert_raises(Rack::Attack::MisconfiguredStoreError) do
get "/private-place"
end
end
assert_equal "Configured store FakeStore doesn't respond to #increment method", raised_exception.message
end
it "works with any object that responds to #read, #write and #increment" do
fake_store_class = Class.new do
attr_accessor :backend
def initialize
@backend = {}
end
def read(key)
@backend[key]
end
def write(key, value, _options = {})
@backend[key] = value
end
def increment(key, _count, _options = {})
@backend[key] ||= 0
@backend[key] += 1
end
end
Rack::Attack.cache.store = fake_store_class.new
get "/"
assert_equal 200, last_response.status
get "/private-place"
assert_equal 403, last_response.status
get "/private-place"
assert_equal 403, last_response.status
get "/"
assert_equal 403, last_response.status
end
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/spec/acceptance/extending_request_object_spec.rb | spec/acceptance/extending_request_object_spec.rb | # frozen_string_literal: true
require_relative "../spec_helper"
describe "Extending the request object" do
before do
Rack::Attack::Request.define_method :authorized? do
env["APIKey"] == "private-secret"
end
Rack::Attack.blocklist("unauthorized requests") do |request|
!request.authorized?
end
end
# We don't want the extension to leak to other test cases
after do
Rack::Attack::Request.undef_method :authorized?
end
it "forbids request if blocklist condition is true" do
get "/"
assert_equal 403, last_response.status
end
it "succeeds if blocklist condition is false" do
get "/", {}, "APIKey" => "private-secret"
assert_equal 200, last_response.status
end
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/spec/acceptance/allow2ban_spec.rb | spec/acceptance/allow2ban_spec.rb | # frozen_string_literal: true
require_relative "../spec_helper"
require "timecop"
describe "allow2ban" do
before do
Rack::Attack.cache.store = ActiveSupport::Cache::MemoryStore.new
Rack::Attack.blocklist("allow2ban pentesters") do |request|
Rack::Attack::Allow2Ban.filter(request.ip, maxretry: 2, findtime: 30, bantime: 60) do
request.path.include?("scarce-resource")
end
end
end
it "returns OK for many requests that doesn't match the filter" do
get "/"
assert_equal 200, last_response.status
get "/"
assert_equal 200, last_response.status
end
it "returns OK for first request that matches the filter" do
get "/scarce-resource"
assert_equal 200, last_response.status
end
it "forbids all access after reaching maxretry limit" do
get "/scarce-resource"
assert_equal 200, last_response.status
get "/scarce-resource"
assert_equal 200, last_response.status
get "/scarce-resource"
assert_equal 403, last_response.status
get "/"
assert_equal 403, last_response.status
end
it "restores access after bantime elapsed" do
get "/scarce-resource"
assert_equal 200, last_response.status
get "/scarce-resource"
assert_equal 200, last_response.status
get "/"
assert_equal 403, last_response.status
Timecop.travel(60) do
get "/"
assert_equal 200, last_response.status
end
end
it "does not forbid all access if maxrety condition is met but not within the findtime timespan" do
get "/scarce-resource"
assert_equal 200, last_response.status
Timecop.travel(31) do
get "/scarce-resource"
assert_equal 200, last_response.status
get "/"
assert_equal 200, last_response.status
end
end
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/spec/acceptance/fail2ban_spec.rb | spec/acceptance/fail2ban_spec.rb | # frozen_string_literal: true
require_relative "../spec_helper"
require "timecop"
describe "fail2ban" do
let(:notifications) { [] }
before do
Rack::Attack.cache.store = ActiveSupport::Cache::MemoryStore.new
Rack::Attack.blocklist("fail2ban pentesters") do |request|
Rack::Attack::Fail2Ban.filter(request.ip, maxretry: 2, findtime: 30, bantime: 60) do
request.path.include?("private-place")
end
end
end
it "returns OK for many requests to non filtered path" do
get "/"
assert_equal 200, last_response.status
get "/"
assert_equal 200, last_response.status
end
it "forbids access to private path" do
get "/private-place"
assert_equal 403, last_response.status
end
it "returns OK for non filtered path if yet not reached maxretry limit" do
get "/private-place"
assert_equal 403, last_response.status
get "/"
assert_equal 200, last_response.status
end
it "forbids all access after reaching maxretry limit" do
get "/private-place"
assert_equal 403, last_response.status
get "/private-place"
assert_equal 403, last_response.status
get "/"
assert_equal 403, last_response.status
end
it "restores access after bantime elapsed" do
get "/private-place"
assert_equal 403, last_response.status
get "/private-place"
assert_equal 403, last_response.status
get "/"
assert_equal 403, last_response.status
Timecop.travel(60) do
get "/"
assert_equal 200, last_response.status
end
end
it "does not forbid all access if maxrety condition is met but not within the findtime timespan" do
get "/private-place"
assert_equal 403, last_response.status
Timecop.travel(31) do
get "/private-place"
assert_equal 403, last_response.status
get "/"
assert_equal 200, last_response.status
end
end
it "notifies when the request is blocked" do
ActiveSupport::Notifications.subscribe("rack.attack") do |_name, _start, _finish, _id, payload|
notifications.push(payload)
end
get "/"
assert_equal 200, last_response.status
assert notifications.empty?
get "/private-place"
assert_equal 403, last_response.status
assert_equal 1, notifications.size
notification = notifications.pop
assert_equal 'fail2ban pentesters', notification[:request].env["rack.attack.matched"]
assert_equal :blocklist, notification[:request].env["rack.attack.match_type"]
get "/"
assert_equal 200, last_response.status
assert notifications.empty?
get "/private-place"
assert_equal 403, last_response.status
assert_equal 1, notifications.size
notification = notifications.pop
assert_equal 'fail2ban pentesters', notification[:request].env["rack.attack.matched"]
assert_equal :blocklist, notification[:request].env["rack.attack.match_type"]
get "/"
assert_equal 403, last_response.status
assert_equal 1, notifications.size
notification = notifications.pop
assert_equal 'fail2ban pentesters', notification[:request].env["rack.attack.matched"]
assert_equal :blocklist, notification[:request].env["rack.attack.match_type"]
end
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/spec/acceptance/safelisting_ip_spec.rb | spec/acceptance/safelisting_ip_spec.rb | # frozen_string_literal: true
require_relative "../spec_helper"
describe "Safelist an IP" do
let(:notifications) { [] }
before do
Rack::Attack.blocklist("admin") do |request|
request.path == "/admin"
end
Rack::Attack.safelist_ip("5.6.7.8")
end
it "forbids request if blocklist condition is true and safelist is false" do
get "/admin", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 403, last_response.status
end
it "forbids request if blocklist condition is true and safelist is false (missing IP)" do
get "/admin", {}, "REMOTE_ADDR" => ""
assert_equal 403, last_response.status
end
it "succeeds if blocklist condition is false and safelist is false" do
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 200, last_response.status
end
it "succeeds request if blocklist condition is false and safelist is true" do
get "/", {}, "REMOTE_ADDR" => "5.6.7.8"
assert_equal 200, last_response.status
end
it "succeeds request if both blocklist and safelist conditions are true" do
get "/admin", {}, "REMOTE_ADDR" => "5.6.7.8"
assert_equal 200, last_response.status
end
it "notifies when the request is safe" do
ActiveSupport::Notifications.subscribe("safelist.rack_attack") do |_name, _start, _finish, _id, payload|
notifications.push(payload)
end
get "/admin", {}, "REMOTE_ADDR" => "5.6.7.8"
assert_equal 200, last_response.status
assert_equal 1, notifications.size
notification = notifications.pop
assert_equal :safelist, notification[:request].env["rack.attack.match_type"]
end
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/spec/acceptance/cache_store_config_for_allow2ban_spec.rb | spec/acceptance/cache_store_config_for_allow2ban_spec.rb | # frozen_string_literal: true
require_relative "../spec_helper"
require "minitest/stub_const"
describe "Cache store config when using allow2ban" do
before do
Rack::Attack.blocklist("allow2ban pentesters") do |request|
Rack::Attack::Allow2Ban.filter(request.ip, maxretry: 2, findtime: 30, bantime: 60) do
request.path.include?("scarce-resource")
end
end
end
unless defined?(Rails)
it "gives semantic error if no store was configured" do
assert_raises(Rack::Attack::MissingStoreError) do
get "/scarce-resource"
end
end
end
it "gives semantic error if store is missing #read method" do
raised_exception = nil
fake_store_class = Class.new do
def write(key, value); end
def increment(key, count, options = {}); end
end
Object.stub_const(:FakeStore, fake_store_class) do
Rack::Attack.cache.store = FakeStore.new
raised_exception = assert_raises(Rack::Attack::MisconfiguredStoreError) do
get "/scarce-resource"
end
end
assert_equal "Configured store FakeStore doesn't respond to #read method", raised_exception.message
end
it "gives semantic error if store is missing #write method" do
raised_exception = nil
fake_store_class = Class.new do
def read(key); end
def increment(key, count, options = {}); end
end
Object.stub_const(:FakeStore, fake_store_class) do
Rack::Attack.cache.store = FakeStore.new
raised_exception = assert_raises(Rack::Attack::MisconfiguredStoreError) do
get "/scarce-resource"
end
end
assert_equal "Configured store FakeStore doesn't respond to #write method", raised_exception.message
end
it "gives semantic error if store is missing #increment method" do
raised_exception = nil
fake_store_class = Class.new do
def read(key); end
def write(key, value); end
end
Object.stub_const(:FakeStore, fake_store_class) do
Rack::Attack.cache.store = FakeStore.new
raised_exception = assert_raises(Rack::Attack::MisconfiguredStoreError) do
get "/scarce-resource"
end
end
assert_equal "Configured store FakeStore doesn't respond to #increment method", raised_exception.message
end
it "works with any object that responds to #read, #write and #increment" do
fake_store_class = Class.new do
attr_accessor :backend
def initialize
@backend = {}
end
def read(key)
@backend[key]
end
def write(key, value, _options = {})
@backend[key] = value
end
def increment(key, _count, _options = {})
@backend[key] ||= 0
@backend[key] += 1
end
end
Object.stub_const(:FakeStore, fake_store_class) do
Rack::Attack.cache.store = FakeStore.new
get "/"
assert_equal 200, last_response.status
get "/scarce-resource"
assert_equal 200, last_response.status
get "/scarce-resource"
assert_equal 200, last_response.status
get "/scarce-resource"
assert_equal 403, last_response.status
get "/"
assert_equal 403, last_response.status
end
end
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/spec/acceptance/rails_middleware_spec.rb | spec/acceptance/rails_middleware_spec.rb | # frozen_string_literal: true
require_relative "../spec_helper"
if defined?(Rails::Application)
describe "Middleware for Rails" do
before do
@app = Class.new(Rails::Application) do
config.eager_load = false
config.logger = Logger.new(nil) # avoid creating the log/ directory automatically
config.cache_store = :null_store # avoid creating tmp/ directory for cache
end
end
it "is used by default" do
@app.initialize!
assert @app.middleware.include?(Rack::Attack)
end
end
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/spec/acceptance/customizing_blocked_response_spec.rb | spec/acceptance/customizing_blocked_response_spec.rb | # frozen_string_literal: true
require_relative "../spec_helper"
describe "Customizing block responses" do
before do
Rack::Attack.blocklist("block 1.2.3.4") do |request|
request.ip == "1.2.3.4"
end
end
it "can be customized" do
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 403, last_response.status
Rack::Attack.blocklisted_responder = lambda do |_req|
[503, {}, ["Blocked"]]
end
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 503, last_response.status
assert_equal "Blocked", last_response.body
end
it "exposes match data" do
matched = nil
match_type = nil
Rack::Attack.blocklisted_responder = lambda do |req|
matched = req.env['rack.attack.matched']
match_type = req.env['rack.attack.match_type']
[503, {}, ["Blocked"]]
end
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal "block 1.2.3.4", matched
assert_equal :blocklist, match_type
end
it "supports old style" do
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 403, last_response.status
silence_warnings do
Rack::Attack.blocklisted_response = lambda do |_env|
[503, {}, ["Blocked"]]
end
end
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 503, last_response.status
assert_equal "Blocked", last_response.body
end
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/spec/acceptance/safelisting_spec.rb | spec/acceptance/safelisting_spec.rb | # frozen_string_literal: true
require_relative "../spec_helper"
describe "#safelist" do
let(:notifications) { [] }
before do
Rack::Attack.blocklist do |request|
request.ip == "1.2.3.4"
end
Rack::Attack.safelist do |request|
request.path == "/safe_space"
end
end
it "forbids request if blocklist condition is true and safelist is false" do
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 403, last_response.status
end
it "succeeds if blocklist condition is false and safelist is false" do
get "/", {}, "REMOTE_ADDR" => "5.6.7.8"
assert_equal 200, last_response.status
end
it "succeeds request if blocklist condition is false and safelist is true" do
get "/safe_space", {}, "REMOTE_ADDR" => "5.6.7.8"
assert_equal 200, last_response.status
end
it "succeeds request if both blocklist and safelist conditions are true" do
get "/safe_space", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 200, last_response.status
end
it "notifies when the request is safe" do
ActiveSupport::Notifications.subscribe("rack.attack") do |_name, _start, _finish, _id, payload|
notifications.push(payload)
end
get "/safe_space", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 200, last_response.status
assert_equal 1, notifications.size
notification = notifications.pop
assert_nil notification[:request].env["rack.attack.matched"]
assert_equal :safelist, notification[:request].env["rack.attack.match_type"]
end
end
describe "#safelist with name" do
let(:notifications) { [] }
before do
Rack::Attack.blocklist("block 1.2.3.4") do |request|
request.ip == "1.2.3.4"
end
Rack::Attack.safelist("safe path") do |request|
request.path == "/safe_space"
end
end
it "forbids request if blocklist condition is true and safelist is false" do
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 403, last_response.status
end
it "succeeds if blocklist condition is false and safelist is false" do
get "/", {}, "REMOTE_ADDR" => "5.6.7.8"
assert_equal 200, last_response.status
end
it "succeeds request if blocklist condition is false and safelist is true" do
get "/safe_space", {}, "REMOTE_ADDR" => "5.6.7.8"
assert_equal 200, last_response.status
end
it "succeeds request if both blocklist and safelist conditions are true" do
get "/safe_space", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 200, last_response.status
end
it "notifies when the request is safe" do
ActiveSupport::Notifications.subscribe("safelist.rack_attack") do |_name, _start, _finish, _id, payload|
notifications.push(payload)
end
get "/safe_space", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 200, last_response.status
assert_equal 1, notifications.size
notification = notifications.pop
assert_equal "safe path", notification[:request].env["rack.attack.matched"]
assert_equal :safelist, notification[:request].env["rack.attack.match_type"]
end
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/spec/acceptance/blocking_spec.rb | spec/acceptance/blocking_spec.rb | # frozen_string_literal: true
require_relative "../spec_helper"
describe "#blocklist" do
let(:notifications) { [] }
before do
Rack::Attack.blocklist do |request|
request.ip == "1.2.3.4"
end
end
it "forbids request if blocklist condition is true" do
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 403, last_response.status
end
it "succeeds if blocklist condition is false" do
get "/", {}, "REMOTE_ADDR" => "5.6.7.8"
assert_equal 200, last_response.status
end
it "notifies when the request is blocked" do
ActiveSupport::Notifications.subscribe("rack.attack") do |_name, _start, _finish, _id, payload|
notifications.push(payload)
end
get "/", {}, "REMOTE_ADDR" => "5.6.7.8"
assert notifications.empty?
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 1, notifications.size
notification = notifications.pop
assert_nil notification[:request].env["rack.attack.matched"]
assert_equal :blocklist, notification[:request].env["rack.attack.match_type"]
end
end
describe "#blocklist with name" do
let(:notifications) { [] }
before do
Rack::Attack.blocklist("block 1.2.3.4") do |request|
request.ip == "1.2.3.4"
end
end
it "forbids request if blocklist condition is true" do
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 403, last_response.status
end
it "succeeds if blocklist condition is false" do
get "/", {}, "REMOTE_ADDR" => "5.6.7.8"
assert_equal 200, last_response.status
end
it "notifies when the request is blocked" do
ActiveSupport::Notifications.subscribe("blocklist.rack_attack") do |_name, _start, _finish, _id, payload|
notifications.push(payload)
end
get "/", {}, "REMOTE_ADDR" => "5.6.7.8"
assert notifications.empty?
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 1, notifications.size
notification = notifications.pop
assert_equal "block 1.2.3.4", notification[:request].env["rack.attack.matched"]
assert_equal :blocklist, notification[:request].env["rack.attack.match_type"]
end
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/spec/acceptance/customizing_throttled_response_spec.rb | spec/acceptance/customizing_throttled_response_spec.rb | # frozen_string_literal: true
require_relative "../spec_helper"
describe "Customizing throttled response" do
before do
Rack::Attack.cache.store = ActiveSupport::Cache::MemoryStore.new
Rack::Attack.throttle("by ip", limit: 1, period: 60) do |request|
request.ip
end
end
it "can be customized" do
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 200, last_response.status
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 429, last_response.status
Rack::Attack.throttled_responder = lambda do |_req|
[503, {}, ["Throttled"]]
end
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 503, last_response.status
assert_equal "Throttled", last_response.body
end
it "exposes match data" do
matched = nil
match_type = nil
match_data = nil
match_discriminator = nil
Rack::Attack.throttled_responder = lambda do |req|
matched = req.env['rack.attack.matched']
match_type = req.env['rack.attack.match_type']
match_data = req.env['rack.attack.match_data']
match_discriminator = req.env['rack.attack.match_discriminator']
[429, {}, ["Throttled"]]
end
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal "by ip", matched
assert_equal :throttle, match_type
assert_equal 60, match_data[:period]
assert_equal 1, match_data[:limit]
assert_equal 2, match_data[:count]
assert_equal "1.2.3.4", match_discriminator
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 3, match_data[:count]
end
it "supports old style" do
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 200, last_response.status
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 429, last_response.status
silence_warnings do
Rack::Attack.throttled_response = lambda do |_req|
[503, {}, ["Throttled"]]
end
end
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 503, last_response.status
assert_equal "Throttled", last_response.body
end
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/spec/acceptance/safelisting_subnet_spec.rb | spec/acceptance/safelisting_subnet_spec.rb | # frozen_string_literal: true
require_relative "../spec_helper"
describe "Safelisting an IP subnet" do
let(:notifications) { [] }
before do
Rack::Attack.blocklist("admin") do |request|
request.path == "/admin"
end
Rack::Attack.safelist_ip("5.6.0.0/16")
end
it "forbids request if blocklist condition is true and safelist is false" do
get "/admin", {}, "REMOTE_ADDR" => "5.7.0.0"
assert_equal 403, last_response.status
end
it "succeeds if blocklist condition is false and safelist is false" do
get "/", {}, "REMOTE_ADDR" => "5.7.0.0"
assert_equal 200, last_response.status
end
it "succeeds request if blocklist condition is false and safelist is true" do
get "/", {}, "REMOTE_ADDR" => "5.6.0.0"
assert_equal 200, last_response.status
end
it "succeeds request if both blocklist and safelist conditions are true" do
get "/admin", {}, "REMOTE_ADDR" => "5.6.255.255"
assert_equal 200, last_response.status
end
it "notifies when the request is safe" do
ActiveSupport::Notifications.subscribe("safelist.rack_attack") do |_name, _start, _finish, _id, payload|
notifications.push(payload)
end
get "/admin", {}, "REMOTE_ADDR" => "5.6.0.0"
assert_equal 200, last_response.status
assert_equal 1, notifications.size
notification = notifications.pop
assert_equal :safelist, notification[:request].env["rack.attack.match_type"]
end
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/spec/acceptance/track_throttle_spec.rb | spec/acceptance/track_throttle_spec.rb | # frozen_string_literal: true
require_relative "../spec_helper"
require "timecop"
describe "#track with throttle-ish options" do
let(:notifications) { [] }
it "notifies when throttle goes over the limit without actually throttling requests" do
Rack::Attack.cache.store = ActiveSupport::Cache::MemoryStore.new
Rack::Attack.track("by ip", limit: 1, period: 60) do |request|
request.ip
end
ActiveSupport::Notifications.subscribe("track.rack_attack") do |_name, _start, _finish, _id, payload|
notifications.push(payload)
end
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert notifications.empty?
assert_equal 200, last_response.status
get "/", {}, "REMOTE_ADDR" => "5.6.7.8"
assert notifications.empty?
assert_equal 200, last_response.status
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 1, notifications.size
notification = notifications.pop
assert_equal "by ip", notification[:request].env["rack.attack.matched"]
assert_equal :track, notification[:request].env["rack.attack.match_type"]
assert_equal 200, last_response.status
Timecop.travel(60) do
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert notifications.empty?
assert_equal 200, last_response.status
end
end
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/spec/acceptance/stores/active_support_mem_cache_store_spec.rb | spec/acceptance/stores/active_support_mem_cache_store_spec.rb | # frozen_string_literal: true
require_relative "../../spec_helper"
if defined?(::Dalli)
require_relative "../../support/cache_store_helper"
describe "ActiveSupport::Cache::MemCacheStore as a cache backend" do
before do
Rack::Attack.cache.store = if ActiveSupport.gem_version >= Gem::Version.new("7.2.0")
ActiveSupport::Cache::MemCacheStore.new(pool: true)
else
ActiveSupport::Cache::MemCacheStore.new(pool_size: 2)
end
end
after do
Rack::Attack.cache.store.clear
end
it_works_for_cache_backed_features(fetch_from_store: ->(key) { Rack::Attack.cache.store.read(key) })
end
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/spec/acceptance/stores/active_support_redis_cache_store_spec.rb | spec/acceptance/stores/active_support_redis_cache_store_spec.rb | # frozen_string_literal: true
require_relative "../../spec_helper"
should_run =
defined?(::Redis) &&
Gem::Version.new(::Redis::VERSION) >= Gem::Version.new("4") &&
defined?(::ActiveSupport::Cache::RedisCacheStore)
if should_run
require_relative "../../support/cache_store_helper"
describe "ActiveSupport::Cache::RedisCacheStore as a cache backend" do
before do
Rack::Attack.cache.store = if ActiveSupport.gem_version >= Gem::Version.new("7.2.0")
ActiveSupport::Cache::RedisCacheStore.new(pool: true)
else
ActiveSupport::Cache::RedisCacheStore.new(pool_size: 2)
end
end
after do
Rack::Attack.cache.store.clear
end
it_works_for_cache_backed_features(fetch_from_store: ->(key) { Rack::Attack.cache.store.read(key) })
end
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/spec/acceptance/stores/redis_spec.rb | spec/acceptance/stores/redis_spec.rb | # frozen_string_literal: true
require_relative "../../spec_helper"
if defined?(::Redis)
require_relative "../../support/cache_store_helper"
describe "Plain redis as a cache backend" do
before do
Rack::Attack.cache.store = Redis.new
end
after do
Rack::Attack.cache.store.flushdb
end
it_works_for_cache_backed_features(fetch_from_store: ->(key) { Rack::Attack.cache.store.get(key) })
end
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/spec/acceptance/stores/redis_store_spec.rb | spec/acceptance/stores/redis_store_spec.rb | # frozen_string_literal: true
require_relative "../../spec_helper"
require_relative "../../support/cache_store_helper"
if defined?(::Redis::Store)
describe "Redis::Store as a cache backend" do
before do
Rack::Attack.cache.store = ::Redis::Store.new
end
after do
Rack::Attack.cache.store.flushdb
end
it_works_for_cache_backed_features(fetch_from_store: ->(key) { Rack::Attack.cache.store.read(key) })
end
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/spec/acceptance/stores/dalli_client_spec.rb | spec/acceptance/stores/dalli_client_spec.rb | # frozen_string_literal: true
require_relative "../../spec_helper"
if defined?(::Dalli)
require_relative "../../support/cache_store_helper"
require "dalli"
describe "Dalli::Client as a cache backend" do
before do
Rack::Attack.cache.store = Dalli::Client.new
end
after do
Rack::Attack.cache.store.flush_all
end
it_works_for_cache_backed_features(fetch_from_store: ->(key) { Rack::Attack.cache.store.fetch(key) })
end
describe "ConnectionPool with Dalli::Client as a cache backend" do
before do
Rack::Attack.cache.store = ConnectionPool.new { Dalli::Client.new }
end
after do
Rack::Attack.cache.store.with { |client| client.flush_all }
end
it_works_for_cache_backed_features(
fetch_from_store: ->(key) { Rack::Attack.cache.store.with { |client| client.fetch(key) } }
)
end
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/spec/acceptance/stores/active_support_memory_store_spec.rb | spec/acceptance/stores/active_support_memory_store_spec.rb | # frozen_string_literal: true
require_relative "../../spec_helper"
require_relative "../../support/cache_store_helper"
describe "ActiveSupport::Cache::MemoryStore as a cache backend" do
before do
Rack::Attack.cache.store = ActiveSupport::Cache::MemoryStore.new
end
after do
Rack::Attack.cache.store.clear
end
it_works_for_cache_backed_features(fetch_from_store: ->(key) { Rack::Attack.cache.store.fetch(key) })
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/examples/instrumentation.rb | examples/instrumentation.rb | ActiveSupport::Notifications.subscribe(/rack_attack/) do |name, start, finish, request_id, payload|
puts payload[:request].inspect
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/examples/rack_attack.rb | examples/rack_attack.rb | # frozen_string_literal: true
# NB: `req` is a Rack::Request object (basically an env hash with friendly accessor methods)
# Throttle 10 requests/ip/second
# NB: return value of block is key name for counter
# falsy values bypass throttling
Rack::Attack.throttle("req/ip", limit: 10, period: 1) { |req| req.ip }
# Throttle attempts to a particular path. 2 POSTs to /login per second per IP
Rack::Attack.throttle "logins/ip", limit: 2, period: 1 do |req|
req.post? && req.path == "/login" && req.ip
end
# Throttle login attempts per email, 10/minute/email
# Normalize the email, using the same logic as your authentication process, to
# protect against rate limit bypasses.
Rack::Attack.throttle "logins/email", limit: 2, period: 60 do |req|
req.post? && req.path == "/login" && req.params['email'].to_s.downcase.gsub(/\s+/, "")
end
# blocklist bad IPs from accessing admin pages
Rack::Attack.blocklist "bad_ips from logging in" do |req|
req.path =~ /^\/admin/ && bad_ips.include?(req.ip)
end
# safelist a User-Agent
Rack::Attack.safelist 'internal user agent' do |req|
req.user_agent == 'InternalUserAgent'
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/lib/rack/attack.rb | lib/rack/attack.rb | # frozen_string_literal: true
require 'rack'
require 'forwardable'
require 'rack/attack/cache'
require 'rack/attack/configuration'
require 'rack/attack/path_normalizer'
require 'rack/attack/request'
require 'rack/attack/store_proxy/dalli_proxy'
require 'rack/attack/store_proxy/mem_cache_store_proxy'
require 'rack/attack/store_proxy/redis_proxy'
require 'rack/attack/store_proxy/redis_store_proxy'
require 'rack/attack/store_proxy/redis_cache_store_proxy'
require 'rack/attack/railtie' if defined?(::Rails)
module Rack
class Attack
class Error < StandardError; end
class MisconfiguredStoreError < Error; end
class MissingStoreError < Error; end
class IncompatibleStoreError < Error; end
autoload :Check, 'rack/attack/check'
autoload :Throttle, 'rack/attack/throttle'
autoload :Safelist, 'rack/attack/safelist'
autoload :Blocklist, 'rack/attack/blocklist'
autoload :Track, 'rack/attack/track'
autoload :Fail2Ban, 'rack/attack/fail2ban'
autoload :Allow2Ban, 'rack/attack/allow2ban'
class << self
attr_accessor :enabled, :notifier, :throttle_discriminator_normalizer
attr_reader :configuration
def instrument(request)
if notifier
event_type = request.env["rack.attack.match_type"]
notifier.instrument("#{event_type}.rack_attack", request: request)
# Deprecated: Keeping just for backwards compatibility
notifier.instrument("rack.attack", request: request)
end
end
def cache
@cache ||= Cache.new
end
def clear!
warn "[DEPRECATION] Rack::Attack.clear! is deprecated. Please use Rack::Attack.clear_configuration instead"
@configuration.clear_configuration
end
def reset!
cache.reset!
end
extend Forwardable
def_delegators(
:@configuration,
:safelist,
:blocklist,
:blocklist_ip,
:safelist_ip,
:throttle,
:track,
:throttled_responder,
:throttled_responder=,
:blocklisted_responder,
:blocklisted_responder=,
:blocklisted_response,
:blocklisted_response=,
:throttled_response,
:throttled_response=,
:throttled_response_retry_after_header,
:throttled_response_retry_after_header=,
:clear_configuration,
:safelists,
:blocklists,
:throttles,
:tracks
)
end
# Set defaults
@enabled = true
@notifier = ActiveSupport::Notifications if defined?(ActiveSupport::Notifications)
@throttle_discriminator_normalizer = lambda do |discriminator|
discriminator.to_s.strip.downcase
end
@configuration = Configuration.new
attr_reader :configuration
def initialize(app)
@app = app
@configuration = self.class.configuration
end
def call(env)
return @app.call(env) if !self.class.enabled || env["rack.attack.called"]
env["rack.attack.called"] = true
env['PATH_INFO'] = PathNormalizer.normalize_path(env['PATH_INFO'])
request = Rack::Attack::Request.new(env)
if configuration.safelisted?(request)
@app.call(env)
elsif configuration.blocklisted?(request)
# Deprecated: Keeping blocklisted_response for backwards compatibility
if configuration.blocklisted_response
configuration.blocklisted_response.call(env)
else
configuration.blocklisted_responder.call(request)
end
elsif configuration.throttled?(request)
# Deprecated: Keeping throttled_response for backwards compatibility
if configuration.throttled_response
configuration.throttled_response.call(env)
else
configuration.throttled_responder.call(request)
end
else
configuration.tracked?(request)
@app.call(env)
end
end
end
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/lib/rack/attack/version.rb | lib/rack/attack/version.rb | # frozen_string_literal: true
module Rack
class Attack
VERSION = '6.8.0'
end
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/lib/rack/attack/allow2ban.rb | lib/rack/attack/allow2ban.rb | # frozen_string_literal: true
module Rack
class Attack
class Allow2Ban < Fail2Ban
class << self
protected
def key_prefix
'allow2ban'
end
# everything is the same here except we only return true
# (blocking the request) if they have tripped the limit.
def fail!(discriminator, bantime, findtime, maxretry)
count = cache.count("#{key_prefix}:count:#{discriminator}", findtime)
if count >= maxretry
ban!(discriminator, bantime)
end
# we may not block them this time, but they're banned for next time
false
end
end
end
end
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/lib/rack/attack/track.rb | lib/rack/attack/track.rb | # frozen_string_literal: true
module Rack
class Attack
class Track
attr_reader :filter
def initialize(name, options = {}, &block)
options[:type] = :track
@filter =
if options[:limit] && options[:period]
Throttle.new(name, options, &block)
else
Check.new(name, options, &block)
end
end
def matched_by?(request)
filter.matched_by?(request)
end
end
end
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/lib/rack/attack/path_normalizer.rb | lib/rack/attack/path_normalizer.rb | # frozen_string_literal: true
module Rack
class Attack
# When using Rack::Attack with a Rails app, developers expect the request path
# to be normalized. In particular, trailing slashes are stripped.
# (See
# https://github.com/rails/rails/blob/f8edd20/actionpack/lib/action_dispatch/journey/router/utils.rb#L5-L22
# for implementation.)
#
# Look for an ActionDispatch utility class that Rails folks would expect
# to normalize request paths. If unavailable, use a fallback class that
# doesn't normalize the path (as a non-Rails rack app developer expects).
module FallbackPathNormalizer
def self.normalize_path(path)
path
end
end
PathNormalizer = if defined?(::ActionDispatch::Journey::Router::Utils)
# For Rails apps
::ActionDispatch::Journey::Router::Utils
else
FallbackPathNormalizer
end
end
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/lib/rack/attack/railtie.rb | lib/rack/attack/railtie.rb | # frozen_string_literal: true
begin
require 'rails/railtie'
rescue LoadError
return
end
module Rack
class Attack
class Railtie < ::Rails::Railtie
initializer "rack-attack.middleware" do |app|
app.middleware.use(Rack::Attack)
end
end
end
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/lib/rack/attack/configuration.rb | lib/rack/attack/configuration.rb | # frozen_string_literal: true
require "ipaddr"
module Rack
class Attack
class Configuration
DEFAULT_BLOCKLISTED_RESPONDER = lambda { |_req| [403, { 'content-type' => 'text/plain' }, ["Forbidden\n"]] }
DEFAULT_THROTTLED_RESPONDER = lambda do |req|
if Rack::Attack.configuration.throttled_response_retry_after_header
match_data = req.env['rack.attack.match_data']
now = match_data[:epoch_time]
retry_after = match_data[:period] - (now % match_data[:period])
[429, { 'content-type' => 'text/plain', 'retry-after' => retry_after.to_s }, ["Retry later\n"]]
else
[429, { 'content-type' => 'text/plain' }, ["Retry later\n"]]
end
end
attr_reader :safelists, :blocklists, :throttles, :tracks, :anonymous_blocklists, :anonymous_safelists
attr_accessor :blocklisted_responder, :throttled_responder, :throttled_response_retry_after_header
attr_reader :blocklisted_response, :throttled_response # Keeping these for backwards compatibility
def blocklisted_response=(responder)
warn "[DEPRECATION] Rack::Attack.blocklisted_response is deprecated. "\
"Please use Rack::Attack.blocklisted_responder instead."
@blocklisted_response = responder
end
def throttled_response=(responder)
warn "[DEPRECATION] Rack::Attack.throttled_response is deprecated. "\
"Please use Rack::Attack.throttled_responder instead"
@throttled_response = responder
end
def initialize
set_defaults
end
def safelist(name = nil, &block)
safelist = Safelist.new(name, &block)
if name
@safelists[name] = safelist
else
@anonymous_safelists << safelist
end
end
def blocklist(name = nil, &block)
blocklist = Blocklist.new(name, &block)
if name
@blocklists[name] = blocklist
else
@anonymous_blocklists << blocklist
end
end
def blocklist_ip(ip_address)
@anonymous_blocklists << Blocklist.new do |request|
request.ip && !request.ip.empty? && IPAddr.new(ip_address).include?(IPAddr.new(request.ip))
end
end
def safelist_ip(ip_address)
@anonymous_safelists << Safelist.new do |request|
request.ip && !request.ip.empty? && IPAddr.new(ip_address).include?(IPAddr.new(request.ip))
end
end
def throttle(name, options, &block)
@throttles[name] = Throttle.new(name, options, &block)
end
def track(name, options = {}, &block)
@tracks[name] = Track.new(name, options, &block)
end
def safelisted?(request)
@anonymous_safelists.any? { |safelist| safelist.matched_by?(request) } ||
@safelists.any? { |_name, safelist| safelist.matched_by?(request) }
end
def blocklisted?(request)
@anonymous_blocklists.any? { |blocklist| blocklist.matched_by?(request) } ||
@blocklists.any? { |_name, blocklist| blocklist.matched_by?(request) }
end
def throttled?(request)
@throttles.any? do |_name, throttle|
throttle.matched_by?(request)
end
end
def tracked?(request)
@tracks.each_value do |track|
track.matched_by?(request)
end
end
def clear_configuration
set_defaults
end
private
def set_defaults
@safelists = {}
@blocklists = {}
@throttles = {}
@tracks = {}
@anonymous_blocklists = []
@anonymous_safelists = []
@throttled_response_retry_after_header = false
@blocklisted_responder = DEFAULT_BLOCKLISTED_RESPONDER
@throttled_responder = DEFAULT_THROTTLED_RESPONDER
# Deprecated: Keeping these for backwards compatibility
@blocklisted_response = nil
@throttled_response = nil
end
end
end
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/lib/rack/attack/fail2ban.rb | lib/rack/attack/fail2ban.rb | # frozen_string_literal: true
module Rack
class Attack
class Fail2Ban
class << self
def filter(discriminator, options)
bantime = options[:bantime] or raise ArgumentError, "Must pass bantime option"
findtime = options[:findtime] or raise ArgumentError, "Must pass findtime option"
maxretry = options[:maxretry] or raise ArgumentError, "Must pass maxretry option"
if banned?(discriminator)
# Return true for blocklist
true
elsif yield
fail!(discriminator, bantime, findtime, maxretry)
end
end
def reset(discriminator, options)
findtime = options[:findtime] or raise ArgumentError, "Must pass findtime option"
cache.reset_count("#{key_prefix}:count:#{discriminator}", findtime)
# Clear ban flag just in case it's there
cache.delete("#{key_prefix}:ban:#{discriminator}")
end
def banned?(discriminator)
cache.read("#{key_prefix}:ban:#{discriminator}") ? true : false
end
protected
def key_prefix
'fail2ban'
end
def fail!(discriminator, bantime, findtime, maxretry)
count = cache.count("#{key_prefix}:count:#{discriminator}", findtime)
if count >= maxretry
ban!(discriminator, bantime)
end
true
end
private
def ban!(discriminator, bantime)
cache.write("#{key_prefix}:ban:#{discriminator}", 1, bantime)
end
def cache
Rack::Attack.cache
end
end
end
end
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/lib/rack/attack/safelist.rb | lib/rack/attack/safelist.rb | # frozen_string_literal: true
module Rack
class Attack
class Safelist < Check
def initialize(name = nil, &block)
super
@type = :safelist
end
end
end
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/lib/rack/attack/base_proxy.rb | lib/rack/attack/base_proxy.rb | # frozen_string_literal: true
require 'delegate'
module Rack
class Attack
class BaseProxy < SimpleDelegator
class << self
def proxies
@@proxies ||= []
end
def inherited(klass)
super
proxies << klass
end
def lookup(store)
proxies.find { |proxy| proxy.handle?(store) }
end
def handle?(_store)
raise NotImplementedError
end
end
end
end
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/lib/rack/attack/check.rb | lib/rack/attack/check.rb | # frozen_string_literal: true
module Rack
class Attack
class Check
attr_reader :name, :block, :type
def initialize(name, options = {}, &block)
@name = name
@block = block
@type = options.fetch(:type, nil)
end
def matched_by?(request)
block.call(request).tap do |match|
if match
request.env["rack.attack.matched"] = name
request.env["rack.attack.match_type"] = type
Rack::Attack.instrument(request)
end
end
end
end
end
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/lib/rack/attack/request.rb | lib/rack/attack/request.rb | # frozen_string_literal: true
# Rack::Attack::Request is the same as :ActionDispatch::Request in Rails apps,
# and ::Rack::Request in other apps by default.
#
# This is a safe place to add custom helper methods to the request object
# through monkey patching:
#
# class Rack::Attack::Request < ::Rack::Request
# def localhost?
# ip == "127.0.0.1"
# end
# end
#
# Rack::Attack.safelist("localhost") {|req| req.localhost? }
#
module Rack
class Attack
class Request < defined?(::ActionDispatch::Request) ? ::ActionDispatch::Request : ::Rack::Request
end
end
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
rack/rack-attack | https://github.com/rack/rack-attack/blob/d1a979dd32ac5783e06d661fab65c8c390019f4b/lib/rack/attack/throttle.rb | lib/rack/attack/throttle.rb | # frozen_string_literal: true
module Rack
class Attack
class Throttle
MANDATORY_OPTIONS = [:limit, :period].freeze
attr_reader :name, :limit, :period, :block, :type
def initialize(name, options, &block)
@name = name
@block = block
MANDATORY_OPTIONS.each do |opt|
raise ArgumentError, "Must pass #{opt.inspect} option" unless options[opt]
end
@limit = options[:limit]
@period = options[:period].respond_to?(:call) ? options[:period] : options[:period].to_i
@type = options.fetch(:type, :throttle)
end
def cache
Rack::Attack.cache
end
def matched_by?(request)
discriminator = discriminator_for(request)
return false unless discriminator
current_period = period_for(request)
current_limit = limit_for(request)
count = cache.count("#{name}:#{discriminator}", current_period)
data = {
discriminator: discriminator,
count: count,
period: current_period,
limit: current_limit,
epoch_time: cache.last_epoch_time
}
annotate_request_with_throttle_data(request, data)
(count > current_limit).tap do |throttled|
if throttled
annotate_request_with_matched_data(request, data)
Rack::Attack.instrument(request)
end
end
end
private
def discriminator_for(request)
discriminator = block.call(request)
if discriminator && Rack::Attack.throttle_discriminator_normalizer
discriminator = Rack::Attack.throttle_discriminator_normalizer.call(discriminator)
end
discriminator
end
def period_for(request)
period.respond_to?(:call) ? period.call(request) : period
end
def limit_for(request)
limit.respond_to?(:call) ? limit.call(request) : limit
end
def annotate_request_with_throttle_data(request, data)
(request.env['rack.attack.throttle_data'] ||= {})[name] = data
end
def annotate_request_with_matched_data(request, data)
request.env['rack.attack.matched'] = name
request.env['rack.attack.match_discriminator'] = data[:discriminator]
request.env['rack.attack.match_type'] = type
request.env['rack.attack.match_data'] = data
end
end
end
end
| ruby | MIT | d1a979dd32ac5783e06d661fab65c8c390019f4b | 2026-01-04T15:42:47.875992Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.