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
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot/evaluation.rb
lib/factory_bot/evaluation.rb
module FactoryBot class Evaluation def initialize(evaluator, attribute_assigner, to_create, observer) @evaluator = evaluator @attribute_assigner = attribute_assigner @to_create = to_create @observer = observer end delegate :object, :hash, to: :@attribute_assigner def create(result_instance) case @to_create.arity when 2 then @to_create[result_instance, @evaluator] else @to_create[result_instance] end end def notify(name, result_instance) @observer.update(name, result_instance) end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot/strategy_syntax_method_registrar.rb
lib/factory_bot/strategy_syntax_method_registrar.rb
module FactoryBot # @api private class StrategySyntaxMethodRegistrar def initialize(strategy_name) @strategy_name = strategy_name end def define_strategy_methods define_singular_strategy_method define_list_strategy_method define_pair_strategy_method end def self.with_index(block, index) if block&.arity == 2 ->(instance) { block.call(instance, index) } else block end end private def define_singular_strategy_method strategy_name = @strategy_name define_syntax_method(strategy_name) do |name, *traits_and_overrides, &block| FactoryRunner.new(name, strategy_name, traits_and_overrides).run(&block) end end def define_list_strategy_method strategy_name = @strategy_name define_syntax_method("#{strategy_name}_list") do |name, amount, *traits_and_overrides, &block| unless amount.respond_to?(:times) raise ArgumentError, "count missing for #{strategy_name}_list" end Array.new(amount) do |i| block_with_index = StrategySyntaxMethodRegistrar.with_index(block, i) send(strategy_name, name, *traits_and_overrides, &block_with_index) end end end def define_pair_strategy_method strategy_name = @strategy_name define_syntax_method("#{strategy_name}_pair") do |name, *traits_and_overrides, &block| Array.new(2) { send(strategy_name, name, *traits_and_overrides, &block) } end end def define_syntax_method(name, &block) FactoryBot::Syntax::Methods.module_exec do if method_defined?(name) || private_method_defined?(name) undef_method(name) end define_method(name, &block) end end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot/evaluator.rb
lib/factory_bot/evaluator.rb
require "active_support/core_ext/class/attribute" module FactoryBot # @api private class Evaluator class_attribute :attribute_lists private_instance_methods.each do |method| undef_method(method) unless method.match?(/^__|initialize/) end def initialize(build_strategy, overrides = {}) @build_strategy = build_strategy @overrides = overrides @cached_attributes = overrides @instance = nil @overrides.each do |name, value| singleton_class.define_attribute(name) { value } end end def association(factory_name, *traits_and_overrides) overrides = traits_and_overrides.extract_options! strategy_override = overrides.fetch(:strategy) { FactoryBot.use_parent_strategy ? @build_strategy.to_sym : :create } traits_and_overrides += [overrides.except(:strategy)] runner = FactoryRunner.new(factory_name, strategy_override, traits_and_overrides) @build_strategy.association(runner) end attr_accessor :instance def method_missing(method_name, ...) if @instance.respond_to?(method_name) @instance.send(method_name, ...) else SyntaxRunner.new.send(method_name, ...) end end def respond_to_missing?(method_name, _include_private = false) @instance.respond_to?(method_name) || SyntaxRunner.new.respond_to?(method_name) end def __override_names__ @overrides.keys end def increment_sequence(sequence, scope: self) value = sequence.next(scope) raise if value.respond_to?(:start_with?) && value.start_with?("#<FactoryBot::Declaration") value rescue raise ArgumentError, "Sequence '#{sequence.uri_manager.first}' failed to " \ "return a value. Perhaps it needs a scope to operate? (scope: <object>)" end def self.attribute_list AttributeList.new.tap do |list| attribute_lists.each do |attribute_list| list.apply_attributes attribute_list.to_a end end end def self.define_attribute(name, &block) if instance_methods(false).include?(name) || private_instance_methods(false).include?(name) undef_method(name) end define_method(name) do if @cached_attributes.key?(name) @cached_attributes[name] else @cached_attributes[name] = instance_exec(&block) end end end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot/decorator/invocation_tracker.rb
lib/factory_bot/decorator/invocation_tracker.rb
module FactoryBot class Decorator class InvocationTracker < Decorator def initialize(component) super @invoked_methods = [] end def method_missing(name, *args, &block) # rubocop:disable Style/MissingRespondToMissing @invoked_methods << name super end ruby2_keywords :method_missing if respond_to?(:ruby2_keywords, true) def __invoked_methods__ @invoked_methods.uniq end end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot/decorator/attribute_hash.rb
lib/factory_bot/decorator/attribute_hash.rb
module FactoryBot class Decorator class AttributeHash < Decorator def initialize(component, attributes = []) super(component) @attributes = attributes end def attributes @attributes.each_with_object({}) do |attribute_name, result| result[attribute_name] = @component.send(attribute_name) end end end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot/decorator/new_constructor.rb
lib/factory_bot/decorator/new_constructor.rb
module FactoryBot class Decorator class NewConstructor < Decorator def initialize(component, build_class) super(component) @build_class = build_class end delegate :new, to: :@build_class end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot/decorator/disallows_duplicates_registry.rb
lib/factory_bot/decorator/disallows_duplicates_registry.rb
module FactoryBot class Decorator class DisallowsDuplicatesRegistry < Decorator def register(name, item) if registered?(name) raise DuplicateDefinitionError, "#{@component.name} already registered: #{name}" else @component.register(name, item) end end end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot/declaration/dynamic.rb
lib/factory_bot/declaration/dynamic.rb
module FactoryBot class Declaration # @api private class Dynamic < Declaration def initialize(name, ignored = false, block = nil) super(name, ignored) @block = block end def ==(other) self.class == other.class && name == other.name && ignored == other.ignored && block == other.block end protected attr_reader :block private def build [Attribute::Dynamic.new(name, @ignored, @block)] end end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot/declaration/implicit.rb
lib/factory_bot/declaration/implicit.rb
module FactoryBot class Declaration # @api private class Implicit < Declaration def initialize(name, factory = nil, ignored = false) super(name, ignored) @factory = factory end def ==(other) self.class == other.class && name == other.name && factory == other.factory && ignored == other.ignored end protected attr_reader :factory private def build if FactoryBot.factories.registered?(name) [Attribute::Association.new(name, name, {})] elsif FactoryBot::Internal.sequences.registered?(name) [Attribute::Sequence.new(name, name, @ignored)] elsif @factory.name.to_s == name.to_s message = "Self-referencing trait '#{@name}'" raise TraitDefinitionError, message else @factory.inherit_traits([name]) [] end end end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot/declaration/association.rb
lib/factory_bot/declaration/association.rb
module FactoryBot class Declaration # @api private class Association < Declaration def initialize(name, *options) super(name, false) @options = options.dup @overrides = options.extract_options! @factory_name = @overrides.delete(:factory) || name @traits = options end def ==(other) self.class == other.class && name == other.name && options == other.options end protected attr_reader :options private attr_reader :factory_name, :overrides, :traits def build raise_if_arguments_are_declarations! [ Attribute::Association.new( name, factory_name, [traits, overrides].flatten ) ] end def raise_if_arguments_are_declarations! if factory_name.is_a?(Declaration) raise ArgumentError.new(<<~MSG) Association '#{name}' received an invalid factory argument. Did you mean? 'factory: :#{factory_name.name}' MSG end overrides.each do |attribute, value| if value.is_a?(Declaration) raise ArgumentError.new(<<~MSG) Association '#{name}' received an invalid attribute override. Did you mean? '#{attribute}: :#{value.name}' MSG end end end end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot/syntax/methods.rb
lib/factory_bot/syntax/methods.rb
module FactoryBot module Syntax ## This module is a container for all strategy methods provided by ## FactoryBot. This includes all the default strategies provided ({Methods#build}, ## {Methods#create}, {Methods#build_stubbed}, and {Methods#attributes_for}), as ## well as the complementary *_list and *_pair methods. ## @example singular factory execution ## # basic use case ## build(:completed_order) ## ## # factory yielding its result to a block ## create(:post) do |post| ## create(:comment, post: post) ## end ## ## # factory with attribute override ## attributes_for(:post, title: "I love Ruby!") ## ## # factory with traits and attribute override ## build_stubbed(:user, :admin, :male, name: "John Doe") ## ## @example multiple factory execution ## # basic use case ## build_list(:completed_order, 2) ## create_list(:completed_order, 2) ## ## # factory with attribute override ## attributes_for_list(:post, 4, title: "I love Ruby!") ## ## # factory with traits and attribute override ## build_stubbed_list(:user, 15, :admin, :male, name: "John Doe") module Methods # @!parse FactoryBot::Internal.register_default_strategies # @!method build(name, *traits_and_overrides, &block) # (see #strategy_method) # Builds a registered factory by name. # @return [Object] instantiated object defined by the factory # @!method create(name, *traits_and_overrides, &block) # (see #strategy_method) # Creates a registered factory by name. # @return [Object] instantiated object defined by the factory # @!method build_stubbed(name, *traits_and_overrides, &block) # (see #strategy_method) # Builds a stubbed registered factory by name. # @return [Object] instantiated object defined by the factory # @!method attributes_for(name, *traits_and_overrides, &block) # (see #strategy_method) # Generates a hash of attributes for a registered factory by name. # @return [Hash] hash of attributes for the factory # @!method build_list(name, amount, *traits_and_overrides, &block) # (see #strategy_method_list) # @return [Array] array of built objects defined by the factory # @!method create_list(name, amount, *traits_and_overrides, &block) # (see #strategy_method_list) # @return [Array] array of created objects defined by the factory # @!method build_stubbed_list(name, amount, *traits_and_overrides, &block) # (see #strategy_method_list) # @return [Array] array of stubbed objects defined by the factory # @!method attributes_for_list(name, amount, *traits_and_overrides, &block) # (see #strategy_method_list) # @return [Array<Hash>] array of attribute hashes for the factory # @!method build_pair(name, *traits_and_overrides, &block) # (see #strategy_method_pair) # @return [Array] pair of built objects defined by the factory # @!method create_pair(name, *traits_and_overrides, &block) # (see #strategy_method_pair) # @return [Array] pair of created objects defined by the factory # @!method build_stubbed_pair(name, *traits_and_overrides, &block) # (see #strategy_method_pair) # @return [Array] pair of stubbed objects defined by the factory # @!method attributes_for_pair(name, *traits_and_overrides, &block) # (see #strategy_method_pair) # @return [Array<Hash>] pair of attribute hashes for the factory # @!method strategy_method(name, traits_and_overrides, &block) # @!visibility private # @param [Symbol] name the name of the factory to build # @param [Array<Symbol, Symbol, Hash>] traits_and_overrides splat args traits and a hash of overrides # @param [Proc] block block to be executed # @!method strategy_method_list(name, amount, traits_and_overrides, &block) # @!visibility private # @param [Symbol] name the name of the factory to execute # @param [Integer] amount the number of instances to execute # @param [Array<Symbol, Symbol, Hash>] traits_and_overrides splat args traits and a hash of overrides # @param [Proc] block block to be executed # @!method strategy_method_pair(name, traits_and_overrides, &block) # @!visibility private # @param [Symbol] name the name of the factory to execute # @param [Array<Symbol, Symbol, Hash>] traits_and_overrides splat args traits and a hash of overrides # @param [Proc] block block to be executed # Generates and returns the next value in a global or factory sequence. # # Arguments: # context: (Array of Symbols) # The definition context of the sequence, with the sequence name # as the final entry # scope: (object)(optional) # The object the sequence should be evaluated within # # Returns: # The next value in the sequence. (Object) # # Example: # generate(:my_factory, :my_trair, :my_sequence) # def generate(*uri_parts, scope: nil) uri = FactoryBot::UriManager.build_uri(uri_parts) sequence = Sequence.find_by_uri(uri) || raise(KeyError, "Sequence not registered: #{FactoryBot::UriManager.build_uri(uri_parts)}") increment_sequence(sequence, scope: scope) end # Generates and returns the list of values in a global or factory sequence. # # Arguments: # uri_parts: (Array of Symbols) # The definition context of the sequence, with the sequence name # as the final entry # scope: (object)(optional) # The object the sequence should be evaluated within # # Returns: # The next value in the sequence. (Object) # # Example: # generate_list(:my_factory, :my_trair, :my_sequence, 5) # def generate_list(*uri_parts, count, scope: nil) uri = FactoryBot::UriManager.build_uri(uri_parts) sequence = Sequence.find_by_uri(uri) || raise(KeyError, "Sequence not registered: '#{uri}'") (1..count).map do increment_sequence(sequence, scope: scope) end end # ====================================================================== # = PRIVATE # ====================================================================== # private ## # Increments the given sequence and returns the value. # # Arguments: # sequence: # The sequence instance # scope: (object)(optional) # The object the sequence should be evaluated within # def increment_sequence(sequence, scope: nil) value = sequence.next(scope) raise if value.respond_to?(:start_with?) && value.start_with?("#<FactoryBot::Declaration") value rescue raise ArgumentError, "Sequence '#{sequence.uri_manager.first}' failed to " \ "return a value. Perhaps it needs a scope to operate? (scope: <object>)" end end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot/syntax/default.rb
lib/factory_bot/syntax/default.rb
module FactoryBot module Syntax module Default include Methods def define(&block) DSL.run(block) end def modify(&block) ModifyDSL.run(block) end class DSL def factory(name, options = {}, &block) factory = Factory.new(name, options) proxy = FactoryBot::DefinitionProxy.new(factory.definition) proxy.instance_eval(&block) if block Internal.register_factory(factory) proxy.child_factories.each do |(child_name, child_options, child_block)| parent_factory = child_options.delete(:parent) || name factory(child_name, child_options.merge(parent: parent_factory), &child_block) end end def sequence(name, ...) Internal.register_sequence(Sequence.new(name, ...)) end def trait(name, &block) Internal.register_trait(Trait.new(name, &block)) end def self.run(block) new.instance_eval(&block) end delegate :after, :before, :callback, :initialize_with, :skip_create, :to_create, to: FactoryBot::Internal end class ModifyDSL def factory(name, _options = {}, &block) factory = Internal.factory_by_name(name) proxy = FactoryBot::DefinitionProxy.new(factory.definition.overridable) proxy.instance_eval(&block) end def self.run(block) new.instance_eval(&block) end end end end extend Syntax::Default end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot/strategy/build.rb
lib/factory_bot/strategy/build.rb
module FactoryBot module Strategy class Build def association(runner) runner.run end def result(evaluation) evaluation.notify(:before_build, nil) evaluation.object.tap do |instance| evaluation.notify(:after_build, instance) end end def to_sym :build end end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot/strategy/attributes_for.rb
lib/factory_bot/strategy/attributes_for.rb
module FactoryBot module Strategy class AttributesFor def association(runner) runner.run(:null) end def result(evaluation) evaluation.hash end def to_sym :attributes_for end end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot/strategy/stub.rb
lib/factory_bot/strategy/stub.rb
module FactoryBot module Strategy class Stub @@next_id = 1000 DISABLED_PERSISTENCE_METHODS = [ :connection, :decrement!, :delete, :destroy!, :destroy, :increment!, :reload, :save!, :save, :toggle!, :touch, :update!, :update, :update_attribute, :update_attributes!, :update_attributes, :update_column, :update_columns ].freeze def self.next_id=(id) @@next_id = id end def association(runner) runner.run(:build_stubbed) end def result(evaluation) evaluation.object.tap do |instance| stub_database_interaction_on_result(instance) set_timestamps(instance) clear_changes_information(instance) evaluation.notify(:after_stub, instance) end end def to_sym :stub end private def next_id(result_instance) if uuid_primary_key?(result_instance) SecureRandom.uuid else @@next_id += 1 end end def stub_database_interaction_on_result(result_instance) if has_settable_id?(result_instance) result_instance.id ||= next_id(result_instance) end result_instance.instance_eval do def persisted? true end def new_record? false end def destroyed? false end DISABLED_PERSISTENCE_METHODS.each do |write_method| define_singleton_method(write_method) do |*args| raise "stubbed models are not allowed to access the database - " \ "#{self.class}##{write_method}(#{args.join(",")})" end end end end def has_settable_id?(result_instance) result_instance.respond_to?(:id=) && (!result_instance.class.respond_to?(:primary_key) || result_instance.class.primary_key) end def uuid_primary_key?(result_instance) result_instance.respond_to?(:column_for_attribute) && (column = result_instance.column_for_attribute(result_instance.class.primary_key)) && column.respond_to?(:sql_type) && column.sql_type == "uuid" end def clear_changes_information(result_instance) if result_instance.respond_to?(:clear_changes_information) result_instance.clear_changes_information end end def set_timestamps(result_instance) timestamp = Time.current if missing_created_at?(result_instance) result_instance.created_at = timestamp end if missing_updated_at?(result_instance) result_instance.updated_at = timestamp end end def missing_created_at?(result_instance) result_instance.respond_to?(:created_at) && result_instance.respond_to?(:created_at=) && result_instance.created_at.blank? end def missing_updated_at?(result_instance) result_instance.respond_to?(:updated_at) && result_instance.respond_to?(:updated_at=) && result_instance.updated_at.blank? end end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot/strategy/null.rb
lib/factory_bot/strategy/null.rb
module FactoryBot module Strategy class Null def association(runner) end def result(evaluation) end def to_sym :null end end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot/strategy/create.rb
lib/factory_bot/strategy/create.rb
module FactoryBot module Strategy class Create def association(runner) runner.run end def result(evaluation) evaluation.notify(:before_build, nil) evaluation.object.tap do |instance| evaluation.notify(:after_build, instance) evaluation.notify(:before_create, instance) evaluation.create(instance) evaluation.notify(:after_create, instance) end end def to_sym :create end end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot/attribute/dynamic.rb
lib/factory_bot/attribute/dynamic.rb
module FactoryBot class Attribute # @api private class Dynamic < Attribute def initialize(name, ignored, block) super(name, ignored) @block = block end def to_proc block = @block -> { value = case block.arity when 1, -1, -2 then instance_exec(self, &block) else instance_exec(&block) end raise SequenceAbuseError if FactoryBot::Sequence === value value } end end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot/attribute/sequence.rb
lib/factory_bot/attribute/sequence.rb
module FactoryBot class Attribute # @api private class Sequence < Attribute def initialize(name, sequence, ignored) super(name, ignored) @sequence = sequence end def to_proc sequence = @sequence -> { FactoryBot.generate(sequence) } end end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot/attribute/association.rb
lib/factory_bot/attribute/association.rb
module FactoryBot class Attribute # @api private class Association < Attribute attr_reader :factory def initialize(name, factory, overrides) super(name, false) @factory = factory @overrides = overrides end def to_proc factory = @factory overrides = @overrides traits_and_overrides = [factory, overrides].flatten factory_name = traits_and_overrides.shift -> { association(factory_name, *traits_and_overrides) } end def association? true end end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
kaminari/kaminari
https://github.com/kaminari/kaminari/blob/55d6e40767442d206236d3718c5bdb32d01f2345/misc/bug_report_template.rb
misc/bug_report_template.rb
begin require "bundler/inline" rescue LoadError => e $stderr.puts "Bundler version 1.10 or later is required. Please update your Bundler" raise e end gemfile(true) do source "https://rubygems.org" # Activate the gem you are reporting the issue against. gem "railties", "5.0.1" gem "activerecord", "5.0.1" gem "sqlite3" gem "kaminari-core" gem "kaminari-activerecord" end require "active_record" require "minitest/autorun" require "logger" require "kaminari/core" require "kaminari/activerecord" # Ensure backward compatibility with Minitest 4 Minitest::Test = MiniTest::Unit::TestCase unless defined?(Minitest::Test) # This connection will do for database-independent bug reports. ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:") ActiveRecord::Base.logger = Logger.new(STDOUT) ActiveRecord::Schema.define do create_table :posts, force: true do |t| end create_table :comments, force: true do |t| t.integer :post_id end end class Post < ActiveRecord::Base has_many :comments end class Comment < ActiveRecord::Base belongs_to :post end class BugTest < Minitest::Test def test_pagination_stuff post = Post.create! post.comments << Comment.create! assert_equal 1, Post.page(1).total_count assert_equal 1, post.reload.comments.page(1).total_count end end
ruby
MIT
55d6e40767442d206236d3718c5bdb32d01f2345
2026-01-04T15:38:55.939543Z
false
kaminari/kaminari
https://github.com/kaminari/kaminari/blob/55d6e40767442d206236d3718c5bdb32d01f2345/test/test_helper.rb
test/test_helper.rb
# frozen_string_literal: true $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) $LOAD_PATH.unshift(File.join(Gem.loaded_specs['kaminari-core'].gem_dir, 'test')) $LOAD_PATH.unshift(File.dirname(__FILE__)) ENV['RAILS_ENV'] ||= 'test' ENV['DB'] ||= 'sqlite3' # require logger before requiring rails, or Rails 6 fails to boot require 'logger' require 'rails' require 'active_record' require 'bundler/setup' Bundler.require # Simulate a gem providing a subclass of ActiveRecord::Base before the Railtie is loaded. require 'fake_gem' require 'fake_app/rails_app' require 'test/unit/rails/test_help' # Requires supporting files with custom matchers and macros, etc, # in ./support/ and its subdirectories. Dir["#{File.join(Gem.loaded_specs['kaminari-core'].gem_dir, 'test')}/support/**/*.rb"].each {|f| require f}
ruby
MIT
55d6e40767442d206236d3718c5bdb32d01f2345
2026-01-04T15:38:55.939543Z
false
kaminari/kaminari
https://github.com/kaminari/kaminari/blob/55d6e40767442d206236d3718c5bdb32d01f2345/kaminari-core/test/fake_gem.rb
kaminari-core/test/fake_gem.rb
# frozen_string_literal: true module Kaminari module FakeGem extend ActiveSupport::Concern module ClassMethods def inherited(kls) super def kls.fake_gem_defined_method; end end end end end ActiveSupport.on_load :active_record do ActiveRecord::Base.send :include, Kaminari::FakeGem # Simulate a gem providing a subclass of ActiveRecord::Base before the Railtie is loaded. class GemDefinedModel < ActiveRecord::Base end end
ruby
MIT
55d6e40767442d206236d3718c5bdb32d01f2345
2026-01-04T15:38:55.939543Z
false
kaminari/kaminari
https://github.com/kaminari/kaminari/blob/55d6e40767442d206236d3718c5bdb32d01f2345/kaminari-core/test/requests/navigation_test.rb
kaminari-core/test/requests/navigation_test.rb
# frozen_string_literal: true require 'test_helper' class NavigationTest < Test::Unit::TestCase include Capybara::DSL setup do 1.upto(100) {|i| User.create! name: "user#{'%03d' % i}" } Capybara.current_driver = :rack_test end teardown do Capybara.reset_sessions! Capybara.use_default_driver User.delete_all end test 'navigating by pagination links' do visit '/users' assert page.has_no_content? 'previous page' assert page.has_content? 'next page' within 'nav.pagination' do within 'span.page.current' do assert page.has_content? '1' end within 'span.next' do click_link 'Next ›' end end assert page.has_content? 'previous page' assert page.has_content? 'next page' within 'nav.pagination' do within 'span.page.current' do assert page.has_content? '2' end within 'span.last' do click_link 'Last »' end end assert page.has_content? 'previous page' assert page.has_no_content? 'next page' within 'nav.pagination' do within 'span.page.current' do assert page.has_content? '4' end within 'span.prev' do click_link '‹ Prev' end end assert page.has_content? 'previous page' assert page.has_content? 'next page' within 'nav.pagination' do within 'span.page.current' do assert page.has_content? '3' end within 'span.first' do click_link '« First' end end within 'nav.pagination' do within 'span.page.current' do assert page.has_content? '1' end end within 'div.info' do assert page.has_text? 'Displaying users 1' end end end
ruby
MIT
55d6e40767442d206236d3718c5bdb32d01f2345
2026-01-04T15:38:55.939543Z
false
kaminari/kaminari
https://github.com/kaminari/kaminari/blob/55d6e40767442d206236d3718c5bdb32d01f2345/kaminari-core/test/requests/request_format_test.rb
kaminari-core/test/requests/request_format_test.rb
# frozen_string_literal: true require 'test_helper' class RenderingWithFormatOptionTest < Test::Unit::TestCase include Capybara::DSL setup do User.create! name: 'user1' end teardown do Capybara.reset_sessions! Capybara.use_default_driver User.delete_all end test "Make sure that kaminari doesn't affect the format" do visit '/users/index_text.text' assert_equal 200, page.status_code assert page.has_content? 'partial1' assert page.has_content? 'partial2' end end
ruby
MIT
55d6e40767442d206236d3718c5bdb32d01f2345
2026-01-04T15:38:55.939543Z
false
kaminari/kaminari
https://github.com/kaminari/kaminari/blob/55d6e40767442d206236d3718c5bdb32d01f2345/kaminari-core/test/helpers/action_view_extension_test.rb
kaminari-core/test/helpers/action_view_extension_test.rb
# frozen_string_literal: true require 'test_helper' if defined?(::Rails::Railtie) && defined?(::ActionView) class ActionViewExtensionTest < ActionView::TestCase setup do self.output_buffer = ::ActionView::OutputBuffer.new I18n.available_locales = [:en, :de, :fr] I18n.locale = :en end teardown do User.delete_all end sub_test_case '#paginate' do setup do 50.times {|i| User.create! name: "user#{i}"} end test 'returns a String' do users = User.page(1) assert_kind_of String, view.paginate(users, params: {controller: 'users', action: 'index'}) end test 'escaping the pagination for javascript' do users = User.page(1) assert_nothing_raised do escape_javascript(view.paginate users, params: {controller: 'users', action: 'index'}) end end test 'allows for overriding params with the :params option' do view.params[:controller], view.params[:action] = 'addresses', 'new' users = User.page(1) assert_match '/users?page=2', view.paginate(users, params: { controller: 'users', action: 'index' }) end test 'accepts :theme option' do users = User.page(1) begin view_paths_was = controller.view_paths.paths controller.append_view_path File.join(Gem.loaded_specs['kaminari-core'].gem_dir, 'test/fake_app/views') html = view.paginate users, theme: 'bootstrap', params: {controller: 'users', action: 'index'} assert_match(/bootstrap-paginator/, html) assert_match(/bootstrap-page-link/, html) ensure controller.view_paths.instance_variable_set :@paths, view_paths_was end end test 'accepts :views_prefix option' do users = User.page(1) begin view_paths_was = controller.view_paths.paths controller.append_view_path File.join(Gem.loaded_specs['kaminari-core'].gem_dir, 'test/fake_app/views') assert_equal " <b>1</b>\n", view.paginate(users, views_prefix: 'alternative/', params: {controller: 'users', action: 'index'}) ensure controller.view_paths.instance_variable_set :@paths, view_paths_was end end test 'accepts :paginator_class option' do users = User.page(1) custom_paginator = Class.new(Kaminari::Helpers::Paginator) do def to_s "CUSTOM PAGINATION" end end assert_equal 'CUSTOM PAGINATION', view.paginate(users, paginator_class: custom_paginator, params: {controller: 'users', action: 'index'}) end test 'total_pages: 3' do users = User.page(1) assert_match(/<a href="\/users\?page=3">Last/, view.paginate(users, total_pages: 3, params: {controller: 'users', action: 'index'})) end test "page: 20 (out of range)" do users = User.page(20) html = view.paginate users, params: {controller: 'users', action: 'index'} assert_not_match(/Last/, html) assert_not_match(/Next/, html) end end sub_test_case '#link_to_previous_page' do setup do 60.times {|i| User.create! name: "user#{i}"} end sub_test_case 'having previous pages' do test 'the default behaviour' do users = User.page(3) html = view.link_to_previous_page users, 'Previous', params: {controller: 'users', action: 'index'} assert_match(/page=2/, html) assert_match(/rel="prev"/, html) html = view.link_to_previous_page users, 'Previous', params: {controller: 'users', action: 'index'} do 'At the Beginning' end assert_match(/page=2/, html) assert_match(/rel="prev"/, html) end test 'overriding rel=' do users = User.page(3) assert_match(/rel="external"/, view.link_to_previous_page(users, 'Previous', rel: 'external', params: {controller: 'users', action: 'index'})) end test 'with params' do users = User.page(3) params[:status] = 'active' assert_match(/status=active/, view.link_to_previous_page(users, 'Previous', params: {controller: 'users', action: 'index'})) end end test 'the first page' do users = User.page(1) assert_nil view.link_to_previous_page(users, 'Previous', params: {controller: 'users', action: 'index'}) assert_equal 'At the Beginning', (view.link_to_previous_page(users, 'Previous', params: {controller: 'users', action: 'index'}) do 'At the Beginning' end) end test 'out of range' do users = User.page(5) assert_nil view.link_to_previous_page(users, 'Previous', params: {controller: 'users', action: 'index'}) assert_equal 'At the Beginning', (view.link_to_previous_page(users, 'Previous', params: {controller: 'users', action: 'index'}) do 'At the Beginning' end) end test '#link_to_previous_page accepts ActionController::Parameters' do users = User.page(3) params = ActionController::Parameters.new(controller: 'users', action: 'index', status: 'active') html = view.link_to_previous_page users, 'Previous', params: params assert_match(/page=2/, html) assert_match(/rel="prev"/, html) assert_match(/status=active/, html) end end sub_test_case '#link_to_next_page' do setup do 50.times {|i| User.create! name: "user#{i}"} end sub_test_case 'having more page' do test 'the default behaviour' do users = User.page(1) html = view.link_to_next_page users, 'More', params: {controller: 'users', action: 'index'} assert_match(/page=2/, html) assert_match(/rel="next"/, html) end test 'overriding rel=' do users = User.page(1) assert_match(/rel="external"/, view.link_to_next_page(users, 'More', rel: 'external', params: {controller: 'users', action: 'index'})) end test 'with params' do users = User.page(1) params[:status] = 'active' assert_match(/status=active/, view.link_to_next_page(users, 'More', params: {controller: 'users', action: 'index'})) end end test 'the last page' do users = User.page(2) assert_nil view.link_to_next_page(users, 'More', params: {controller: 'users', action: 'index'}) end test 'out of range' do users = User.page(5) assert_nil view.link_to_next_page(users, 'More', params: {controller: 'users', action: 'index'}) end test '#link_to_next_page accepts ActionController::Parameters' do users = User.page(1) params = ActionController::Parameters.new(controller: 'users', action: 'index', status: 'active') html = view.link_to_next_page users, 'More', params: params assert_match(/page=2/, html) assert_match(/rel="next"/, html) assert_match(/status=active/, html) end end sub_test_case '#page_entries_info' do sub_test_case 'on a model without namespace' do sub_test_case 'having no entries' do test 'with default entry name' do users = User.page(1).per(25) assert_equal 'No users found', view.page_entries_info(users) end test 'setting the entry name option to "member"' do users = User.page(1).per(25) assert_equal 'No members found', view.page_entries_info(users, entry_name: 'member') end end sub_test_case 'having 1 entry' do setup do User.create! name: 'user1' end test 'with default entry name' do users = User.page(1).per(25) assert_equal 'Displaying <b>1</b> user', view.page_entries_info(users) end test 'setting the entry name option to "member"' do users = User.page(1).per(25) assert_equal 'Displaying <b>1</b> member', view.page_entries_info(users, entry_name: 'member') end end sub_test_case 'having more than 1 but less than a page of entries' do setup do 10.times {|i| User.create! name: "user#{i}"} end test 'with default entry name' do users = User.page(1).per(25) assert_equal 'Displaying <b>all 10</b> users', view.page_entries_info(users) end test 'setting the entry name option to "member"' do users = User.page(1).per(25) assert_equal 'Displaying <b>all 10</b> members', view.page_entries_info(users, entry_name: 'member') end end sub_test_case 'having more than one page of entries' do setup do 50.times {|i| User.create! name: "user#{i}"} end sub_test_case 'the first page' do test 'with default entry name' do users = User.page(1).per(25) assert_equal 'Displaying users <b>1–25</b> of <b>50</b> in total', view.page_entries_info(users) end test 'setting the entry name option to "member"' do users = User.page(1).per(25) assert_equal 'Displaying members <b>1–25</b> of <b>50</b> in total', view.page_entries_info(users, entry_name: 'member') end end sub_test_case 'the next page' do test 'with default entry name' do users = User.page(2).per(25) assert_equal 'Displaying users <b>26–50</b> of <b>50</b> in total', view.page_entries_info(users) end test 'setting the entry name option to "member"' do users = User.page(2).per(25) assert_equal 'Displaying members <b>26–50</b> of <b>50</b> in total', view.page_entries_info(users, entry_name: 'member') end end sub_test_case 'the last page' do test 'with default entry name' do begin User.max_pages 4 users = User.page(4).per(10) assert_equal 'Displaying users <b>31–40</b> of <b>40</b> in total', view.page_entries_info(users) ensure User.max_pages nil end end end test 'it accepts a decorated object' do page_info_presenter = Class.new(SimpleDelegator) do include ActionView::Helpers::NumberHelper def total_count number_with_delimiter(1_000) end end users = page_info_presenter.new(User.page(1).per(25)) assert_equal 'Displaying users <b>1–25</b> of <b>1,000</b> in total', view.page_entries_info(users) end end end sub_test_case 'I18n' do setup do 50.times {|i| User.create! name: "user#{i}"} end test 'page_entries_info translates entry' do users = User.page(1).per(25) begin I18n.backend.store_translations(:en, User.i18n_scope => { models: { user: { one: "person", other: "people" } } }) assert_equal 'Displaying people <b>1–25</b> of <b>50</b> in total', view.page_entries_info(users) ensure I18n.backend.reload! end end sub_test_case 'with any other locale' do teardown do I18n.backend.reload! end sub_test_case ':de' do setup do I18n.locale = :de I18n.backend.store_translations(:de, helpers: { page_entries_info: { one_page: { display_entries: { one: "Displaying <b>1</b> %{entry_name}", other: "Displaying <b>all %{count}</b> %{entry_name}" } }, more_pages: { display_entries: "Displaying %{entry_name} <b>%{first}–%{last}</b> of <b>%{total}</b> in total" } } } ) end test 'with default entry name' do users = User.page(1).per(50) assert_equal 'Displaying <b>all 50</b> Benutzer', view.page_entries_info(users, entry_name: 'Benutzer') end test 'the last page with default entry name' do users = User.page(5).per(10) assert_equal 'Displaying Benutzer <b>41–50</b> of <b>50</b> in total', view.page_entries_info(users, entry_name: 'Benutzer') end end end sub_test_case ':fr' do setup do I18n.locale = :fr ActiveSupport::Inflector.inflections(:fr) do |inflect| inflect.plural(/$/, 's') inflect.singular(/s$/, '') end I18n.backend.store_translations(:fr, helpers: { page_entries_info: { one_page: { display_entries: { one: "Displaying <b>1</b> %{entry_name}", other: "Displaying <b>all %{count}</b> %{entry_name}" } }, more_pages: { display_entries: "Displaying %{entry_name} <b>%{first}–%{last}</b> of <b>%{total}</b> in total" } } } ) end sub_test_case 'having 1 entry' do setup do User.delete_all User.create! name: 'user1' end test 'with default entry name' do users = User.page(1).per(25) assert_equal 'Displaying <b>1</b> utilisateur', view.page_entries_info(users, entry_name: 'utilisateur') end end test 'having multiple entries with default entry name' do users = User.page(1).per(50) assert_equal 'Displaying <b>all 50</b> utilisateurs', view.page_entries_info(users, entry_name: 'utilisateur') end test 'the last page with default entry name' do users = User.page(5).per(10) assert_equal 'Displaying utilisateurs <b>41–50</b> of <b>50</b> in total', view.page_entries_info(users, entry_name: 'utilisateur') end end end sub_test_case 'on a model with namespace' do teardown do User::Address.delete_all end test 'having no entries' do addresses = User::Address.page(1).per(25) assert_equal 'No addresses found', view.page_entries_info(addresses) end sub_test_case 'having 1 entry' do setup do User::Address.create! end test 'with default entry name' do addresses = User::Address.page(1).per(25) assert_equal 'Displaying <b>1</b> address', view.page_entries_info(addresses) end test 'setting the entry name option to "place"' do addresses = User::Address.page(1).per(25) assert_equal 'Displaying <b>1</b> place', view.page_entries_info(addresses, entry_name: 'place') end end sub_test_case 'having more than 1 but less than a page of entries' do setup do 10.times { User::Address.create! } end test 'with default entry name' do addresses = User::Address.page(1).per(25) assert_equal 'Displaying <b>all 10</b> addresses', view.page_entries_info(addresses) end test 'setting the entry name option to "place"' do addresses = User::Address.page(1).per(25) assert_equal 'Displaying <b>all 10</b> places', view.page_entries_info(addresses, entry_name: 'place') end end sub_test_case 'having more than one page of entries' do setup do 50.times { User::Address.create! } end sub_test_case 'the first page' do test 'with default entry name' do addresses = User::Address.page(1).per(25) assert_equal 'Displaying addresses <b>1–25</b> of <b>50</b> in total', view.page_entries_info(addresses) end test 'setting the entry name option to "place"' do addresses = User::Address.page(1).per(25) assert_equal 'Displaying places <b>1–25</b> of <b>50</b> in total', view.page_entries_info(addresses, entry_name: 'place') end end sub_test_case 'the next page' do test 'with default entry name' do addresses = User::Address.page(2).per(25) assert_equal 'Displaying addresses <b>26–50</b> of <b>50</b> in total', view.page_entries_info(addresses) end test 'setting the entry name option to "place"' do addresses = User::Address.page(2).per(25) assert_equal 'Displaying places <b>26–50</b> of <b>50</b> in total', view.page_entries_info(addresses, entry_name: 'place') end end end end sub_test_case 'on a PaginatableArray' do test 'with a non-empty array' do numbers = Kaminari.paginate_array(%w{one two three}).page(1) assert_equal 'Displaying <b>all 3</b> entries', view.page_entries_info(numbers) end test 'with an empty array and total_count option' do users = Kaminari.paginate_array([], total_count: 50).page(1).per(1) assert_equal 'Displaying users <b>1–1</b> of <b>50</b> in total', view.page_entries_info(users, entry_name: 'user') end end end sub_test_case '#rel_next_prev_link_tags' do setup do 31.times {|i| User.create! name: "user#{i}"} end test 'the first page' do users = User.page(1).per(10) html = view.rel_next_prev_link_tags users, params: {controller: 'users', action: 'index'} assert_not_match(/rel="prev"/, html) assert_match(/rel="next"/, html) assert_match(/\?page=2/, html) end test 'the second page' do users = User.page(2).per(10) html = view.rel_next_prev_link_tags users, params: {controller: 'users', action: 'index'} assert_match(/rel="prev"/, html) assert_not_match(/\?page=1/, html) assert_match(/rel="next"/, html) assert_match(/\?page=3/, html) end test 'the last page' do users = User.page(4).per(10) html = view.rel_next_prev_link_tags users, params: {controller: 'users', action: 'index'} assert_match(/rel="prev"/, html) assert_match(/\?page=3"/, html) assert_not_match(/rel="next"/, html) end end sub_test_case '#path_to_next_page' do setup do 2.times {|i| User.create! name: "user#{i}"} end test 'the first page' do users = User.page(1).per(1) assert_equal '/users?page=2', view.path_to_next_page(users, params: {controller: 'users', action: 'index'}) end test 'the last page' do users = User.page(2).per(1) assert_nil view.path_to_next_page(users, params: {controller: 'users', action: 'index'}) end test 'format option' do users = User.page(1).per(1) assert_equal '/users.turbo_stream?page=2', view.path_to_next_page(users, params: {controller: 'users', action: 'index', format: :turbo_stream}) end end sub_test_case '#path_to_prev_page' do setup do 3.times {|i| User.create! name: "user#{i}"} end test 'the first page' do users = User.page(1).per(1) assert_nil view.path_to_prev_page(users, params: {controller: 'users', action: 'index'}) end test 'the second page' do users = User.page(2).per(1) assert_equal '/users', view.path_to_prev_page(users, params: {controller: 'users', action: 'index'}) end test 'the last page' do users = User.page(3).per(1) assert_equal '/users?page=2', view.path_to_prev_page(users, params: {controller: 'users', action: 'index'}) end end sub_test_case '#next_page_url' do setup do 2.times {|i| User.create! name: "user#{i}"} end test 'the first page' do users = User.page(1).per(1) assert_equal 'http://test.host/users?page=2', view.next_page_url(users, params: {controller: 'users', action: 'index'}) end test 'the last page' do users = User.page(2).per(1) assert_nil view.next_page_url(users, params: {controller: 'users', action: 'index'}) end end sub_test_case '#prev_page_url' do setup do 3.times {|i| User.create! name: "user#{i}"} end test 'the first page' do users = User.page(1).per(1) assert_nil view.prev_page_url(users, params: {controller: 'users', action: 'index'}) end test 'the second page' do users = User.page(2).per(1) assert_equal 'http://test.host/users', view.prev_page_url(users, params: {controller: 'users', action: 'index'}) end test 'the last page' do users = User.page(3).per(1) assert_equal 'http://test.host/users?page=2', view.prev_page_url(users, params: {controller: 'users', action: 'index'}) end end end end
ruby
MIT
55d6e40767442d206236d3718c5bdb32d01f2345
2026-01-04T15:38:55.939543Z
false
kaminari/kaminari
https://github.com/kaminari/kaminari/blob/55d6e40767442d206236d3718c5bdb32d01f2345/kaminari-core/test/helpers/tags_test.rb
kaminari-core/test/helpers/tags_test.rb
# frozen_string_literal: true require 'test_helper' if defined?(::Rails::Railtie) && defined?(ActionView) class TagTest < ActionView::TestCase sub_test_case '#page_url_for' do setup do self.params[:controller] = 'users' self.params[:action] = 'index' end sub_test_case 'for first page' do test 'by default' do assert_equal '/users', Kaminari::Helpers::Tag.new(self).page_url_for(1) end test 'config.params_on_first_page == true' do begin Kaminari.config.params_on_first_page = true assert_equal '/users?page=1', Kaminari::Helpers::Tag.new(self).page_url_for(1) ensure Kaminari.config.params_on_first_page = false end end end sub_test_case 'with a friendly route setting' do setup do self.params[:controller] = 'addresses' self.params[:action] = 'index' self.params[:page] = 3 end sub_test_case 'for first page' do test 'by default' do assert_equal('/addresses', Kaminari::Helpers::Tag.new(self).page_url_for(1)) end test 'config.params_on_first_page == true' do begin Kaminari.config.params_on_first_page = true assert_equal('/addresses/page/1', Kaminari::Helpers::Tag.new(self).page_url_for(1)) ensure Kaminari.config.params_on_first_page = false end end end test 'for other page' do assert_equal('/addresses/page/5', Kaminari::Helpers::Tag.new(self).page_url_for(5)) end end sub_test_case "with param_name = 'user[page]' option" do setup do self.params[:user] = {page: '3', scope: 'active'} end test 'for first page' do assert_not_match(/user%5Bpage%5D=\d+/, Kaminari::Helpers::Tag.new(self, param_name: 'user[page]').page_url_for(1)) # not match user[page]=\d+ assert_match(/user%5Bscope%5D=active/, Kaminari::Helpers::Tag.new(self, param_name: 'user[page]').page_url_for(1)) # match user[scope]=active end test 'for other page' do assert_match(/user%5Bpage%5D=2/, Kaminari::Helpers::Tag.new(self, param_name: 'user[page]').page_url_for(2)) # match user[page]=2 assert_match(/user%5Bscope%5D=active/, Kaminari::Helpers::Tag.new(self, param_name: 'user[page]').page_url_for(2)) # match user[scope]=active end end sub_test_case "with param_name = 'foo.page' option" do setup do self.params['foo.page'] = 2 end test 'for first page' do assert_not_match(/foo\.page=\d+/, Kaminari::Helpers::Tag.new(self, param_name: 'foo.page').page_url_for(1)) end test 'for other page' do assert_match(/foo\.page=\d+/, Kaminari::Helpers::Tag.new(self, param_name: 'foo.page').page_url_for(2)) end end sub_test_case "with param_name = :symbol_param option" do test 'using a symbol as param_name' do assert_match(/symbol_param=\d+/, Kaminari::Helpers::Tag.new(self, param_name: :symbol_param).page_url_for(2)) end end end end class PaginatorTest < ActionView::TestCase test '#current?' do # current_page == page assert_true Kaminari::Helpers::Paginator::PageProxy.new({current_page: 26}, 26, nil).current? # current_page != page assert_false Kaminari::Helpers::Paginator::PageProxy.new({current_page: 13}, 26, nil).current? end test '#first?' do # page == 1 assert_true Kaminari::Helpers::Paginator::PageProxy.new({current_page: 26}, 1, nil).first? # page != 1 assert_false Kaminari::Helpers::Paginator::PageProxy.new({current_page: 13}, 2, nil).first? end test '#last?' do # current_page == page assert_true Kaminari::Helpers::Paginator::PageProxy.new({total_pages: 39}, 39, nil).last? # current_page != page assert_false Kaminari::Helpers::Paginator::PageProxy.new({total_pages: 39}, 38, nil).last? end test '#next?' do # page == current_page + 1 assert_true Kaminari::Helpers::Paginator::PageProxy.new({current_page: 52}, 53, nil).next? # page != current_page + 1 assert_false Kaminari::Helpers::Paginator::PageProxy.new({current_page: 52}, 77, nil).next? end test '#prev?' do # page == current_page - 1 assert_true Kaminari::Helpers::Paginator::PageProxy.new({current_page: 77}, 76, nil).prev? # page != current_page + 1 assert_false Kaminari::Helpers::Paginator::PageProxy.new({current_page: 77}, 80, nil).prev? end test '#rel' do # page == current_page - 1 assert_equal 'prev', Kaminari::Helpers::Paginator::PageProxy.new({current_page: 77}, 76, nil).rel # page == current_page assert_nil Kaminari::Helpers::Paginator::PageProxy.new({current_page: 78}, 78, nil).rel # page == current_page + 1 assert_equal 'next', Kaminari::Helpers::Paginator::PageProxy.new({current_page: 52}, 53, nil).rel end test '#left_outer?' do # current_page == left assert_true Kaminari::Helpers::Paginator::PageProxy.new({left: 3}, 3, nil).left_outer? # current_page == left + 1 assert_false Kaminari::Helpers::Paginator::PageProxy.new({left: 3}, 4, nil).left_outer? # current_page == left + 2 assert_false Kaminari::Helpers::Paginator::PageProxy.new({left: 3}, 5, nil).left_outer? end test '#right_outer?' do # total_pages - page > right assert_false Kaminari::Helpers::Paginator::PageProxy.new({total_pages: 10, right: 3}, 6, nil).right_outer? # total_pages - page == right assert_false Kaminari::Helpers::Paginator::PageProxy.new({total_pages: 10, right: 3}, 7, nil).right_outer? # total_pages - page < right assert_true Kaminari::Helpers::Paginator::PageProxy.new({total_pages: 10, right: 3}, 8, nil).right_outer? end sub_test_case '#inside_window?' do test 'page > current_page' do # page - current_page > window assert_false Kaminari::Helpers::Paginator::PageProxy.new({current_page: 4, window: 5}, 10, nil).inside_window? # page - current_page == window assert_true Kaminari::Helpers::Paginator::PageProxy.new({current_page: 4, window: 6}, 10, nil).inside_window? # page - current_page < window assert_true Kaminari::Helpers::Paginator::PageProxy.new({current_page: 4, window: 7}, 10, nil).inside_window? end test 'current_page > page' do # current_page - page > window assert_false Kaminari::Helpers::Paginator::PageProxy.new({current_page: 15, window: 4}, 10, nil).inside_window? # current_page - page == window assert_true Kaminari::Helpers::Paginator::PageProxy.new({current_page: 15, window: 5}, 10, nil).inside_window? # current_page - page < window assert_true Kaminari::Helpers::Paginator::PageProxy.new({current_page: 15, window: 6}, 10, nil).inside_window? end end sub_test_case '#was_truncated?' do setup do stub(@template = Object.new) do options { {} } params { {} } end end test 'last.is_a? Gap' do assert_true Kaminari::Helpers::Paginator::PageProxy.new({}, 10, Kaminari::Helpers::Gap.new(@template)).was_truncated? end test 'last.is not a Gap' do assert_false Kaminari::Helpers::Paginator::PageProxy.new({}, 10, Kaminari::Helpers::Page.new(@template)).was_truncated? end end sub_test_case '#single_gap?' do setup do @window_options = {left: 1, window: 1, right: 1, total_pages: 9} end def gap_for(page) Kaminari::Helpers::Paginator::PageProxy.new(@window_options, page, nil) end test "in case of '1 ... 4 5 6 ... 9'" do @window_options[:current_page] = 5 assert_false gap_for(2).single_gap? assert_false gap_for(3).single_gap? assert_false gap_for(7).single_gap? assert_false gap_for(8).single_gap? end test "in case of '1 ... 3 4 5 ... 9'" do @window_options[:current_page] = 4 assert_true gap_for(2).single_gap? assert_false gap_for(6).single_gap? assert_false gap_for(8).single_gap? end test "in case of '1 ... 3 4 5 ... 7'" do @window_options[:current_page] = 4 @window_options[:total_pages] = 7 assert_true gap_for(2).single_gap? assert_true gap_for(6).single_gap? end test "in case of '1 ... 5 6 7 ... 9'" do @window_options[:current_page] = 6 assert_false gap_for(2).single_gap? assert_false gap_for(4).single_gap? assert_true gap_for(8).single_gap? end end test '#out_of_range?' do # within range assert_false Kaminari::Helpers::Paginator::PageProxy.new({total_pages: 5}, 4, nil).out_of_range? # on last page assert_false Kaminari::Helpers::Paginator::PageProxy.new({total_pages: 5}, 5, nil).out_of_range? # out of range assert_true Kaminari::Helpers::Paginator::PageProxy.new({total_pages: 5}, 6, nil).out_of_range? end end end
ruby
MIT
55d6e40767442d206236d3718c5bdb32d01f2345
2026-01-04T15:38:55.939543Z
false
kaminari/kaminari
https://github.com/kaminari/kaminari/blob/55d6e40767442d206236d3718c5bdb32d01f2345/kaminari-core/test/helpers/paginator_tags_test.rb
kaminari-core/test/helpers/paginator_tags_test.rb
# frozen_string_literal: true require 'test_helper' if defined? ::Kaminari::Actionview class PaginatorTagsTest < ActionView::TestCase # A test paginator that can detect instantiated tags inside class TagSpy < Kaminari::Helpers::Paginator def initialize(*, **) super @tags = [] end def page_tag(page) @tags << page.to_i super end %w[first_page prev_page next_page last_page gap].each do |tag| eval <<-DEF, nil, __FILE__, __LINE__ + 1 def #{tag}_tag @tags << :#{tag} super end DEF end def partial_path 'kaminari/paginator' end def to_s super @tags end end def tags_for(collection, window: 4, outer_window: 0) view.paginate(collection, paginator_class: TagSpy, window: window, outer_window: outer_window, params: {controller: 'users', action: 'index'}) end teardown do User.delete_all end test '1 page in total' do 3.times {|i| User.create! name: "user#{i}"} assert_empty tags_for(User.page(1).per(3)) end sub_test_case 'when having 1 outer_window (and 1 inner window)' do def tags_for(collection, window: 1, outer_window: 1) super end test '10 pages in total' do 20.times {|i| User.create! name: "user#{i}"} assert_equal [1, 2, :gap, 10, :next_page, :last_page], tags_for(User.page(1).per(2)) assert_equal [:first_page, :prev_page, 1, 2, 3, :gap, 10, :next_page, :last_page], tags_for(User.page(2).per(2)) assert_equal [:first_page, :prev_page, 1, 2, 3, 4, :gap, 10, :next_page, :last_page], tags_for(User.page(3).per(2)) # the 3rd page doesn't become a gap because it's a single gap assert_equal [:first_page, :prev_page, 1, 2, 3, 4, 5, :gap, 10, :next_page, :last_page], tags_for(User.page(4).per(2)) assert_equal [:first_page, :prev_page, 1, :gap, 4, 5, 6, :gap, 10, :next_page, :last_page], tags_for(User.page(5).per(2)) assert_equal [:first_page, :prev_page, 1, :gap, 5, 6, 7, :gap, 10, :next_page, :last_page], tags_for(User.page(6).per(2)) # the 9th page doesn't become a gap because it's a single gap assert_equal [:first_page, :prev_page, 1, :gap, 6, 7, 8, 9, 10, :next_page, :last_page], tags_for(User.page(7).per(2)) assert_equal [:first_page, :prev_page, 1, :gap, 7, 8, 9, 10, :next_page, :last_page], tags_for(User.page(8).per(2)) assert_equal [:first_page, :prev_page, 1, :gap, 8, 9, 10, :next_page, :last_page], tags_for(User.page(9).per(2)) assert_equal [:first_page, :prev_page, 1, :gap, 9, 10], tags_for(User.page(10).per(2)) end end end end
ruby
MIT
55d6e40767442d206236d3718c5bdb32d01f2345
2026-01-04T15:38:55.939543Z
false
kaminari/kaminari
https://github.com/kaminari/kaminari/blob/55d6e40767442d206236d3718c5bdb32d01f2345/kaminari-core/test/helpers/helpers_test.rb
kaminari-core/test/helpers/helpers_test.rb
# frozen_string_literal: true require 'test_helper' class PaginatorHelperTest < ActiveSupport::TestCase include Kaminari::Helpers def template stub(r = Object.new) do render.with_any_args params { {} } options { {} } url_for {|h| "/foo?page=#{h[:page]}"} link_to { "<a href='#'>link</a>" } output_buffer { defined?(ActionView) ? ::ActionView::OutputBuffer.new : ::ActiveSupport::SafeBuffer.new } t { |*args, **kwargs| [args, kwargs] } end r end test 'view helper methods delegated to template' do paginator = Paginator.new(template, params: {}) assert_equal "<a href='#'>link</a>", paginator.link_to('link', '#') end test 'view helper methods delegated to template with kwargs work correctly' do paginator = Paginator.new(template, params: {}) assert_equal [['positional'], {keyword: :value}], paginator.t('positional', keyword: :value) end sub_test_case '#params' do setup do @paginator = Paginator.new(template, params: {controller: 'foo', action: 'bar'}) end test 'when params has no form params' do assert_equal({'controller' => 'foo', 'action' => 'bar'}, @paginator.page_tag(template).instance_variable_get('@params')) end test 'when params has form params' do stub(template).params do {authenticity_token: 'token', commit: 'submit', utf8: 'true', _method: 'patch'} end assert_equal({'controller' => 'foo', 'action' => 'bar'}, @paginator.page_tag(template).instance_variable_get('@params')) end end test '#param_name' do paginator = Paginator.new(template, param_name: :pagina) assert_equal :pagina, paginator.page_tag(template).instance_variable_get('@param_name') end end
ruby
MIT
55d6e40767442d206236d3718c5bdb32d01f2345
2026-01-04T15:38:55.939543Z
false
kaminari/kaminari
https://github.com/kaminari/kaminari/blob/55d6e40767442d206236d3718c5bdb32d01f2345/kaminari-core/test/models/array_test.rb
kaminari-core/test/models/array_test.rb
# frozen_string_literal: true require 'test_helper' class PaginatableArrayTest < ActiveSupport::TestCase setup do @array = Kaminari::PaginatableArray.new((1..100).to_a) end test 'initial state' do assert_equal 0, Kaminari::PaginatableArray.new.count end test 'specifying limit and offset when initializing' do assert_equal 3, Kaminari::PaginatableArray.new((1..100).to_a, limit: 10, offset: 20).current_page end sub_test_case '#page' do def assert_first_page_of_array(arr) assert_equal 25, arr.count assert_equal 1, arr.current_page assert_equal 1, arr.first end def assert_blank_array_page(arr) assert_equal 0, arr.count end test 'page 1' do assert_first_page_of_array @array.page(1) end test 'page 2' do arr = @array.page 2 assert_equal 25, arr.count assert_equal 2, arr.current_page assert_equal 26, arr.first end test 'page without an argument' do assert_first_page_of_array @array.page end test 'page < 1' do assert_first_page_of_array @array.page(0) end test 'page > max page' do assert_blank_array_page @array.page(5) end end sub_test_case '#per' do test 'page 1 per 5' do arr = @array.page(1).per(5) assert_equal 5, arr.count assert_equal 1, arr.first end test 'page 1 per 0' do assert_equal 0, @array.page(1).per(0).count end end sub_test_case '#padding' do test 'page 1 per 5 padding 1' do arr = @array.page(1).per(5).padding(1) assert_equal 5, arr.count assert_equal 2, arr.first end test 'page 1 per 5 padding "1" (as string)' do arr = @array.page(1).per(5).padding('1') assert_equal 5, arr.count assert_equal 2, arr.first end test 'page 19 per 5 padding 5' do arr = @array.page(19).per(5).padding(5) assert_equal 19, arr.current_page assert_equal 19, arr.total_pages end test 'per 25, padding 25' do assert_equal 3, @array.page(1).padding(25).total_pages end test 'Negative padding' do assert_raise(ArgumentError) { @array.page(1).per(5).padding(-1) } end end sub_test_case '#total_pages' do test 'per 25 (default)' do assert_equal 4, @array.page.total_pages end test 'per 7' do assert_equal 15, @array.page(2).per(7).total_pages end test 'per 65536' do assert_equal 1, @array.page(50).per(65536).total_pages end test 'per 0' do assert_raise(Kaminari::ZeroPerPageOperation) { @array.page(50).per(0).total_pages } end test 'per -1 (using default)' do assert_equal 4, @array.page(5).per(-1).total_pages end test 'per "String value that can not be converted into Number" (using default)' do assert_equal 4, @array.page(5).per('aho').total_pages end end sub_test_case '#current_page' do test 'any page, per 0' do assert_raise(Kaminari::ZeroPerPageOperation) { @array.page.per(0).current_page } end test 'page 1' do assert_equal 1, @array.page(1).current_page end test 'page 2' do assert_equal 2, @array.page(2).per(3).current_page end end sub_test_case '#next_page' do test 'page 1' do assert_equal 2, @array.page.next_page end test 'page 5' do assert_nil @array.page(5).next_page end end sub_test_case '#prev_page' do test 'page 1' do assert_nil @array.page.prev_page end test 'page 3' do assert_equal 2, @array.page(3).prev_page end test 'page 5' do assert_nil @array.page(5).prev_page end end sub_test_case '#count' do test 'page 1' do assert_equal 25, @array.page.count end test 'page 2' do assert_equal 25, @array.page(2).count end end sub_test_case 'when setting total count explicitly' do test 'array 1..10, page 5, per 10, total_count 9999' do arr = Kaminari::PaginatableArray.new((1..10).to_a, total_count: 9999).page(5).per(10) assert_equal 10, arr.count assert_equal 1, arr.first assert_equal 5, arr.current_page assert_equal 9999, arr.total_count end test 'array 1..15, page 1, per 10, total_count 15' do arr = Kaminari::PaginatableArray.new((1..15).to_a, total_count: 15).page(1).per(10) assert_equal 10, arr.count assert_equal 1, arr.first assert_equal 1, arr.current_page assert_equal 15, arr.total_count end test 'array 1..25, page 2, per 10, total_count 15' do arr = Kaminari::PaginatableArray.new((1..25).to_a, total_count: 15).page(2).per(10) assert_equal 5, arr.count assert_equal 11, arr.first assert_equal 2, arr.current_page assert_equal 15, arr.total_count end end end
ruby
MIT
55d6e40767442d206236d3718c5bdb32d01f2345
2026-01-04T15:38:55.939543Z
false
kaminari/kaminari
https://github.com/kaminari/kaminari/blob/55d6e40767442d206236d3718c5bdb32d01f2345/kaminari-core/test/models/configuration_methods_test.rb
kaminari-core/test/models/configuration_methods_test.rb
# frozen_string_literal: true require 'test_helper' class ConfigurationMethodsTest < ActiveSupport::TestCase sub_test_case '#default_per_page' do if defined? ActiveRecord test 'AR::Base should be not polluted by configuration methods' do assert_not_respond_to ActiveRecord::Base, :paginates_per end end test 'by default' do assert_equal 25, User.page(1).limit_value end test 'when configuring both on global and model-level' do Kaminari.configure {|c| c.default_per_page = 50 } User.paginates_per 100 assert_equal 100, User.page(1).limit_value end test 'when configuring multiple times' do Kaminari.configure {|c| c.default_per_page = 10 } Kaminari.configure {|c| c.default_per_page = 20 } assert_equal 20, User.page(1).limit_value end teardown do Kaminari.configure {|c| c.default_per_page = 25 } User.paginates_per nil end end sub_test_case '#max_per_page' do teardown do Kaminari.configure {|c| c.max_per_page = nil } User.max_paginates_per nil end if defined? ActiveRecord test 'AR::Base should be not polluted by configuration methods' do assert_not_respond_to ActiveRecord::Base, :max_paginates_per end end test 'by default' do assert_equal 1000, User.page(1).per(1000).limit_value end test 'when configuring both on global and model-level' do Kaminari.configure {|c| c.max_per_page = 50 } User.max_paginates_per 100 assert_equal 100, User.page(1).per(1000).limit_value end test 'when configuring multiple times' do Kaminari.configure {|c| c.max_per_page = 10 } Kaminari.configure {|c| c.max_per_page = 20 } assert_equal 20, User.page(1).per(1000).limit_value end end sub_test_case '#max_pages' do if defined? ActiveRecord test 'AR::Base should be not polluted by configuration methods' do assert_not_respond_to ActiveRecord::Base, :max_pages end end setup do 100.times do |count| User.create!(name: "User#{count}") end end teardown do Kaminari.configure {|c| c.max_pages = nil } User.max_pages nil User.delete_all end test 'by default' do assert_equal 20, User.page(1).per(5).total_pages end test 'when configuring both on global and model-level' do Kaminari.configure {|c| c.max_pages = 10 } User.max_pages 15 assert_equal 15, User.page(1).per(5).total_pages end test 'when configuring multiple times' do Kaminari.configure {|c| c.max_pages = 10 } Kaminari.configure {|c| c.max_pages = 15 } assert_equal 15, User.page(1).per(5).total_pages end end end
ruby
MIT
55d6e40767442d206236d3718c5bdb32d01f2345
2026-01-04T15:38:55.939543Z
false
kaminari/kaminari
https://github.com/kaminari/kaminari/blob/55d6e40767442d206236d3718c5bdb32d01f2345/kaminari-core/test/models/active_record/paginable_without_count_test.rb
kaminari-core/test/models/active_record/paginable_without_count_test.rb
# frozen_string_literal: true require 'test_helper' if defined? ActiveRecord class PaginableWithoutCountTest < ActiveSupport::TestCase def self.startup 26.times { User.create! } super end def self.shutdown User.delete_all super end test 'it does not make count queries after calling #each' do @scope = User.page(1).without_count @scope.each assert_no_queries do assert_not @scope.last_page? end assert_no_queries do assert_not @scope.out_of_range? end end test 'it does not make count queries after calling #last_page? or #out_of_range?' do @scope = User.page(1).without_count assert_not @scope.last_page? assert_not @scope.out_of_range? assert_no_queries { @scope.each } end test '#last_page? returns false when total count == 26 and page size == 25' do @users = User.page(1).without_count assert_equal 25, @users.size assert_equal 25, @users.each.size assert_not @users.last_page? assert_not @users.out_of_range? end test '#last_page? returns true when total count == page size' do @users = User.page(1).per(26).without_count assert_equal 26, @users.size assert_equal 26, @users.each.size assert @users.last_page? assert_not @users.out_of_range? end test '#last_page? returns true when total count == 26, page size == 25, and page == 2' do @users = User.page(2).without_count assert_equal 1, @users.size assert_equal 1, @users.each.size assert @users.last_page? assert_not @users.out_of_range? end test '#out_of_range? returns true when total count == 26, page size == 25, and page == 3' do @users = User.page(3).without_count assert_equal 0, @users.size assert_equal 0, @users.each.size assert_not @users.last_page? assert @users.out_of_range? end test 'it works when chained after `where`' do @scope = User.where.not(id: nil).page(1).without_count @scope.each assert_no_queries do assert_not @scope.last_page? end assert_no_queries do assert_not @scope.out_of_range? end end test 'regression: call arel first' do @users = User.page(1).without_count @users.arel assert_equal false, @users.last_page? end test 'regression: call last page first' do @users = User.page(1).without_count @users.last_page? @users.arel assert_equal false, @users.last_page? end def assert_no_queries subscriber = ActiveSupport::Notifications.subscribe 'sql.active_record' do raise 'A SQL query is being made to the db:' end yield ensure ActiveSupport::Notifications.unsubscribe subscriber end end end
ruby
MIT
55d6e40767442d206236d3718c5bdb32d01f2345
2026-01-04T15:38:55.939543Z
false
kaminari/kaminari
https://github.com/kaminari/kaminari/blob/55d6e40767442d206236d3718c5bdb32d01f2345/kaminari-core/test/models/active_record/inherited_test.rb
kaminari-core/test/models/active_record/inherited_test.rb
# frozen_string_literal: true require 'test_helper' if defined? ActiveRecord class ActiveRecordModelExtensionTest < ActiveSupport::TestCase test 'An AR model responds to Kaminari defined methods' do assert_respond_to Class.new(ActiveRecord::Base), :page end test "Kaminari doesn't prevent other AR extension gems to define a method" do assert_respond_to Class.new(ActiveRecord::Base), :fake_gem_defined_method end end end
ruby
MIT
55d6e40767442d206236d3718c5bdb32d01f2345
2026-01-04T15:38:55.939543Z
false
kaminari/kaminari
https://github.com/kaminari/kaminari/blob/55d6e40767442d206236d3718c5bdb32d01f2345/kaminari-core/test/models/active_record/scopes_test.rb
kaminari-core/test/models/active_record/scopes_test.rb
# frozen_string_literal: true require 'test_helper' if defined? ActiveRecord class ActiveRecordModelExtensionTest < ActiveSupport::TestCase test 'Changing page_method_name' do begin Kaminari.configure {|config| config.page_method_name = :per_page_kaminari } model = Class.new ActiveRecord::Base assert_respond_to model, :per_page_kaminari assert_not_respond_to model, :page ensure Kaminari.configure {|config| config.page_method_name = :page } end end end class ActiveRecordExtensionTest < ActiveSupport::TestCase def assert_first_page(relation) assert_equal 25, relation.count assert_equal 'user001', relation.first.name end def assert_blank_page(relation) assert_equal 0, relation.count end class << self def startup [User, GemDefinedModel, Device].each do |m| 1.upto(100) {|i| m.create! name: "user#{'%03d' % i}", age: (i / 10)} end super end def shutdown [User, GemDefinedModel, Device].each(&:delete_all) super end end [User, Admin, GemDefinedModel, Device].each do |model_class| sub_test_case "for #{model_class}" do sub_test_case '#page' do test 'page 1' do assert_first_page model_class.page(1) end test 'page 2' do relation = model_class.page 2 assert_equal 25, relation.count assert_equal 'user026', relation.first.name end test 'page without an argument' do assert_first_page model_class.page end test 'page < 1' do assert_first_page model_class.page(0) end test 'page > max page' do assert_blank_page model_class.page(5) end test 'invalid page as a Hash' do assert_first_page model_class.page(page: { hacked: 100 }) end test 'invalid page as a Array' do assert_first_page model_class.page(page: [2, 3]) end test 'ensure #order_values is preserved' do relation = model_class.order('id').page 1 assert_equal ['id'], relation.order_values.uniq end end sub_test_case '#per' do test 'page 1 per 5' do relation = model_class.page(1).per(5) assert_equal 5, relation.count assert_equal 'user001', relation.first.name end test 'page 1 per 5 with max_per_page < 5' do begin model_class.max_paginates_per 4 relation = model_class.page(1).per(5) assert_equal 4, relation.count ensure model_class.max_paginates_per nil end end test 'page 1 per nil (using default)' do assert_equal model_class.default_per_page, model_class.page(1).per(nil).count end test 'page 1 per nil with max_per_page > default_per_page' do begin model_class.max_paginates_per(30) assert_equal 25, model_class.page(1).per(nil).count ensure model_class.max_paginates_per(nil) end end test 'page 1 per nil with max_per_page < default_per_page' do begin model_class.max_paginates_per(10) assert_equal 10, model_class.page(1).per(nil).count ensure model_class.max_paginates_per(nil) end end test 'page 1 per 0' do assert_equal 0, model_class.page(1).per(0).count end # I know it's a bit strange to have this here, but I couldn't find any better place for this case sub_test_case 'when max_per_page is given via model class, and `per` is not actually called' do test 'with max_per_page > default_per_page' do begin model_class.max_paginates_per(200) assert_equal 25, model_class.page(1).count ensure model_class.max_paginates_per(nil) end end test 'with max_per_page < default_per_page' do begin model_class.max_paginates_per(5) assert_equal 5, model_class.page(1).count ensure model_class.max_paginates_per(nil) end end end end sub_test_case '#max_paginates_per' do setup do model_class.max_paginates_per(10) end teardown do model_class.max_paginates_per(nil) end sub_test_case 'calling max_paginates_per() after per()' do test 'when #max_paginates_per is greater than #per' do assert_equal 15, model_class.page(1).per(15).max_paginates_per(20).count end test 'when #per is greater than #max_paginates_per' do assert_equal 20, model_class.page(1).per(30).max_paginates_per(20).count end test 'when nil is given to #per and #max_paginates_per is specified' do assert_equal 20, model_class.page(1).per(nil).max_paginates_per(20).count end end sub_test_case 'calling max_paginates_per() before per()' do test 'when #max_paginates_per is greater than #per' do assert_equal 15, model_class.page(1).max_paginates_per(20).per(15).count end test 'when #per is greater than #max_paginates_per' do assert_equal 20, model_class.page(1).max_paginates_per(20).per(30).count end test 'when nil is given to #per and #max_paginates_per is specified' do assert_equal 20, model_class.page(1).max_paginates_per(20).per(nil).count end end sub_test_case 'calling max_paginates_per() without per()' do test 'when #max_paginates_per is greater than the default per_page' do assert_equal 20, model_class.page(1).max_paginates_per(20).count end test 'when #max_paginates_per is less than the default per_page' do assert_equal 25, model_class.page(1).max_paginates_per(30).count end end end sub_test_case '#padding' do test 'page 1 per 5 padding 1' do relation = model_class.page(1).per(5).padding(1) assert_equal 5, relation.count assert_equal 'user002', relation.first.name end test 'page 1 per 5 padding "1" (as string)' do relation = model_class.page(1).per(5).padding('1') assert_equal 5, relation.count assert_equal 'user002', relation.first.name end test 'page 19 per 5 padding 5' do relation = model_class.page(19).per(5).padding(5) assert_equal 19, relation.current_page assert_equal 19, relation.total_pages end test 'Negative padding' do assert_raise(ArgumentError) { model_class.page(1).per(5).padding(-1) } end end sub_test_case '#total_pages' do test 'per 25 (default)' do assert_equal 4, model_class.page.total_pages end test 'per 7' do assert_equal 15, model_class.page(2).per(7).total_pages end test 'per 65536' do assert_equal 1, model_class.page(50).per(65536).total_pages end test 'per 0' do assert_raise Kaminari::ZeroPerPageOperation do model_class.page(50).per(0).total_pages end end test 'per -1 (using default)' do assert_equal 4, model_class.page(5).per(-1).total_pages end test 'per "String value that can not be converted into Number" (using default)' do assert_equal 4, model_class.page(5).per('aho').total_pages end test 'with max_pages < total pages count from database' do begin model_class.max_pages 3 assert_equal 3, model_class.page.total_pages ensure model_class.max_pages nil end end test 'with max_pages > total pages count from database' do begin model_class.max_pages 11 assert_equal 4, model_class.page.total_pages ensure model_class.max_pages nil end end test 'with max_pages is nil (default)' do model_class.max_pages nil assert_equal 4, model_class.page.total_pages end test 'with per(nil) using default' do assert_equal 4, model_class.page.per(nil).total_pages end end sub_test_case '#current_page' do test 'any page, per 0' do assert_raise Kaminari::ZeroPerPageOperation do model_class.page.per(0).current_page end end test 'page 1' do assert_equal 1, model_class.page.current_page end test 'page 2' do assert_equal 2, model_class.page(2).per(3).current_page end end sub_test_case '#current_per_page' do test 'per 0' do assert_equal 0, model_class.page.per(0).current_per_page end test 'no per specified' do assert_equal model_class.default_per_page, model_class.page.current_per_page end test 'per specified as 42' do assert_equal 42, model_class.page.per(42).current_per_page end end sub_test_case '#next_page' do test 'page 1' do assert_equal 2, model_class.page.next_page end test 'page 5' do assert_nil model_class.page(5).next_page end end sub_test_case '#prev_page' do test 'page 1' do assert_nil model_class.page.prev_page end test 'page 3' do assert_equal 2, model_class.page(3).prev_page end test 'page 5' do assert_nil model_class.page(5).prev_page end end sub_test_case '#first_page?' do test 'on first page' do assert_true model_class.page(1).per(10).first_page? end test 'not on first page' do assert_false model_class.page(5).per(10).first_page? end end sub_test_case '#last_page?' do test 'on last page' do assert_true model_class.page(10).per(10).last_page? end test 'within range' do assert_false model_class.page(1).per(10).last_page? end test 'out of range' do assert_false model_class.page(11).per(10).last_page? end end sub_test_case '#out_of_range?' do test 'on last page' do assert_false model_class.page(10).per(10).out_of_range? end test 'within range' do assert_false model_class.page(1).per(10).out_of_range? end test 'out of range' do assert_true model_class.page(11).per(10).out_of_range? end end sub_test_case '#count' do test 'page 1' do assert_equal 25, model_class.page.count end test 'page 2' do assert_equal 25, model_class.page(2).count end end test 'chained with .group' do relation = model_class.group('age').page(2).per 5 # 0..10 assert_equal 11, relation.total_count assert_equal 3, relation.total_pages end test 'activerecord descendants' do assert_not_equal 0, ActiveRecord::Base.descendants.length end end end end end
ruby
MIT
55d6e40767442d206236d3718c5bdb32d01f2345
2026-01-04T15:38:55.939543Z
false
kaminari/kaminari
https://github.com/kaminari/kaminari/blob/55d6e40767442d206236d3718c5bdb32d01f2345/kaminari-core/test/models/active_record/active_record_relation_methods_test.rb
kaminari-core/test/models/active_record/active_record_relation_methods_test.rb
# frozen_string_literal: true require 'test_helper' if defined? ActiveRecord class ActiveRecordRelationMethodsTest < ActiveSupport::TestCase sub_test_case '#total_count' do setup do @author = User.create! name: 'author' @author2 = User.create! name: 'author2' @author3 = User.create! name: 'author3' @books = 2.times.map {|i| @author.books_authored.create!(title: "title%03d" % i) } @books2 = 3.times.map {|i| @author2.books_authored.create!(title: "title%03d" % i) } @books3 = 4.times.map {|i| @author3.books_authored.create!(title: "subject%03d" % i) } @readers = 4.times.map { User.create! name: 'reader' } @books.each {|book| book.readers << @readers } end teardown do Book.delete_all User.delete_all Readership.delete_all end test 'total_count on not yet loaded Relation' do assert_equal 0, User.where('1 = 0').page(1).total_count assert_equal 0, User.where('1 = 0').page(1).per(10).total_count assert_equal 7, User.page(1).total_count assert_equal 7, User.page(1).per(10).total_count assert_equal 7, User.page(2).total_count assert_equal 7, User.page(2).per(10).total_count assert_equal 7, User.page(2).per(2).total_count end test 'total_count on loaded Relation' do assert_equal 0, User.where('1 = 0').page(1).load.total_count assert_equal 0, User.where('1 = 0').page(1).per(10).load.total_count assert_equal 7, User.page(1).load.total_count assert_equal 7, User.page(1).per(10).load.total_count assert_equal 7, User.page(2).load.total_count assert_equal 7, User.page(2).per(10).load.total_count assert_equal 7, User.page(2).per(2).load.total_count assert_equal 7, User.page(1).per(2).padding(6).load.total_count old_max_per_page = User.max_per_page User.max_paginates_per(5) assert_equal 7, User.page(1).per(100).load.total_count assert_equal 7, User.page(2).per(100).load.total_count User.max_paginates_per(old_max_per_page) end test 'it should reset total_count memoization when the scope is cloned' do assert_equal 1, User.page.tap(&:total_count).where(name: 'author').total_count end test 'it should successfully count the results when the scope includes an order which references a generated column' do assert_equal @readers.size, @author.readers.by_read_count.page(1).total_count end test 'it should keep includes and successfully count the results when the scope use conditions on includes' do # Only @author and @author2 have books titled with the title00x pattern assert_equal 2, User.includes(:books_authored).references(:books).where("books.title LIKE 'title00%'").page(1).total_count end test 'when the Relation has custom select clause' do assert_nothing_raised do User.select('*, 1 as one').page(1).total_count end end test 'it should ignore the options for rails 4.1+ when total_count receives options' do assert_equal 7, User.page(1).total_count(:name, distinct: true) end test 'it should not throw exception by passing options to count when the scope returns an ActiveSupport::OrderedHash' do assert_nothing_raised do @author.readers.by_read_count.page(1).total_count(:name, distinct: true) end end test "it counts the number of rows, not the number of keys, with an alias field" do @books.each {|book| book.readers << @readers[0..1] } assert_equal 8, Readership.select('user_id, count(user_id) as read_count, book_id').group(:user_id, :book_id).page(1).total_count end test "it counts the number of rows, not the number of keys without an alias field" do @books.each {|book| book.readers << @readers[0..1] } assert_equal 8, Readership.select('user_id, count(user_id), book_id').group(:user_id, :book_id).page(1).total_count end test "throw an exception when calculating total_count when the query includes column aliases used by a group-by clause" do assert_equal 3, Book.joins(authorships: :user).select("users.name as author_name").group('users.name').page(1).total_count end test 'total_count is calculable with page 1 per "5" (the string)' do assert_equal 7, User.page(1).per('5').load.total_count end test 'calculating total_count with GROUP BY ... HAVING clause' do assert_equal 2, Authorship.group(:user_id).having("COUNT(book_id) >= 3").page(1).total_count end test 'calculating total_count with GROUP BY ... HAVING clause with model that has default scope' do assert_equal 2, CurrentAuthorship.group(:user_id).having("COUNT(book_id) >= 3").page(1).total_count end test 'calculating STI total_count with GROUP BY clause' do [ ['Fenton', Dog], ['Bob', Dog], ['Garfield', Cat], ['Bob', Cat], ['Caine', Insect] ].each { |name, type| type.create!(name: name) } assert_equal 3, Mammal.group(:name).page(1).total_count end test 'total_count with max_pages does not add LIMIT' do begin subscriber = ActiveSupport::Notifications.subscribe 'sql.active_record' do |_, __, ___, ____, payload| assert_not_match(/LIMIT/, payload[:sql]) end assert_equal 7, User.page.total_count ensure ActiveSupport::Notifications.unsubscribe subscriber end end test 'total_count with max_pages adds "LIMIT (max_pages * per_page)" to the count query' do begin subscriber = ActiveSupport::Notifications.subscribe 'sql.active_record' do |_, __, ___, ____, payload| assert_match(/LIMIT/, payload[:sql]) end User.max_pages 10 assert_equal 7, User.page.total_count ensure User.max_pages nil ActiveSupport::Notifications.unsubscribe subscriber end end end end end
ruby
MIT
55d6e40767442d206236d3718c5bdb32d01f2345
2026-01-04T15:38:55.939543Z
false
kaminari/kaminari
https://github.com/kaminari/kaminari/blob/55d6e40767442d206236d3718c5bdb32d01f2345/kaminari-core/test/generators/views_generator_test.rb
kaminari-core/test/generators/views_generator_test.rb
# frozen_string_literal: true require 'test_helper' if defined?(::Rails::Railtie) && ENV['GENERATOR_SPEC'] require 'rails/generators' require 'generators/kaminari/views_generator' class GitHubApiHelperTest < ::Test::Unit::TestCase test '.get_files_in_master' do assert_include Kaminari::Generators::GitHubApiHelper.get_files_in_master, %w(README.md 7f712676aac6bcd912981a9189c110303a1ee266) end test '.get_content_for' do assert Kaminari::Generators::GitHubApiHelper.get_content_for('README.md').start_with?('# ') end end end
ruby
MIT
55d6e40767442d206236d3718c5bdb32d01f2345
2026-01-04T15:38:55.939543Z
false
kaminari/kaminari
https://github.com/kaminari/kaminari/blob/55d6e40767442d206236d3718c5bdb32d01f2345/kaminari-core/test/config/config_test.rb
kaminari-core/test/config/config_test.rb
# frozen_string_literal: true require 'test_helper' class ConfigurationTest < ::Test::Unit::TestCase sub_test_case 'default_per_page' do test 'by default' do assert_equal 25, Kaminari.config.default_per_page end test 'configured via config block' do begin Kaminari.configure {|c| c.default_per_page = 17} assert_equal 17, Kaminari.config.default_per_page ensure Kaminari.configure {|c| c.default_per_page = 25} end end end sub_test_case 'max_per_page' do test 'by default' do assert_nil Kaminari.config.max_per_page end test 'configure via config block' do begin Kaminari.configure {|c| c.max_per_page = 100} assert_equal 100, Kaminari.config.max_per_page ensure Kaminari.configure {|c| c.max_per_page = nil} end end end sub_test_case 'window' do test 'by default' do assert_equal 4, Kaminari.config.window end end sub_test_case 'outer_window' do test 'by default' do assert_equal 0, Kaminari.config.outer_window end end sub_test_case 'left' do test 'by default' do assert_equal 0, Kaminari.config.left end end sub_test_case 'right' do test 'by default' do assert_equal 0, Kaminari.config.right end end sub_test_case 'param_name' do test 'by default' do assert_equal :page, Kaminari.config.param_name end test 'configured via config block' do begin Kaminari.configure {|c| c.param_name = -> { :test } } assert_equal :test, Kaminari.config.param_name ensure Kaminari.configure {|c| c.param_name = :page } end end end sub_test_case 'max_pages' do test 'by default' do assert_nil Kaminari.config.max_pages end test 'configure via config block' do begin Kaminari.configure {|c| c.max_pages = 5} assert_equal 5, Kaminari.config.max_pages ensure Kaminari.configure {|c| c.max_pages = nil} end end end sub_test_case 'params_on_first_page' do test 'by default' do assert_equal false, Kaminari.config.params_on_first_page end test 'configure via config block' do begin Kaminari.configure {|c| c.params_on_first_page = true } assert_equal true, Kaminari.config.params_on_first_page ensure Kaminari.configure {|c| c.params_on_first_page = false } end end end end
ruby
MIT
55d6e40767442d206236d3718c5bdb32d01f2345
2026-01-04T15:38:55.939543Z
false
kaminari/kaminari
https://github.com/kaminari/kaminari/blob/55d6e40767442d206236d3718c5bdb32d01f2345/kaminari-core/test/fake_app/rails_app.rb
kaminari-core/test/fake_app/rails_app.rb
# frozen_string_literal: true # require 'rails/all' require 'action_controller/railtie' require 'action_view/railtie' require 'active_record/railtie' if defined? ActiveRecord # config class KaminariTestApp < Rails::Application config.load_defaults "#{Rails::VERSION::MAJOR}.#{Rails::VERSION::MINOR}" if config.respond_to? :load_defaults config.secret_key_base = config.secret_token = '3b7cd727ee24e8444053437c36cc66c4' config.session_store :cookie_store, key: '_myapp_session' config.active_support.deprecation = :log config.eager_load = false # Rails.root config.root = File.dirname(__FILE__) config.active_record.belongs_to_required_by_default = false if (Rails::VERSION::MAJOR >= 5) && defined?(ActiveRecord) end Rails.backtrace_cleaner.remove_silencers! Rails.application.initialize! # routes Rails.application.routes.draw do resources :users do get 'index_text(.:format)', action: :index_text, on: :collection end resources :addresses do get 'page/:page', action: :index, on: :collection end end #models require 'fake_app/active_record/models' if defined? ActiveRecord # controllers class ApplicationController < ActionController::Base; end class UsersController < ApplicationController def index @users = User.page params[:page] render inline: <<-ERB <%= @users.map(&:name).join("\n") %> <%= link_to_previous_page @users, 'previous page', class: 'prev' %> <%= link_to_next_page @users, 'next page', class: 'next' %> <%= paginate @users %> <div class="info"><%= page_entries_info @users %></div> ERB end def index_text @users = User.page params[:page] end end if defined? ActiveRecord class AddressesController < ApplicationController def index @addresses = User::Address.page params[:page] render inline: <<-ERB <%= @addresses.map(&:street).join("\n") %> <%= paginate @addresses %> ERB end end end # helpers Object.const_set(:ApplicationHelper, Module.new)
ruby
MIT
55d6e40767442d206236d3718c5bdb32d01f2345
2026-01-04T15:38:55.939543Z
false
kaminari/kaminari
https://github.com/kaminari/kaminari/blob/55d6e40767442d206236d3718c5bdb32d01f2345/kaminari-core/test/fake_app/active_record/models.rb
kaminari-core/test/fake_app/active_record/models.rb
# frozen_string_literal: true # models class User < ActiveRecord::Base has_many :authorships has_many :readerships has_many :books_authored, through: :authorships, source: :book has_many :books_read, through: :readerships, source: :book has_many :addresses, class_name: 'User::Address' def readers User.joins(books_read: :authors).where(authors_books: {id: self}) end scope :by_name, -> { order(:name) } scope :by_read_count, -> { cols = if connection.adapter_name == "PostgreSQL" column_names.map { |column| %{"users"."#{column}"} } else ['users.id'] end group(*cols).select("count(readerships.id) AS read_count, #{cols.join(', ')}").order('read_count DESC') } end class Authorship < ActiveRecord::Base belongs_to :user belongs_to :book end class CurrentAuthorship < ActiveRecord::Base self.table_name = 'authorships' belongs_to :user belongs_to :book default_scope -> { where(deleted_at: nil) } end class Readership < ActiveRecord::Base belongs_to :user belongs_to :book end class Book < ActiveRecord::Base has_many :authorships has_many :readerships has_many :authors, through: :authorships, source: :user has_many :readers, through: :readerships, source: :user end # a model that is a descendant of AR::Base but doesn't directly inherit AR::Base class Admin < User end # a model with namespace class User::Address < ActiveRecord::Base belongs_to :user end class Animal < ActiveRecord::Base; end class Mammal < Animal; end class Dog < Mammal; end class Cat < Mammal; end class Insect < Animal; end # a class that uses abstract class class Product < ActiveRecord::Base self.abstract_class = true end class Device < Product end # migrations ActiveRecord::Migration.verbose = false ActiveRecord::Tasks::DatabaseTasks.root = Dir.pwd ActiveRecord::Tasks::DatabaseTasks.drop_current 'test' ActiveRecord::Tasks::DatabaseTasks.create_current 'test' class CreateAllTables < ActiveRecord::VERSION::MAJOR >= 5 ? ActiveRecord::Migration[5.0] : ActiveRecord::Migration def self.up create_table(:gem_defined_models) { |t| t.string :name; t.integer :age } create_table(:users) {|t| t.string :name; t.integer :age} create_table(:books) {|t| t.string :title} create_table(:readerships) {|t| t.integer :user_id; t.integer :book_id } create_table(:authorships) {|t| t.integer :user_id; t.integer :book_id; t.datetime :deleted_at } create_table(:user_addresses) {|t| t.string :street; t.integer :user_id } create_table(:devices) {|t| t.string :name; t.integer :age} create_table(:animals) {|t| t.string :type; t.string :name} end end CreateAllTables.up
ruby
MIT
55d6e40767442d206236d3718c5bdb32d01f2345
2026-01-04T15:38:55.939543Z
false
kaminari/kaminari
https://github.com/kaminari/kaminari/blob/55d6e40767442d206236d3718c5bdb32d01f2345/kaminari-core/lib/generators/kaminari/config_generator.rb
kaminari-core/lib/generators/kaminari/config_generator.rb
# frozen_string_literal: true module Kaminari module Generators # rails g kaminari:config class ConfigGenerator < Rails::Generators::Base # :nodoc: source_root File.expand_path(File.join(File.dirname(__FILE__), 'templates')) desc <<DESC Description: Copies Kaminari configuration file to your application's initializer directory. DESC def copy_config_file template 'kaminari_config.rb', 'config/initializers/kaminari_config.rb' end end end end
ruby
MIT
55d6e40767442d206236d3718c5bdb32d01f2345
2026-01-04T15:38:55.939543Z
false
kaminari/kaminari
https://github.com/kaminari/kaminari/blob/55d6e40767442d206236d3718c5bdb32d01f2345/kaminari-core/lib/generators/kaminari/views_generator.rb
kaminari-core/lib/generators/kaminari/views_generator.rb
# frozen_string_literal: true module Kaminari module Generators # rails g kaminari:views THEME class ViewsGenerator < Rails::Generators::NamedBase # :nodoc: source_root File.expand_path('../../../../app/views/kaminari', __FILE__) class_option :template_engine, type: :string, aliases: '-e', desc: 'Template engine for the views. Available options are "erb", "haml", and "slim".' class_option :views_prefix, type: :string, desc: 'Prefix for path to put views in.' class << self def banner #:nodoc: <<-BANNER.chomp rails g kaminari:views THEME [options] Copies all paginator partial templates to your application. You can choose a template THEME by specifying one from the list below: - default The default one. This one is used internally while you don't override the partials. #{themes.map {|t| " - #{t.name}\n#{t.description}"}.join("\n")} BANNER end private def themes @themes ||= GitHubApiHelper.get_files_in_master.group_by {|fn, _| fn[0...(fn.index('/') || 0)]}.delete_if {|fn, _| fn.blank?}.map do |name, files| Theme.new name, files end rescue SocketError [] end end desc '' def copy_or_fetch #:nodoc: return copy_default_views if file_name == 'default' if (theme = self.class.themes.detect {|t| t.name == file_name}) if download_templates(theme).empty? say "template_engine: #{template_engine} is not available for theme: #{file_name}" end else say "no such theme: #{file_name}\n available themes: #{self.class.themes.map(&:name).join ', '}" end end private def download_templates(theme) theme.templates_for(template_engine).each do |template| say " downloading #{template.name} from kaminari_themes..." create_file view_path_for(template.name), GitHubApiHelper.get_content_for("#{theme.name}/#{template.name}") end end def copy_default_views filename_pattern = File.join self.class.source_root, "*.html.#{template_engine}" Dir.glob(filename_pattern).map {|f| File.basename f}.each do |f| copy_file f, view_path_for(f) end end def view_path_for(file) ['app', 'views', views_prefix, 'kaminari', File.basename(file)].compact.join('/') end def views_prefix options[:views_prefix].try(:to_s) end def template_engine engine = options[:template_engine].try(:to_s).try(:downcase) if engine == 'haml' || engine == 'slim' Kaminari.deprecator.warn 'The -e option is deprecated and will be removed in the near future. Please use the html2slim gem or the html2haml gem ' \ 'to convert erb templates manually.' end engine || 'erb' end end Template = Struct.new(:name, :sha) do def description? name == 'DESCRIPTION' end def view? name =~ /^app\/views\// end def engine #:nodoc: File.extname(name).sub(/^\./, '') end end class Theme attr_accessor :name def initialize(name, templates) #:nodoc: @name, @templates = name, templates.map {|fn, sha| Template.new fn.sub(/^#{name}\//, ''), sha} end def description #:nodoc: file = @templates.detect(&:description?) return "#{' ' * 12}#{name}" unless file GitHubApiHelper.get_content_for("#{@name}/#{file.name}").chomp.gsub(/^/, ' ' * 12) end def templates_for(template_engine) #:nodoc: @templates.select {|t| t.engine == template_engine } end end module GitHubApiHelper require 'open-uri' def get_files_in_master master_tree_sha = URI.open('https://api.github.com/repos/amatsuda/kaminari_themes/git/refs/heads/master') do |json| ActiveSupport::JSON.decode(json.read)['object']['sha'] end URI.parse("https://api.github.com/repos/amatsuda/kaminari_themes/git/trees/#{master_tree_sha}?recursive=1").open do |json| blobs = ActiveSupport::JSON.decode(json.read)['tree'].find_all {|i| i['type'] == 'blob' } blobs.map do |blob| [blob['path'], blob['sha']] end end end module_function :get_files_in_master def get_content_for(path) URI.parse("https://api.github.com/repos/amatsuda/kaminari_themes/contents/#{path}").open do |json| Base64.decode64(ActiveSupport::JSON.decode(json.read)['content']) end end module_function :get_content_for end end end
ruby
MIT
55d6e40767442d206236d3718c5bdb32d01f2345
2026-01-04T15:38:55.939543Z
false
kaminari/kaminari
https://github.com/kaminari/kaminari/blob/55d6e40767442d206236d3718c5bdb32d01f2345/kaminari-core/lib/generators/kaminari/templates/kaminari_config.rb
kaminari-core/lib/generators/kaminari/templates/kaminari_config.rb
# frozen_string_literal: true Kaminari.configure do |config| # config.default_per_page = 25 # config.max_per_page = nil # config.window = 4 # config.outer_window = 0 # config.left = 0 # config.right = 0 # config.page_method_name = :page # config.param_name = :page # config.max_pages = nil # config.params_on_first_page = false end
ruby
MIT
55d6e40767442d206236d3718c5bdb32d01f2345
2026-01-04T15:38:55.939543Z
false
kaminari/kaminari
https://github.com/kaminari/kaminari/blob/55d6e40767442d206236d3718c5bdb32d01f2345/kaminari-core/lib/kaminari/core.rb
kaminari-core/lib/kaminari/core.rb
# frozen_string_literal: true module Kaminari def self.deprecator @deprecator ||= ActiveSupport::Deprecation.new("2.0", "kaminari-core") end end # load Rails/Railtie begin require 'rails' rescue LoadError #do nothing end # load Kaminari components require 'kaminari/config' require 'kaminari/exceptions' require 'kaminari/helpers/paginator' require 'kaminari/helpers/helper_methods' require 'kaminari/models/page_scope_methods' require 'kaminari/models/configuration_methods' require 'kaminari/models/array_extension' if defined? ::Rails::Railtie require 'kaminari/railtie' require 'kaminari/engine' end
ruby
MIT
55d6e40767442d206236d3718c5bdb32d01f2345
2026-01-04T15:38:55.939543Z
false
kaminari/kaminari
https://github.com/kaminari/kaminari/blob/55d6e40767442d206236d3718c5bdb32d01f2345/kaminari-core/lib/kaminari/exceptions.rb
kaminari-core/lib/kaminari/exceptions.rb
# frozen_string_literal: true module Kaminari class ZeroPerPageOperation < ZeroDivisionError; end end
ruby
MIT
55d6e40767442d206236d3718c5bdb32d01f2345
2026-01-04T15:38:55.939543Z
false
kaminari/kaminari
https://github.com/kaminari/kaminari/blob/55d6e40767442d206236d3718c5bdb32d01f2345/kaminari-core/lib/kaminari/railtie.rb
kaminari-core/lib/kaminari/railtie.rb
# frozen_string_literal: true module Kaminari class Railtie < ::Rails::Railtie #:nodoc: # Doesn't actually do anything. Just keeping this hook point, mainly for compatibility initializer 'kaminari' do end end end
ruby
MIT
55d6e40767442d206236d3718c5bdb32d01f2345
2026-01-04T15:38:55.939543Z
false
kaminari/kaminari
https://github.com/kaminari/kaminari/blob/55d6e40767442d206236d3718c5bdb32d01f2345/kaminari-core/lib/kaminari/config.rb
kaminari-core/lib/kaminari/config.rb
# frozen_string_literal: true module Kaminari # Configures global settings for Kaminari # Kaminari.configure do |config| # config.default_per_page = 10 # end class << self def configure yield config end def config @_config ||= Config.new end end class Config attr_accessor :default_per_page, :max_per_page, :window, :outer_window, :left, :right, :page_method_name, :max_pages, :params_on_first_page attr_writer :param_name def initialize @default_per_page = 25 @max_per_page = nil @window = 4 @outer_window = 0 @left = 0 @right = 0 @page_method_name = :page @param_name = :page @max_pages = nil @params_on_first_page = false end # If param_name was given as a callable object, call it when returning def param_name @param_name.respond_to?(:call) ? @param_name.call : @param_name end end end
ruby
MIT
55d6e40767442d206236d3718c5bdb32d01f2345
2026-01-04T15:38:55.939543Z
false
kaminari/kaminari
https://github.com/kaminari/kaminari/blob/55d6e40767442d206236d3718c5bdb32d01f2345/kaminari-core/lib/kaminari/engine.rb
kaminari-core/lib/kaminari/engine.rb
# frozen_string_literal: true module Kaminari #:nodoc: class Engine < ::Rails::Engine #:nodoc: initializer :deprecator do |app| app.deprecators[:kaminari] = Kaminari.deprecator if app.respond_to?(:deprecators) end end end
ruby
MIT
55d6e40767442d206236d3718c5bdb32d01f2345
2026-01-04T15:38:55.939543Z
false
kaminari/kaminari
https://github.com/kaminari/kaminari/blob/55d6e40767442d206236d3718c5bdb32d01f2345/kaminari-core/lib/kaminari/helpers/helper_methods.rb
kaminari-core/lib/kaminari/helpers/helper_methods.rb
# frozen_string_literal: true module Kaminari module Helpers # The Kaminari::Helpers::UrlHelper module provides useful methods for # generating a path or url to a particular page. A class must implement the # following methods: # # * <tt>url_for</tt>: A method that generates an actual path # * <tt>params</tt>: A method that returns query string parameters # * <tt>request</tt>: A method that returns a Rack::Request object # # A normal Rails controller implements all the methods, which make it # trivial to use this module: # # ==== Examples # # class UsersController < ApplicationController # include Kaminari::Helpers::UrlHelper # # def index # @users = User.page(1) # # path_to_next_page(@items) # # => /items?page=2 # end # end # module UrlHelper # A helper that calculates the url to the next page. # # ==== Examples # Basic usage: # # <%= next_page_url @items %> # #-> http://www.example.org/items?page=2 # # It will return `nil` if there is no next page. def next_page_url(scope, options = {}) "#{request.base_url}#{next_page_path(scope, options)}" if scope.next_page end alias url_to_next_page next_page_url def path_to_next_url(scope, options = {}) Kaminari.deprecator.warn 'path_to_next_url is deprecated. Use next_page_url or url_to_next_page instead.' next_page_url(scope, options) end # A helper that calculates the url to the previous page. # # ==== Examples # Basic usage: # # <%= prev_page_url @items %> # #-> http://www.example.org/items # # It will return `nil` if there is no previous page. def prev_page_url(scope, options = {}) "#{request.base_url}#{prev_page_path(scope, options)}" if scope.prev_page end alias previous_page_url prev_page_url alias url_to_prev_page prev_page_url alias url_to_previous_page prev_page_url # A helper that calculates the path to the next page. # # ==== Examples # Basic usage: # # <%= path_to_next_page @items %> # #-> /items?page=2 # # It will return `nil` if there is no next page. def next_page_path(scope, options = {}) Kaminari::Helpers::NextPage.new(self, **options.reverse_merge(current_page: scope.current_page)).url if scope.next_page end alias path_to_next_page next_page_path # A helper that calculates the path to the previous page. # # ==== Examples # Basic usage: # # <%= path_to_prev_page @items %> # #-> /items # # It will return `nil` if there is no previous page. def prev_page_path(scope, options = {}) Kaminari::Helpers::PrevPage.new(self, **options.reverse_merge(current_page: scope.current_page)).url if scope.prev_page end alias previous_page_path prev_page_path alias path_to_previous_page prev_page_path alias path_to_prev_page prev_page_path end module HelperMethods include UrlHelper # A helper that renders the pagination links. # # <%= paginate @articles %> # # ==== Options # * <tt>:window</tt> - The "inner window" size (4 by default). # * <tt>:outer_window</tt> - The "outer window" size (0 by default). # * <tt>:left</tt> - The "left outer window" size (0 by default). # * <tt>:right</tt> - The "right outer window" size (0 by default). # * <tt>:params</tt> - url_for parameters for the links (:controller, :action, etc.) # * <tt>:param_name</tt> - parameter name for page number in the links (:page by default) # * <tt>:remote</tt> - Ajax? (false by default) # * <tt>:paginator_class</tt> - Specify a custom Paginator (Kaminari::Helpers::Paginator by default) # * <tt>:template</tt> - Specify a custom template renderer for rendering the Paginator (receiver by default) # * <tt>:ANY_OTHER_VALUES</tt> - Any other hash key & values would be directly passed into each tag as :locals value. def paginate(scope, paginator_class: Kaminari::Helpers::Paginator, template: nil, **options) options[:total_pages] ||= scope.total_pages options.reverse_merge! current_page: scope.current_page, per_page: scope.limit_value, remote: false paginator = paginator_class.new (template || self), **options paginator.to_s end # A simple "Twitter like" pagination link that creates a link to the previous page. # # ==== Examples # Basic usage: # # <%= link_to_previous_page @items, 'Previous Page' %> # # Ajax: # # <%= link_to_previous_page @items, 'Previous Page', remote: true %> # # By default, it renders nothing if there are no more results on the previous page. # You can customize this output by passing a block. # # <%= link_to_previous_page @users, 'Previous Page' do %> # <span>At the Beginning</span> # <% end %> def link_to_previous_page(scope, name, **options) prev_page = path_to_prev_page(scope, options) options.except! :params, :param_name options[:rel] ||= 'prev' if prev_page link_to name, prev_page, options elsif block_given? yield end end alias link_to_prev_page link_to_previous_page # A simple "Twitter like" pagination link that creates a link to the next page. # # ==== Examples # Basic usage: # # <%= link_to_next_page @items, 'Next Page' %> # # Ajax: # # <%= link_to_next_page @items, 'Next Page', remote: true %> # # By default, it renders nothing if there are no more results on the next page. # You can customize this output by passing a block. # # <%= link_to_next_page @users, 'Next Page' do %> # <span>No More Pages</span> # <% end %> def link_to_next_page(scope, name, **options) next_page = path_to_next_page(scope, options) options.except! :params, :param_name options[:rel] ||= 'next' if next_page link_to name, next_page, options elsif block_given? yield end end # Renders a helpful message with numbers of displayed vs. total entries. # Ported from mislav/will_paginate # # ==== Examples # Basic usage: # # <%= page_entries_info @posts %> # #-> Displaying posts 6 - 10 of 26 in total # # By default, the message will use the humanized class name of objects # in collection: for instance, "project types" for ProjectType models. # The namespace will be cut out and only the last name will be used. # Override this with the <tt>:entry_name</tt> parameter: # # <%= page_entries_info @posts, entry_name: 'item' %> # #-> Displaying items 6 - 10 of 26 in total def page_entries_info(collection, entry_name: nil) records = collection.respond_to?(:records) ? collection.records : collection.to_a page_size = records.size entry_name = if entry_name entry_name.pluralize(page_size, I18n.locale) else collection.entry_name(count: page_size).downcase end if collection.total_pages < 2 t('helpers.page_entries_info.one_page.display_entries', entry_name: entry_name, count: collection.total_count) else from = collection.offset_value + 1 to = if collection.is_a? ::Kaminari::PaginatableArray [collection.offset_value + collection.limit_value, collection.total_count].min else collection.offset_value + page_size end t('helpers.page_entries_info.more_pages.display_entries', entry_name: entry_name, first: from, last: to, total: collection.total_count) end.html_safe end # Renders rel="next" and rel="prev" links to be used in the head. # # ==== Examples # Basic usage: # # In head: # <head> # <title>My Website</title> # <%= yield :head %> # </head> # # Somewhere in body: # <% content_for :head do %> # <%= rel_next_prev_link_tags @items %> # <% end %> # # #-> <link rel="next" href="/items/page/3"><link rel="prev" href="/items/page/1"> # def rel_next_prev_link_tags(scope, options = {}) next_page = path_to_next_page(scope, options) prev_page = path_to_prev_page(scope, options) output = String.new output << %Q|<link rel="next" href="#{next_page}">| if next_page output << %Q|<link rel="prev" href="#{prev_page}">| if prev_page output.html_safe end end end end
ruby
MIT
55d6e40767442d206236d3718c5bdb32d01f2345
2026-01-04T15:38:55.939543Z
false
kaminari/kaminari
https://github.com/kaminari/kaminari/blob/55d6e40767442d206236d3718c5bdb32d01f2345/kaminari-core/lib/kaminari/helpers/paginator.rb
kaminari-core/lib/kaminari/helpers/paginator.rb
# frozen_string_literal: true require 'active_support/inflector' require 'kaminari/helpers/tags' module Kaminari module Helpers # The main container tag class Paginator < Tag def initialize(template, window: nil, outer_window: Kaminari.config.outer_window, left: Kaminari.config.left, right: Kaminari.config.right, inner_window: Kaminari.config.window, **options) #:nodoc: super template, **options @window_options = {window: window || inner_window, left: left.zero? ? outer_window : left, right: right.zero? ? outer_window : right} @last = nil @window_options.merge! @options @window_options[:current_page] = @options[:current_page] = PageProxy.new(@window_options, @options[:current_page], nil) #XXX Using parent template's buffer class for rendering each partial here. This might cause problems if the handler mismatches @output_buffer = if defined?(::ActionView::OutputBuffer) ::ActionView::OutputBuffer.new elsif template.instance_variable_get(:@output_buffer) template.instance_variable_get(:@output_buffer).class.new else ActiveSupport::SafeBuffer.new end end # render given block as a view template def render(&block) instance_eval(&block) if @options[:total_pages] > 1 # This allows for showing fall-back HTML when there's only one page: # # <%= paginate(@search_results) || "Showing all search results" %> @output_buffer.presence end # enumerate each page providing PageProxy object as the block parameter # Because of performance reason, this doesn't actually enumerate all pages but pages that are seemingly relevant to the paginator. # "Relevant" pages are: # * pages inside the left outer window plus one for showing the gap tag # * pages inside the inner window plus one on the left plus one on the right for showing the gap tags # * pages inside the right outer window plus one for showing the gap tag def each_relevant_page return to_enum(:each_relevant_page) unless block_given? relevant_pages(@window_options).each do |page| yield PageProxy.new(@window_options, page, @last) end end alias each_page each_relevant_page def relevant_pages(options) left_window_plus_one = [*1..options[:left] + 1] right_window_plus_one = [*options[:total_pages] - options[:right]..options[:total_pages]] inside_window_plus_each_sides = [*options[:current_page] - options[:window] - 1..options[:current_page] + options[:window] + 1] (left_window_plus_one | inside_window_plus_each_sides | right_window_plus_one).sort.reject {|x| (x < 1) || (x > options[:total_pages])} end private :relevant_pages def page_tag(page) @last = Page.new @template, param_name: @param_name, theme: @theme, views_prefix: @views_prefix, internal_params: @params, **@options.merge(page: page) end %w[first_page prev_page next_page last_page gap].each do |tag| eval <<-DEF, nil, __FILE__, __LINE__ + 1 def #{tag}_tag @last = #{tag.classify}.new @template, param_name: @param_name, theme: @theme, views_prefix: @views_prefix, internal_params: @params, **@options end DEF end def to_s #:nodoc: Thread.current[:kaminari_rendering] = true super @window_options.merge paginator: self ensure Thread.current[:kaminari_rendering] = false end # delegates view helper methods to @template def method_missing(name, *args, **kwargs, &block) @template.respond_to?(name) ? @template.send(name, *args, **kwargs, &block) : super end private :method_missing # Wraps a "page number" and provides some utility methods class PageProxy include Comparable def initialize(options, page, last) #:nodoc: @page = page @current_page = options[:current_page] @total_pages = options[:total_pages] @left = options[:left] @right = options[:right] @window = options[:window] @was_truncated = last.is_a? Gap end # the page number def number @page end # current page or not def current? @page == @current_page end # the first page or not def first? @page == 1 end # the last page or not def last? @page == @total_pages end # the previous page or not def prev? @page == @current_page - 1 end # the next page or not def next? @page == @current_page + 1 end # relationship with the current page def rel if next? 'next' elsif prev? 'prev' end end # within the left outer window or not def left_outer? @page <= @left end # within the right outer window or not def right_outer? @total_pages - @page < @right end # inside the inner window or not def inside_window? (@current_page - @page).abs <= @window end # Current page is an isolated gap or not def single_gap? ((@page == @current_page - @window - 1) && (@page == @left + 1)) || ((@page == @current_page + @window + 1) && (@page == @total_pages - @right)) end # The page number exceeds the range of pages or not def out_of_range? @page > @total_pages end # The last rendered tag was "truncated" or not def was_truncated? @was_truncated end #Should we display the link tag? def display_tag? left_outer? || right_outer? || inside_window? || single_gap? end def to_i #:nodoc: number end def to_s #:nodoc: number.to_s end def +(other) #:nodoc: to_i + other.to_i end def -(other) #:nodoc: to_i - other.to_i end def <=>(other) #:nodoc: to_i <=> other.to_i end end end end end
ruby
MIT
55d6e40767442d206236d3718c5bdb32d01f2345
2026-01-04T15:38:55.939543Z
false
kaminari/kaminari
https://github.com/kaminari/kaminari/blob/55d6e40767442d206236d3718c5bdb32d01f2345/kaminari-core/lib/kaminari/helpers/tags.rb
kaminari-core/lib/kaminari/helpers/tags.rb
# frozen_string_literal: true module Kaminari module Helpers PARAM_KEY_EXCEPT_LIST = [:authenticity_token, :commit, :utf8, :_method, :script_name, :original_script_name].freeze # A tag stands for an HTML tag inside the paginator. # Basically, a tag has its own partial template file, so every tag can be # rendered into String using its partial template. # # The template file should be placed in your app/views/kaminari/ directory # with underscored class name (besides the "Tag" class. Tag is an abstract # class, so _tag partial is not needed). # e.g.) PrevLink -> app/views/kaminari/_prev_link.html.erb # # When no matching templates were found in your app, the engine's pre # installed template will be used. # e.g.) Paginator -> $GEM_HOME/kaminari-x.x.x/app/views/kaminari/_paginator.html.erb class Tag def initialize(template, params: nil, param_name: nil, theme: nil, views_prefix: nil, internal_params: nil, **options) #:nodoc: @template, @theme, @views_prefix, @options = template, theme, views_prefix, options @param_name = param_name || Kaminari.config.param_name if internal_params @params = internal_params else @params = template.params # @params in Rails 5 no longer inherits from Hash @params = if @params.respond_to?(:to_unsafe_h) @params.to_unsafe_h else @params.with_indifferent_access end @params.except!(*PARAM_KEY_EXCEPT_LIST) @params.merge! params if params end end def to_s(locals = {}) #:nodoc: formats = @template.respond_to?(:formats) ? @template.formats : Array(@template.params[:format]) formats += [:html] unless formats.include? :html @template.render partial: partial_path, locals: @options.merge(locals), formats: formats end def page_url_for(page) params = params_for(page) params[:only_path] = true @template.url_for params end private def params_for(page) if (@param_name == :page) || !@param_name.to_s.include?('[') page_val = !Kaminari.config.params_on_first_page && (page <= 1) ? nil : page @params[@param_name] = page_val @params else page_params = Rack::Utils.parse_nested_query("#{@param_name}=#{page}") page_params = @params.deep_merge(page_params) if !Kaminari.config.params_on_first_page && (page <= 1) # This converts a hash: # from: {other: "params", page: 1} # to: {other: "params", page: nil} # (when @param_name == "page") # # from: {other: "params", user: {name: "yuki", page: 1}} # to: {other: "params", user: {name: "yuki", page: nil}} # (when @param_name == "user[page]") @param_name.to_s.scan(/[\w.]+/)[0..-2].inject(page_params){|h, k| h[k] }[$&] = nil end page_params end end def partial_path "#{@views_prefix}/kaminari/#{@theme}/#{self.class.name.demodulize.underscore}".gsub('//', '/') end end # Tag that contains a link module Link # target page number def page raise 'Override page with the actual page value to be a Page.' end # the link's href def url page_url_for page end def to_s(locals = {}) #:nodoc: locals[:url] = url super locals end end # A page class Page < Tag include Link # target page number def page @options[:page] end def to_s(locals = {}) #:nodoc: locals[:page] = page super locals end end # Link with page number that appears at the leftmost class FirstPage < Tag include Link def page #:nodoc: 1 end end # Link with page number that appears at the rightmost class LastPage < Tag include Link def page #:nodoc: @options[:total_pages] end end # The "previous" page of the current page class PrevPage < Tag include Link # TODO: Remove this initializer before 1.3.0. def initialize(template, params: {}, param_name: nil, theme: nil, views_prefix: nil, **options) #:nodoc: # params in Rails 5 may not be a Hash either, # so it must be converted to a Hash to be merged into @params if params && params.respond_to?(:to_unsafe_h) Kaminari.deprecator.warn 'Explicitly passing params to helpers could be omitted.' params = params.to_unsafe_h end super(template, params: params, param_name: param_name, theme: theme, views_prefix: views_prefix, **options) end def page #:nodoc: @options[:current_page] - 1 end end # The "next" page of the current page class NextPage < Tag include Link # TODO: Remove this initializer before 1.3.0. def initialize(template, params: {}, param_name: nil, theme: nil, views_prefix: nil, **options) #:nodoc: # params in Rails 5 may not be a Hash either, # so it must be converted to a Hash to be merged into @params if params && params.respond_to?(:to_unsafe_h) Kaminari.deprecator.warn 'Explicitly passing params to helpers could be omitted.' params = params.to_unsafe_h end super(template, params: params, param_name: param_name, theme: theme, views_prefix: views_prefix, **options) end def page #:nodoc: @options[:current_page] + 1 end end # Non-link tag that stands for skipped pages... class Gap < Tag end end end
ruby
MIT
55d6e40767442d206236d3718c5bdb32d01f2345
2026-01-04T15:38:55.939543Z
false
kaminari/kaminari
https://github.com/kaminari/kaminari/blob/55d6e40767442d206236d3718c5bdb32d01f2345/kaminari-core/lib/kaminari/models/configuration_methods.rb
kaminari-core/lib/kaminari/models/configuration_methods.rb
# frozen_string_literal: true require 'active_support/concern' module Kaminari module ConfigurationMethods #:nodoc: extend ActiveSupport::Concern module ClassMethods #:nodoc: # Overrides the default +per_page+ value per model # class Article < ActiveRecord::Base # paginates_per 10 # end def paginates_per(val) @_default_per_page = val end # This model's default +per_page+ value # returns +default_per_page+ value unless explicitly overridden via <tt>paginates_per</tt> def default_per_page (defined?(@_default_per_page) && @_default_per_page) || Kaminari.config.default_per_page end # Overrides the max +per_page+ value per model # class Article < ActiveRecord::Base # max_paginates_per 100 # end def max_paginates_per(val) @_max_per_page = val end # This model's max +per_page+ value # returns +max_per_page+ value unless explicitly overridden via <tt>max_paginates_per</tt> def max_per_page (defined?(@_max_per_page) && @_max_per_page) || Kaminari.config.max_per_page end # Overrides the max_pages value per model when a value is given # class Article < ActiveRecord::Base # max_pages 100 # end # # Also returns this model's max_pages value (globally configured # +max_pages+ value unless explicitly overridden) when no value is given def max_pages(val = :none) if val == :none # getter (defined?(@_max_pages) && @_max_pages) || Kaminari.config.max_pages else # setter @_max_pages = val end end def max_pages_per(val) Kaminari.deprecator.warn 'max_pages_per is deprecated. Use max_pages instead.' max_pages val end end end end
ruby
MIT
55d6e40767442d206236d3718c5bdb32d01f2345
2026-01-04T15:38:55.939543Z
false
kaminari/kaminari
https://github.com/kaminari/kaminari/blob/55d6e40767442d206236d3718c5bdb32d01f2345/kaminari-core/lib/kaminari/models/array_extension.rb
kaminari-core/lib/kaminari/models/array_extension.rb
# frozen_string_literal: true require 'active_support/core_ext/module' module Kaminari # Kind of Array that can paginate class PaginatableArray < Array include Kaminari::ConfigurationMethods::ClassMethods ENTRY = 'entry'.freeze attr_internal_accessor :limit_value, :offset_value # ==== Options # * <tt>:limit</tt> - limit # * <tt>:offset</tt> - offset # * <tt>:total_count</tt> - total_count # * <tt>:padding</tt> - padding def initialize(original_array = [], limit: nil, offset: nil, total_count: nil, padding: nil) @_original_array, @_limit_value, @_offset_value, @_total_count, @_padding = original_array, (limit || default_per_page).to_i, offset.to_i, total_count, padding.to_i if limit && offset extend Kaminari::PageScopeMethods end if @_total_count && (@_total_count <= original_array.count) original_array = original_array.first(@_total_count)[@_offset_value, @_limit_value] end unless @_total_count original_array = original_array[@_offset_value, @_limit_value] end super(original_array || []) end # Used for page_entry_info def entry_name(options = {}) I18n.t('helpers.page_entries_info.entry', **options.reverse_merge(default: ENTRY.pluralize(options[:count]))) end # items at the specified "page" class_eval <<-RUBY, __FILE__, __LINE__ + 1 def #{Kaminari.config.page_method_name}(num = 1) offset(limit_value * ((num = num.to_i - 1) < 0 ? 0 : num)) end RUBY # returns another chunk of the original array def limit(num) self.class.new @_original_array, limit: num, offset: @_offset_value, total_count: @_total_count, padding: @_padding end # total item numbers of the original array def total_count @_total_count || @_original_array.length end # returns another chunk of the original array def offset(num) self.class.new @_original_array, limit: @_limit_value, offset: num, total_count: @_total_count, padding: @_padding end end # Wrap an Array object to make it paginatable # ==== Options # * <tt>:limit</tt> - limit # * <tt>:offset</tt> - offset # * <tt>:total_count</tt> - total_count # * <tt>:padding</tt> - padding def self.paginate_array(array, limit: nil, offset: nil, total_count: nil, padding: nil) PaginatableArray.new array, limit: limit, offset: offset, total_count: total_count, padding: padding end end
ruby
MIT
55d6e40767442d206236d3718c5bdb32d01f2345
2026-01-04T15:38:55.939543Z
false
kaminari/kaminari
https://github.com/kaminari/kaminari/blob/55d6e40767442d206236d3718c5bdb32d01f2345/kaminari-core/lib/kaminari/models/page_scope_methods.rb
kaminari-core/lib/kaminari/models/page_scope_methods.rb
# frozen_string_literal: true module Kaminari module PageScopeMethods # Specify the <tt>per_page</tt> value for the preceding <tt>page</tt> scope # Model.page(3).per(10) def per(num, max_per_page: nil) max_per_page ||= ((defined?(@_max_per_page) && @_max_per_page) || self.max_per_page) @_per = (num || default_per_page).to_i if (n = num.to_i) < 0 || !(/^\d/ =~ num.to_s) self elsif n.zero? limit(n) elsif max_per_page && (max_per_page < n) limit(max_per_page).offset(offset_value / limit_value * max_per_page) else limit(n).offset(offset_value / limit_value * n) end end def max_paginates_per(new_max_per_page) @_max_per_page = new_max_per_page per (defined?(@_per) && @_per) || default_per_page, max_per_page: new_max_per_page end def padding(num) num = num.to_i raise ArgumentError, "padding must not be negative" if num < 0 @_padding = num offset(offset_value + @_padding) end # Total number of pages def total_pages count_without_padding = total_count count_without_padding -= @_padding if defined?(@_padding) && @_padding count_without_padding = 0 if count_without_padding < 0 total_pages_count = (count_without_padding.to_f / limit_value).ceil max_pages && (max_pages < total_pages_count) ? max_pages : total_pages_count rescue FloatDomainError raise ZeroPerPageOperation, "The number of total pages was incalculable. Perhaps you called .per(0)?" end # Current page number def current_page offset_without_padding = offset_value offset_without_padding -= @_padding if defined?(@_padding) && @_padding offset_without_padding = 0 if offset_without_padding < 0 (offset_without_padding / limit_value) + 1 rescue ZeroDivisionError raise ZeroPerPageOperation, "Current page was incalculable. Perhaps you called .per(0)?" end # Current per-page number def current_per_page Kaminari.deprecator.warn '#current_per_page is deprecated and will be removed in the next major ' \ 'version. Please use #limit_value instead.' limit_value # (defined?(@_per) && @_per) || default_per_page end # Next page number in the collection def next_page current_page + 1 unless last_page? || out_of_range? end # Previous page number in the collection def prev_page current_page - 1 unless first_page? || out_of_range? end # First page of the collection? def first_page? current_page == 1 end # Last page of the collection? def last_page? current_page == total_pages end # Out of range of the collection? def out_of_range? current_page > total_pages end end end
ruby
MIT
55d6e40767442d206236d3718c5bdb32d01f2345
2026-01-04T15:38:55.939543Z
false
kaminari/kaminari
https://github.com/kaminari/kaminari/blob/55d6e40767442d206236d3718c5bdb32d01f2345/kaminari-core/lib/kaminari/core/version.rb
kaminari-core/lib/kaminari/core/version.rb
# frozen_string_literal: true module Kaminari module Core VERSION = '1.2.2' end end
ruby
MIT
55d6e40767442d206236d3718c5bdb32d01f2345
2026-01-04T15:38:55.939543Z
false
kaminari/kaminari
https://github.com/kaminari/kaminari/blob/55d6e40767442d206236d3718c5bdb32d01f2345/kaminari-actionview/lib/kaminari/actionview.rb
kaminari-actionview/lib/kaminari/actionview.rb
# frozen_string_literal: true require "kaminari/actionview/version" require 'active_support/lazy_load_hooks' ActiveSupport.on_load :action_view do require 'kaminari/helpers/helper_methods' ::ActionView::Base.send :include, Kaminari::Helpers::HelperMethods require 'kaminari/actionview/action_view_extension' end
ruby
MIT
55d6e40767442d206236d3718c5bdb32d01f2345
2026-01-04T15:38:55.939543Z
false
kaminari/kaminari
https://github.com/kaminari/kaminari/blob/55d6e40767442d206236d3718c5bdb32d01f2345/kaminari-actionview/lib/kaminari/actionview/version.rb
kaminari-actionview/lib/kaminari/actionview/version.rb
# frozen_string_literal: true module Kaminari module Actionview VERSION = '1.2.2' end end
ruby
MIT
55d6e40767442d206236d3718c5bdb32d01f2345
2026-01-04T15:38:55.939543Z
false
kaminari/kaminari
https://github.com/kaminari/kaminari/blob/55d6e40767442d206236d3718c5bdb32d01f2345/kaminari-actionview/lib/kaminari/actionview/action_view_extension.rb
kaminari-actionview/lib/kaminari/actionview/action_view_extension.rb
# frozen_string_literal: true require 'action_view/log_subscriber' require 'action_view/context' require 'kaminari/helpers/paginator' module Kaminari # = Helpers module ActionViewExtension # Monkey-patching AV::LogSubscriber not to log each render_partial module LogSubscriberSilencer def render_partial(*) super unless Thread.current[:kaminari_rendering] end end end end # so that this instance can actually "render" ::Kaminari::Helpers::Paginator.send :include, ::ActionView::Context ActionView::LogSubscriber.send :prepend, Kaminari::ActionViewExtension::LogSubscriberSilencer
ruby
MIT
55d6e40767442d206236d3718c5bdb32d01f2345
2026-01-04T15:38:55.939543Z
false
kaminari/kaminari
https://github.com/kaminari/kaminari/blob/55d6e40767442d206236d3718c5bdb32d01f2345/lib/kaminari.rb
lib/kaminari.rb
# frozen_string_literal: true require 'kaminari/core' require 'kaminari/version' require 'kaminari/actionview' require 'kaminari/activerecord'
ruby
MIT
55d6e40767442d206236d3718c5bdb32d01f2345
2026-01-04T15:38:55.939543Z
false
kaminari/kaminari
https://github.com/kaminari/kaminari/blob/55d6e40767442d206236d3718c5bdb32d01f2345/lib/kaminari/version.rb
lib/kaminari/version.rb
# frozen_string_literal: true module Kaminari VERSION = '1.2.2' end
ruby
MIT
55d6e40767442d206236d3718c5bdb32d01f2345
2026-01-04T15:38:55.939543Z
false
kaminari/kaminari
https://github.com/kaminari/kaminari/blob/55d6e40767442d206236d3718c5bdb32d01f2345/kaminari-activerecord/lib/kaminari/activerecord.rb
kaminari-activerecord/lib/kaminari/activerecord.rb
# frozen_string_literal: true require "kaminari/activerecord/version" require 'active_support/lazy_load_hooks' ActiveSupport.on_load :active_record do require 'kaminari/core' require 'kaminari/activerecord/active_record_extension' ::ActiveRecord::Base.send :include, Kaminari::ActiveRecordExtension end
ruby
MIT
55d6e40767442d206236d3718c5bdb32d01f2345
2026-01-04T15:38:55.939543Z
false
kaminari/kaminari
https://github.com/kaminari/kaminari/blob/55d6e40767442d206236d3718c5bdb32d01f2345/kaminari-activerecord/lib/kaminari/activerecord/active_record_model_extension.rb
kaminari-activerecord/lib/kaminari/activerecord/active_record_model_extension.rb
# frozen_string_literal: true require 'kaminari/activerecord/active_record_relation_methods' module Kaminari module ActiveRecordModelExtension extend ActiveSupport::Concern included do include Kaminari::ConfigurationMethods # Fetch the values at the specified page number # Model.page(5) eval <<-RUBY, nil, __FILE__, __LINE__ + 1 def self.#{Kaminari.config.page_method_name}(num = nil) num = num.respond_to?(:to_i) ? num.to_i : 1 per_page = max_per_page && (default_per_page > max_per_page) ? max_per_page : default_per_page limit(per_page).offset(per_page * ((num = num.to_i - 1) < 0 ? 0 : num)).extending do include Kaminari::ActiveRecordRelationMethods include Kaminari::PageScopeMethods end end RUBY end end end
ruby
MIT
55d6e40767442d206236d3718c5bdb32d01f2345
2026-01-04T15:38:55.939543Z
false
kaminari/kaminari
https://github.com/kaminari/kaminari/blob/55d6e40767442d206236d3718c5bdb32d01f2345/kaminari-activerecord/lib/kaminari/activerecord/version.rb
kaminari-activerecord/lib/kaminari/activerecord/version.rb
# frozen_string_literal: true module Kaminari module Activerecord VERSION = '1.2.2' end end
ruby
MIT
55d6e40767442d206236d3718c5bdb32d01f2345
2026-01-04T15:38:55.939543Z
false
kaminari/kaminari
https://github.com/kaminari/kaminari/blob/55d6e40767442d206236d3718c5bdb32d01f2345/kaminari-activerecord/lib/kaminari/activerecord/active_record_relation_methods.rb
kaminari-activerecord/lib/kaminari/activerecord/active_record_relation_methods.rb
# frozen_string_literal: true module Kaminari # Active Record specific page scope methods implementations module ActiveRecordRelationMethods # Used for page_entry_info def entry_name(options = {}) default = options[:count] == 1 ? model_name.human : model_name.human.pluralize model_name.human(options.reverse_merge(default: default)) end def reset #:nodoc: @total_count = nil super end def total_count(column_name = :all, _options = nil) #:nodoc: return @total_count if defined?(@total_count) && @total_count # There are some cases that total count can be deduced from loaded records if loaded? # Total count has to be 0 if loaded records are 0 return @total_count = 0 if (current_page == 1) && @records.empty? # Total count is calculable at the last page return @total_count = offset_value + @records.length if @records.any? && (@records.length < limit_value) end # #count overrides the #select which could include generated columns referenced in #order, so skip #order here, where it's irrelevant to the result anyway c = except(:offset, :limit, :order) # Remove includes only if they are irrelevant c = c.except(:includes, :eager_load, :preload) unless references_eager_loaded_tables? c = c.limit(max_pages * limit_value) if max_pages && max_pages.respond_to?(:*) # .group returns an OrderedHash that responds to #count c = c.count(column_name) @total_count = if c.is_a?(Hash) || c.is_a?(ActiveSupport::OrderedHash) c.count elsif c.respond_to? :count c.count(column_name) else c end end # Turn this Relation to a "without count mode" Relation. # Note that the "without count mode" is supposed to be performant but has a feature limitation. # Pro: paginates without casting an extra SELECT COUNT query # Con: unable to know the total number of records/pages def without_count extend ::Kaminari::PaginatableWithoutCount end end # A module that makes AR::Relation paginatable without having to cast another SELECT COUNT query module PaginatableWithoutCount module LimitValueSetter # refine PaginatableWithoutCount do # NOTE: this doesn't work in Ruby < 2.4 refine ::ActiveRecord::Relation do private # Update multiple instance variables that hold `limit` to a given value def set_limit_value(new_limit) @values[:limit] = new_limit if @arel case @arel.limit.class.name when 'Integer', 'Fixnum' @arel.limit = new_limit when 'ActiveModel::Attribute::WithCastValue' # comparing by class name because ActiveModel::Attribute::WithCastValue is a private constant @arel.limit = build_cast_value 'LIMIT', new_limit when 'Arel::Nodes::BindParam' if @arel.limit.respond_to?(:value) @arel.limit = Arel::Nodes::BindParam.new(@arel.limit.value.with_cast_value(new_limit)) end end end end end end using Kaminari::PaginatableWithoutCount::LimitValueSetter # Overwrite AR::Relation#load to actually load one more record to judge if the page has next page # then store the result in @_has_next ivar def load if loaded? || limit_value.nil? super else set_limit_value limit_value + 1 super set_limit_value limit_value - 1 if @records.any? @records = @records.dup if (frozen = @records.frozen?) @_has_next = !!@records.delete_at(limit_value) @records.freeze if frozen end self end end # The page wouldn't be the last page if there's "limit + 1" record def last_page? !out_of_range? && !@_has_next end # Empty relation needs no pagination def out_of_range? load unless loaded? @records.empty? end # Force to raise an exception if #total_count is called explicitly. def total_count raise "This scope is marked as a non-count paginable scope and can't be used in combination " \ "with `#paginate' or `#page_entries_info'. Use #link_to_next_page or #link_to_previous_page instead." end end end
ruby
MIT
55d6e40767442d206236d3718c5bdb32d01f2345
2026-01-04T15:38:55.939543Z
false
kaminari/kaminari
https://github.com/kaminari/kaminari/blob/55d6e40767442d206236d3718c5bdb32d01f2345/kaminari-activerecord/lib/kaminari/activerecord/active_record_extension.rb
kaminari-activerecord/lib/kaminari/activerecord/active_record_extension.rb
# frozen_string_literal: true require 'kaminari/activerecord/active_record_model_extension' module Kaminari module ActiveRecordExtension extend ActiveSupport::Concern module ClassMethods #:nodoc: # Future subclasses will pick up the model extension def inherited(kls) #:nodoc: super kls.send(:include, Kaminari::ActiveRecordModelExtension) if kls.superclass == ::ActiveRecord::Base end end included do # Existing subclasses pick up the model extension as well descendants.each do |kls| kls.send(:include, Kaminari::ActiveRecordModelExtension) if kls.superclass == ::ActiveRecord::Base end end end end
ruby
MIT
55d6e40767442d206236d3718c5bdb32d01f2345
2026-01-04T15:38:55.939543Z
false
activeadmin/activeadmin
https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/tasks/test_application.rb
tasks/test_application.rb
# frozen_string_literal: true require "fileutils" module ActiveAdmin class TestApplication attr_reader :rails_env, :template def initialize(opts = {}) @rails_env = opts[:rails_env] || "test" @template = opts[:template] || "rails_template" end def soft_generate if File.exist? app_dir puts "test app #{app_dir} already exists; skipping test app generation" else generate end Bundler.with_original_env do Kernel.system("yarn install") # so tailwindcss/plugin is available for test app Kernel.system("rake dependencies:vendor") # ensure flowbite is updated for test app Dir.chdir(app_dir) do Kernel.system("yarn add @activeadmin/activeadmin") Kernel.system('npm pkg set scripts.build:css="npx @tailwindcss/cli -i ./app/assets/stylesheets/active_admin.css -o ./app/assets/builds/active_admin.css --minify"') Kernel.system("yarn install") Kernel.system("yarn build:css") end end end def generate FileUtils.mkdir_p base_dir args = %W( -m spec/support/#{template}.rb --skip-action-cable --skip-action-mailbox --skip-action-text --skip-active-storage --skip-bootsnap --skip-brakeman --skip-bundler-audit --skip-ci --skip-decrypted-diffs --skip-dev-gems --skip-docker --skip-git --skip-hotwire --skip-jbuilder --skip-kamal --skip-rubocop --skip-solid --skip-system-test --skip-test --skip-thruster --javascript=importmap ) command = ["bundle", "exec", "rails", "new", app_dir, *args].join(" ") env = { "BUNDLE_GEMFILE" => expanded_gemfile, "RAILS_ENV" => rails_env } Bundler.with_original_env do Kernel.system(env, command) end end def full_app_dir File.expand_path(app_dir) end def app_dir @app_dir ||= "#{base_dir}/#{app_name}" end def expanded_gemfile return gemfile if Pathname.new(gemfile).absolute? File.expand_path(gemfile) end private def base_dir @base_dir ||= "tmp/#{rails_env}_apps" end def app_name return "rails_81" if main_app? File.basename(File.dirname(gemfile)) end def main_app? expanded_gemfile == File.expand_path("Gemfile") end def gemfile gemfile_from_env || "Gemfile" end def gemfile_from_env ENV["BUNDLE_GEMFILE"] end end end
ruby
MIT
b9d630ce22a739d57c9c8b9976807a370e4de140
2026-01-04T15:38:25.641812Z
false
activeadmin/activeadmin
https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/tasks/bug_report_template.rb
tasks/bug_report_template.rb
# frozen_string_literal: true require "bundler/inline" gemfile(true) do source "https://rubygems.org" # Use `ACTIVE_ADMIN_PATH=. ruby tasks/bug_report_template.rb` to run # locally, otherwise run against the default branch. if ENV["ACTIVE_ADMIN_PATH"] gem "activeadmin", path: ENV["ACTIVE_ADMIN_PATH"], require: false else gem "activeadmin", github: "activeadmin/activeadmin", require: false end # Change Rails version if necessary. gem "rails", "~> 8.1.0" gem "sprockets", "~> 4.0" gem "importmap-rails", "~> 2.0" gem "sqlite3", force_ruby_platform: true, platform: :mri # Fixes an issue on CI with default gems when using inline bundle with default # gems that are already activated # Ref: rubygems/rubygems#6386 if ENV["CI"] require "net/protocol" require "timeout" gem "net-protocol", Net::Protocol::VERSION gem "timeout", Timeout::VERSION end end require "active_record" ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:") ActiveRecord::Base.logger = Logger.new(STDOUT) ActiveRecord::Schema.define do create_table :active_admin_comments, force: true do |_t| end create_table :users, force: true do |t| t.string :full_name end end require "action_controller/railtie" require "action_view/railtie" require "active_admin" class TestApp < Rails::Application config.root = __dir__ config.hosts << ".example.com" config.session_store :cookie_store, key: "cookie_store_key" config.secret_key_base = "secret_key_base" config.eager_load = false config.logger = Logger.new($stdout) Rails.logger = config.logger end class ApplicationController < ActionController::Base include Rails.application.routes.url_helpers end class ApplicationRecord < ActiveRecord::Base primary_abstract_class def self.ransackable_attributes(auth_object = nil) authorizable_ransackable_attributes end def self.ransackable_associations(auth_object = nil) authorizable_ransackable_associations end end class User < ApplicationRecord end ActiveAdmin.setup do |config| # Authentication disabled by default. Override if necessary. config.authentication_method = false config.current_user_method = false end Rails.application.initialize! ActiveAdmin.register_page "Dashboard" do menu priority: 1, label: proc { I18n.t("active_admin.dashboard") } content do "Test Me" end end ActiveAdmin.register User do end Rails.application.routes.draw do ActiveAdmin.routes(self) end require "minitest/autorun" require "rack/test" require "rails/test_help" # Replace this with the code necessary to make your test fail. class BugTest < ActionDispatch::IntegrationTest def test_admin_root_success? get admin_root_url assert_match "Test Me", response.body # has content assert_match "Users", response.body # has 'Your Models' in menu assert_response :success end def test_admin_users User.create! full_name: "John Doe" get admin_users_url assert_match "John Doe", response.body # has created row assert_response :success end private def app Rails.application end end
ruby
MIT
b9d630ce22a739d57c9c8b9976807a370e4de140
2026-01-04T15:38:25.641812Z
false
activeadmin/activeadmin
https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/app/helpers/active_admin/form_helper.rb
app/helpers/active_admin/form_helper.rb
# frozen_string_literal: true module ActiveAdmin module FormHelper RESERVED_PARAMS = %w(controller action commit utf8).freeze def active_admin_form_for(resource, options = {}, &block) Arbre::Context.new({}, self) do active_admin_form_for resource, options, &block end.content end def hidden_field_tags_for(params, options = {}) fields_for_params(params.to_unsafe_hash, options).map do |kv| k, v = kv.first hidden_field_tag k, v, id: sanitize_to_id("hidden_active_admin_#{k}") end.join("\n").html_safe end # Flatten a params Hash to an array of fields. # # @param params [Hash] # @param options [Hash] :namespace and :except # # @return [Array] of [Hash] with one element. # # @example # fields_for_params(scope: "all", users: ["greg"]) # => [ {"scope" => "all"} , {"users[]" => "greg"} ] # def fields_for_params(params, options = {}) namespace = options[:namespace] except = Array.wrap(options[:except]).map(&:to_s) params.flat_map do |k, v| next if namespace.nil? && RESERVED_PARAMS.include?(k.to_s) next if except.include?(k.to_s) if namespace k = "#{namespace}[#{k}]" end case v when String, TrueClass, FalseClass { k => v } when Symbol { k => v.to_s } when Hash fields_for_params(v, namespace: k) when Array v.map do |v| { "#{k}[]" => v } end when nil { k => "" } else raise TypeError, "Cannot convert #{v.class} value: #{v.inspect}" end end.compact end # Helper method to render a filter form def active_admin_filters_form_for(search, filters, options = {}) defaults = { builder: ActiveAdmin::Filters::FormBuilder, url: collection_path, html: { class: "filters-form" } } required = { html: { method: :get }, as: :q } options = defaults.deep_merge(options).deep_merge(required) form_for search, options do |f| f.template.concat hidden_field_tags_for(params, except: except_hidden_fields) filters.each do |attribute, opts| next if opts.key?(:if) && !call_method_or_proc_on(self, opts[:if]) next if opts.key?(:unless) && call_method_or_proc_on(self, opts[:unless]) filter_opts = opts.except(:if, :unless) filter_opts[:input_html] = instance_exec(&filter_opts[:input_html]) if filter_opts[:input_html].is_a?(Proc) f.filter attribute, filter_opts end buttons = content_tag :div, class: "filters-form-buttons" do f.submit(I18n.t("active_admin.filters.buttons.filter"), class: "filters-form-submit") + link_to(I18n.t("active_admin.filters.buttons.clear"), collection_path, class: "filters-form-clear") end f.template.concat buttons end end private def except_hidden_fields [:q, :page] end end end
ruby
MIT
b9d630ce22a739d57c9c8b9976807a370e4de140
2026-01-04T15:38:25.641812Z
false
activeadmin/activeadmin
https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/app/helpers/active_admin/layout_helper.rb
app/helpers/active_admin/layout_helper.rb
# frozen_string_literal: true module ActiveAdmin module LayoutHelper # Returns the current Active Admin application instance def active_admin_application ActiveAdmin.application end def set_page_title(title) @page_title = title end def site_title # Prioritize namespace and account for Devise views where namespace is not available namespace = active_admin_namespace if respond_to?(:active_admin_namespace) (namespace || active_admin_application).site_title(self) end def html_head_site_title(separator: "-") "#{@page_title || page_title} #{separator} #{site_title}" end def action_items_for_action @action_items_for_action ||= begin if active_admin_config&.action_items? active_admin_config.action_items_for(params[:action], self) else [] end end end def sidebar_sections_for_action @sidebar_sections_for_action ||= begin if active_admin_config&.sidebar_sections? active_admin_config.sidebar_sections_for(params[:action], self) else [] end end end def skip_sidebar! @skip_sidebar = true end def skip_sidebar? @skip_sidebar == true end def flash_messages @flash_messages ||= flash.to_hash.except(*active_admin_application.flash_keys_to_except) end def url_for_comments(*args) parts = [] parts << active_admin_namespace.name unless active_admin_namespace.root? parts << active_admin_namespace.comments_registration_name.underscore parts << "path" send parts.join("_"), *args end end end
ruby
MIT
b9d630ce22a739d57c9c8b9976807a370e4de140
2026-01-04T15:38:25.641812Z
false
activeadmin/activeadmin
https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/app/helpers/active_admin/index_helper.rb
app/helpers/active_admin/index_helper.rb
# frozen_string_literal: true module ActiveAdmin module IndexHelper def scope_name(scope) case scope.name when Proc then self.instance_exec(&scope.name).to_s else scope.name.to_s end end def batch_actions_to_display @batch_actions_to_display ||= begin if active_admin_config && active_admin_config.batch_actions.any? active_admin_config.batch_actions.select do |batch_action| call_method_or_proc_on(self, batch_action.display_if_block) end else [] end end end # 1. removes `select` and `order` to prevent invalid SQL # 2. correctly handles the Hash returned when `group by` is used def collection_size(c = collection) return c.count if c.is_a?(Array) return c.length if c.limit_value c = c.except :select, :order c.group_values.present? ? c.count.count : c.count end def collection_empty?(c = collection) collection_size(c) == 0 end end end
ruby
MIT
b9d630ce22a739d57c9c8b9976807a370e4de140
2026-01-04T15:38:25.641812Z
false
activeadmin/activeadmin
https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/app/helpers/active_admin/display_helper.rb
app/helpers/active_admin/display_helper.rb
# frozen_string_literal: true module ActiveAdmin module DisplayHelper DISPLAY_NAME_FALLBACK = -> { klass = self.class name = if klass.respond_to?(:model_name) if klass.respond_to?(:primary_key) "#{klass.model_name.human} ##{send(klass.primary_key)}" else klass.model_name.human end elsif klass.respond_to?(:primary_key) " ##{send(klass.primary_key)}" end name.present? ? name : to_s } def DISPLAY_NAME_FALLBACK.inspect "DISPLAY_NAME_FALLBACK" end # Attempts to call any known display name methods on the resource. # See the setting in `application.rb` for the list of methods and their priority. def display_name(resource) unless resource.nil? result = render_in_context(resource, display_name_method_for(resource)) if result.to_s.strip.present? ERB::Util.html_escape(result) else ERB::Util.html_escape(render_in_context(resource, DISPLAY_NAME_FALLBACK)) end end end def format_attribute(resource, attr) value = find_value resource, attr if value.is_a?(Arbre::Element) value elsif boolean_attr?(resource, attr, value) Arbre::Context.new { status_tag value } else pretty_format value end end # Attempts to create a human-readable string for any object def pretty_format(object) case object when String, Numeric, Symbol, Arbre::Element object.to_s when Date, Time I18n.localize object, format: active_admin_application.localize_format when Array format_collection(object) else if defined?(::ActiveRecord) && object.is_a?(ActiveRecord::Base) || defined?(::Mongoid) && object.class.include?(Mongoid::Document) auto_link object elsif defined?(::ActiveRecord) && object.is_a?(ActiveRecord::Relation) format_collection(object) else display_name object end end end private # Looks up and caches the first available display name method. # To prevent conflicts, we exclude any methods that happen to be associations. # If no methods are available and we're about to use the Kernel's `to_s`, provide our own. def display_name_method_for(resource) @@display_name_methods_cache ||= {} @@display_name_methods_cache[resource.class] ||= begin methods = active_admin_application.display_name_methods - association_methods_for(resource) method = methods.detect { |method| resource.respond_to? method } if method != :to_s || resource.method(method).source_location method else DISPLAY_NAME_FALLBACK end end end def association_methods_for(resource) return [] unless resource.class.respond_to? :reflect_on_all_associations resource.class.reflect_on_all_associations.map(&:name) end def find_value(resource, attr) if attr.is_a? Proc attr.call resource elsif resource.respond_to? attr resource.public_send attr elsif resource.respond_to? :[] resource[attr] end end def format_collection(collection) safe_join(collection.map { |item| pretty_format(item) }, ", ") end def boolean_attr?(resource, attr, value) case value when TrueClass, FalseClass true else if resource.class.respond_to? :attribute_types resource.class.attribute_types[attr.to_s].is_a?(ActiveModel::Type::Boolean) end end end end end
ruby
MIT
b9d630ce22a739d57c9c8b9976807a370e4de140
2026-01-04T15:38:25.641812Z
false
activeadmin/activeadmin
https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/app/helpers/active_admin/breadcrumb_helper.rb
app/helpers/active_admin/breadcrumb_helper.rb
# frozen_string_literal: true module ActiveAdmin module BreadcrumbHelper ID_FORMAT_REGEXP = /\A(\d+|[a-f0-9]{24}|(?:[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}))\z/.freeze # Returns an array of links to use in a breadcrumb def build_breadcrumb_links(path = request.path, html_options = {}) config = active_admin_config.breadcrumb if config.is_a?(Proc) instance_exec(controller, &config) elsif config.present? default_breadcrumb_links(path, html_options) end end def default_breadcrumb_links(path, html_options = {}) # remove leading "/" and split up the URL # and remove last since it's used as the page title parts = path.split("/").select(&:present?)[0..-2] parts.each_with_index.map do |part, index| # 1. try using `display_name` if we can locate a DB object # 2. try using the model name translation # 3. default to calling `titlecase` on the URL fragment if ID_FORMAT_REGEXP.match?(part) && parts[index - 1] parent = active_admin_config.belongs_to_config.try :target config = parent && parent.resource_name.route_key == parts[index - 1] ? parent : active_admin_config name = display_name config.find_resource part end name ||= I18n.t "activerecord.models.#{part.singularize}", count: 2.1, default: part.titlecase # Don't create a link if the resource's show action is disabled if !config || config.defined_actions.include?(:show) link_to name, "/" + parts[0..index].join("/"), html_options else name end end end end end
ruby
MIT
b9d630ce22a739d57c9c8b9976807a370e4de140
2026-01-04T15:38:25.641812Z
false
activeadmin/activeadmin
https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/app/helpers/active_admin/auto_link_helper.rb
app/helpers/active_admin/auto_link_helper.rb
# frozen_string_literal: true module ActiveAdmin module AutoLinkHelper # Automatically links objects to their resource controllers. If # the resource has not been registered, a string representation of # the object is returned. # # The default content in the link is returned from ActiveAdmin::DisplayHelper#display_name # # You can pass in the content to display # eg: auto_link(@post, "My Link") # def auto_link(resource, content = display_name(resource), **html_options) if url = auto_url_for(resource) link_to content, url, html_options else content end end # Like `auto_link`, except that it only returns a URL for the resource def auto_url_for(resource) config = active_admin_resource_for(resource.class) return unless config if config.controller.action_methods.include?("show") && authorized?(ActiveAdmin::Auth::READ, resource) url_for config.route_instance_path resource, url_options elsif config.controller.action_methods.include?("edit") && authorized?(ActiveAdmin::Auth::EDIT, resource) url_for config.route_edit_instance_path resource, url_options end end def new_action_authorized?(resource_or_class) controller.action_methods.include?("new") && authorized?(ActiveAdmin::Auth::NEW, resource_or_class) end def show_action_authorized?(resource_or_class) controller.action_methods.include?("show") && authorized?(ActiveAdmin::Auth::READ, resource_or_class) end def edit_action_authorized?(resource_or_class) controller.action_methods.include?("edit") && authorized?(ActiveAdmin::Auth::EDIT, resource_or_class) end def destroy_action_authorized?(resource_or_class) controller.action_methods.include?("destroy") && authorized?(ActiveAdmin::Auth::DESTROY, resource_or_class) end def auto_logout_link_path render_or_call_method_or_proc_on(self, active_admin_namespace.logout_link_path) end private # Returns the ActiveAdmin::Resource instance for a class # While `active_admin_namespace` is a helper method, this method seems # to exist to otherwise resolve failed component specs using mock_action_view. def active_admin_resource_for(klass) if respond_to? :active_admin_namespace active_admin_namespace.resource_for klass end end end end
ruby
MIT
b9d630ce22a739d57c9c8b9976807a370e4de140
2026-01-04T15:38:25.641812Z
false
activeadmin/activeadmin
https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/app/controllers/active_admin/page_controller.rb
app/controllers/active_admin/page_controller.rb
# frozen_string_literal: true module ActiveAdmin # All Pages controllers inherit from this controller. class PageController < BaseController # Active admin actions don't require layout. All custom actions do. ACTIVE_ADMIN_ACTIONS = [:index] actions :index before_action :authorize_access! def index(options = {}, &block) render "active_admin/page/index" end private def authorize_access! permission = action_to_permission(params[:action]) authorize! permission, active_admin_config end end end
ruby
MIT
b9d630ce22a739d57c9c8b9976807a370e4de140
2026-01-04T15:38:25.641812Z
false
activeadmin/activeadmin
https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/app/controllers/active_admin/resource_controller.rb
app/controllers/active_admin/resource_controller.rb
# frozen_string_literal: true require "active_admin/collection_decorator" module ActiveAdmin # All Resources Controller inherits from this controller. # It implements actions and helpers for resources. class ResourceController < BaseController respond_to :html, :xml, :json respond_to :csv, only: :index before_action :restrict_download_format_access!, only: [:index, :show] include ResourceController::ActionBuilder include ResourceController::Decorators include ResourceController::DataAccess include ResourceController::PolymorphicRoutes include ResourceController::Scoping include ResourceController::Streaming extend ResourceClassMethods def self.active_admin_config=(config) if @active_admin_config = config defaults resource_class: config.resource_class, route_prefix: config.route_prefix, instance_name: config.resource_name.singular end end # Inherited Resources uses the `self.inherited(base)` hook to add # in `self.resource_class`. To override it, we need to install # our resource_class method each time we're inherited from. def self.inherited(base) super(base) base.override_resource_class_methods! end private def page_presenter case params[:action].to_sym when :index active_admin_config.get_page_presenter(params[:action], params[:as]) when :new, :edit, :create, :update active_admin_config.get_page_presenter(:form) end || super end def default_page_presenter case params[:action].to_sym when :index PagePresenter.new(as: :table) when :new, :edit PagePresenter.new end || super end def page_title if page_presenter[:title] case params[:action].to_sym when :index case page_presenter[:title] when Symbol, Proc instance_exec(&page_presenter[:title]) else page_presenter[:title] end else helpers.render_or_call_method_or_proc_on(resource, page_presenter[:title]) end else default_page_title end end def default_page_title case params[:action].to_sym when :index active_admin_config.plural_resource_label when :show helpers.display_name(resource) when :new, :edit, :create, :update normalized_action = params[:action] normalized_action = 'new' if normalized_action == 'create' normalized_action = 'edit' if normalized_action == 'update' ActiveAdmin::Localizers.resource(active_admin_config).t("#{normalized_action}_model") else I18n.t("active_admin.#{params[:action]}", default: params[:action].to_s.titleize) end end def restrict_download_format_access! unless request.format.html? presenter = active_admin_config.get_page_presenter(:index) download_formats = (presenter || {}).fetch(:download_links, active_admin_config.namespace.download_links) unless build_download_formats(download_formats).include?(request.format.symbol) raise ActiveAdmin::AccessDenied.new(current_active_admin_user, :index) end end end end end
ruby
MIT
b9d630ce22a739d57c9c8b9976807a370e4de140
2026-01-04T15:38:25.641812Z
false
activeadmin/activeadmin
https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/app/controllers/active_admin/base_controller.rb
app/controllers/active_admin/base_controller.rb
# frozen_string_literal: true module ActiveAdmin # BaseController for ActiveAdmin. # It implements ActiveAdmin controllers core features. class BaseController < ::InheritedResources::Base helper MethodOrProcHelper helper LayoutHelper helper FormHelper helper BreadcrumbHelper helper AutoLinkHelper helper DisplayHelper helper IndexHelper layout "active_admin" before_action :only_render_implemented_actions before_action :authenticate_active_admin_user class << self # Ensure that this method is available for the DSL public :actions # Reference to the Resource object which initialized # this controller attr_accessor :active_admin_config end include BaseController::Authorization include BaseController::Menu private # By default Rails will render un-implemented actions when the view exists. Because Active # Admin allows you to not render any of the actions by using the #actions method, we need # to check if they are implemented. def only_render_implemented_actions raise AbstractController::ActionNotFound unless action_methods.include?(params[:action]) end # Calls the authentication method as defined in ActiveAdmin.authentication_method def authenticate_active_admin_user send(active_admin_namespace.authentication_method) if active_admin_namespace.authentication_method end def current_active_admin_user send(active_admin_namespace.current_user_method) if active_admin_namespace.current_user_method end helper_method :current_active_admin_user def current_active_admin_user? !!current_active_admin_user end helper_method :current_active_admin_user? def active_admin_config self.class.active_admin_config end helper_method :active_admin_config def active_admin_namespace active_admin_config.namespace end helper_method :active_admin_namespace ACTIVE_ADMIN_ACTIONS = [:index, :show, :new, :create, :edit, :update, :destroy] def active_admin_root controller, action = active_admin_namespace.root_to.split "#" { controller: controller, action: action } end def page_presenter active_admin_config.get_page_presenter(params[:action].to_sym) || default_page_presenter end helper_method :page_presenter def default_page_presenter PagePresenter.new end def page_title if page_presenter[:title] helpers.render_or_call_method_or_proc_on(self, page_presenter[:title]) else default_page_title end end helper_method :page_title def default_page_title active_admin_config.name end DEFAULT_DOWNLOAD_FORMATS = [:csv, :xml, :json] def build_download_formats(download_links) download_links = instance_exec(&download_links) if download_links.is_a?(Proc) if download_links.is_a?(Array) && !download_links.empty? download_links elsif download_links == false [] else DEFAULT_DOWNLOAD_FORMATS end end helper_method :build_download_formats ActiveSupport.run_load_hooks(:active_admin_controller, self) end end
ruby
MIT
b9d630ce22a739d57c9c8b9976807a370e4de140
2026-01-04T15:38:25.641812Z
false
activeadmin/activeadmin
https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/app/controllers/active_admin/base_controller/menu.rb
app/controllers/active_admin/base_controller/menu.rb
# frozen_string_literal: true module ActiveAdmin class BaseController < ::InheritedResources::Base module Menu extend ActiveSupport::Concern included do before_action :set_current_menu_item helper_method :current_menu helper_method :current_menu_item? end protected def current_menu active_admin_config.navigation_menu end def current_menu_item?(item) item.current?(@current_menu_item) end def set_current_menu_item @current_menu_item = if current_menu && active_admin_config.belongs_to? && parent? parent_item = active_admin_config.belongs_to_config.target.menu_item if current_menu.include? parent_item parent_item else active_admin_config.menu_item end else active_admin_config.menu_item end end end end end
ruby
MIT
b9d630ce22a739d57c9c8b9976807a370e4de140
2026-01-04T15:38:25.641812Z
false
activeadmin/activeadmin
https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/app/controllers/active_admin/base_controller/authorization.rb
app/controllers/active_admin/base_controller/authorization.rb
# frozen_string_literal: true module ActiveAdmin class BaseController < ::InheritedResources::Base module Authorization extend ActiveSupport::Concern ACTIONS_DICTIONARY = { index: ActiveAdmin::Authorization::READ, show: ActiveAdmin::Authorization::READ, new: ActiveAdmin::Authorization::NEW, create: ActiveAdmin::Authorization::CREATE, edit: ActiveAdmin::Authorization::EDIT, update: ActiveAdmin::Authorization::UPDATE, destroy: ActiveAdmin::Authorization::DESTROY } included do rescue_from ActiveAdmin::AccessDenied, with: :dispatch_active_admin_access_denied helper_method :authorized? helper_method :authorize! helper_method :active_admin_authorization end protected # Authorize the action and subject. Available in the controller # as well as all the views. # # @param [Symbol] action The action to check if the user has permission # to perform on the subject. # # @param [any] subject The subject that the user is trying to perform # the action on. # # @return [Boolean] # def authorized?(action, subject = nil) active_admin_authorization.authorized?(action, subject) end # Authorize the action and subject. Available in the controller # as well as all the views. If the action is not allowed, it raises # an ActiveAdmin::AccessDenied exception. # # @param [Symbol] action The action to check if the user has permission # to perform on the subject. # # @param [any] subject The subject that the user is trying to perform # the action on. # # @return [Boolean] True if authorized, otherwise raises # an ActiveAdmin::AccessDenied. def authorize!(action, subject = nil) unless authorized? action, subject raise ActiveAdmin::AccessDenied.new( current_active_admin_user, action, subject) end end # Performs authorization on the resource using the current controller # action as the permission action. # def authorize_resource!(resource) permission = action_to_permission(params[:action]) authorize! permission, resource end # Retrieve or instantiate the authorization instance for this resource # # @return [ActiveAdmin::AuthorizationAdapter] def active_admin_authorization @active_admin_authorization ||= active_admin_authorization_adapter.new active_admin_config, current_active_admin_user end # Returns the class to be used as the authorization adapter # # @return [Class] def active_admin_authorization_adapter adapter = active_admin_namespace.authorization_adapter if adapter.is_a? String adapter.constantize else adapter end end # Converts a controller action into one of the correct Active Admin # authorization names. Uses the ACTIONS_DICTIONARY to convert the # action name to permission. # # @param [String, Symbol] action The controller action name. # # @return [Symbol] The permission name to use. def action_to_permission(action) if action && action = action.to_sym Authorization::ACTIONS_DICTIONARY[action] || action end end def dispatch_active_admin_access_denied(exception) instance_exec(self, exception, &active_admin_namespace.on_unauthorized_access.to_proc) end def rescue_active_admin_access_denied(exception) error = exception.message respond_to do |format| format.html do flash[:error] = error redirect_backwards_or_to_root end format.csv { render body: error, status: :unauthorized } format.json { render json: { error: error }, status: :unauthorized } format.xml { render xml: "<error>#{error}</error>", status: :unauthorized } end end def redirect_backwards_or_to_root redirect_back fallback_location: active_admin_root end end end end
ruby
MIT
b9d630ce22a739d57c9c8b9976807a370e4de140
2026-01-04T15:38:25.641812Z
false
activeadmin/activeadmin
https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/app/controllers/active_admin/resource_controller/resource_class_methods.rb
app/controllers/active_admin/resource_controller/resource_class_methods.rb
# frozen_string_literal: true module ActiveAdmin class ResourceController < BaseController module ResourceClassMethods # Override the default `resource_class` class and instance # methods to only return the class defined in the instance # of ActiveAdmin::Resource def override_resource_class_methods! class_exec do def self.resource_class=(klass); end def self.resource_class @active_admin_config ? @active_admin_config.resource_class : nil end private def resource_class self.class.resource_class end end end end end end
ruby
MIT
b9d630ce22a739d57c9c8b9976807a370e4de140
2026-01-04T15:38:25.641812Z
false
activeadmin/activeadmin
https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/app/controllers/active_admin/resource_controller/data_access.rb
app/controllers/active_admin/resource_controller/data_access.rb
# frozen_string_literal: true module ActiveAdmin class ResourceController < BaseController # This module overrides most of the data access methods in Inherited # Resources to provide Active Admin with it's data. # # The module also deals with authorization and resource callbacks. # module DataAccess def self.included(base) base.class_exec do include Callbacks include ScopeChain define_active_admin_callbacks :build, :create, :update, :save, :destroy helper_method :current_scope end end protected COLLECTION_APPLIES = [ :authorization_scope, :filtering, :scoping, :sorting, :includes, :pagination, :collection_decorator ].freeze # Retrieve, memoize and authorize the current collection from the db. This # method delegates the finding of the collection to #find_collection. # # Once #collection has been called, the collection is available using # either the @collection instance variable or an instance variable named # after the resource that the collection is for. eg: Post => @post. # # @return [ActiveRecord::Relation] The collection for the index def collection get_collection_ivar || begin collection = find_collection authorize! Authorization::READ, active_admin_config.resource_class set_collection_ivar collection end end # Does the actual work of retrieving the current collection from the db. # This is a great method to override if you would like to perform # some additional db # work before your controller returns and # authorizes the collection. # # @return [ActiveRecord::Relation] The collection for the index def find_collection(options = {}) collection = scoped_collection collection_applies(options).each do |applyer| collection = send(:"apply_#{applyer}", collection) end collection end # Override this method in your controllers to modify the start point # of our searches and index. # # This method should return an ActiveRecord::Relation object so that # the searching and filtering can be applied on top # # Note, unless you are doing something special, you should use the # scope_to method from the Scoping module instead of overriding this # method. def scoped_collection end_of_association_chain end # Retrieve, memoize and authorize a resource based on params[:id]. The # actual work of finding the resource is done in #find_resource. # # This method is used on all the member actions: # # * show # * edit # * update # * destroy # # @return [ActiveRecord::Base] An active record object def resource get_resource_ivar || begin resource = find_resource resource = apply_decorations(resource) authorize_resource! resource set_resource_ivar resource end end # Does the actual work of finding a resource in the database. This # method uses the finder method as defined in InheritedResources. # # @return [ActiveRecord::Base] An active record object. def find_resource scoped_collection.send method_for_find, params[:id] end # Builds, memoize and authorize a new instance of the resource. The # actual work of building the new instance is delegated to the # #build_new_resource method. # # This method is used to instantiate and authorize new resources in the # new and create controller actions. # # @return [ActiveRecord::Base] An un-saved active record base object def build_resource get_resource_ivar || begin resource = build_new_resource resource = apply_decorations(resource) resource = assign_attributes(resource, resource_params) run_build_callbacks resource authorize_resource! resource set_resource_ivar resource end end # Builds a new resource. This method uses the method_for_build provided # by Inherited Resources. # # @return [ActiveRecord::Base] An un-saved active record base object def build_new_resource apply_authorization_scope(scoped_collection).send( method_for_build, *resource_params.map { |params| params.slice(active_admin_config.resource_class.inheritance_column) } ) end # Calls all the appropriate callbacks and then creates the new resource. # # @param [ActiveRecord::Base] object The new resource to create # # @return [void] def create_resource(object) run_create_callbacks object do save_resource(object) end end # Calls all the appropriate callbacks and then saves the new resource. # # @param [ActiveRecord::Base] object The new resource to save # # @return [void] def save_resource(object) run_save_callbacks object do object.save end end # Update an object with the given attributes. Also calls the appropriate # callbacks for update action. # # @param [ActiveRecord::Base] object The instance to update # # @param [Array] attributes An array with the attributes in the first position # and the Active Record "role" in the second. The role # may be set to nil. # # @return [void] def update_resource(object, attributes) status = nil ActiveRecord::Base.transaction do object = assign_attributes(object, attributes) run_update_callbacks object do status = save_resource(object) raise ActiveRecord::Rollback unless status end end status end # Destroys an object from the database and calls appropriate callbacks. # # @return [void] def destroy_resource(object) run_destroy_callbacks object do object.destroy end end # # Collection Helper Methods # # Gives the authorization library a change to pre-scope the collection. # # In the case of the CanCan adapter, it calls `#accessible_by` on # the collection. # # @param [ActiveRecord::Relation] collection The collection to scope # # @return [ActiveRecord::Relation] a scoped collection of query def apply_authorization_scope(collection) action_name = action_to_permission(params[:action]) active_admin_authorization.scope_collection(collection, action_name) end def apply_sorting(chain) params[:order] ||= active_admin_config.sort_order order_clause = active_admin_config.order_clause.new(active_admin_config, params[:order]) if order_clause.valid? order_clause.apply(chain) else chain # just return the chain end end # Applies any Ransack search methods to the currently scoped collection. # Both `search` and `ransack` are provided, but we use `ransack` to prevent conflicts. def apply_filtering(chain) @search = chain.ransack(params[:q] || {}, auth_object: active_admin_authorization) @search.result end def apply_scoping(chain) @collection_before_scope = chain if current_scope scope_chain(current_scope, chain) else chain end end def apply_includes(chain) if active_admin_config.includes.any? chain.includes(*active_admin_config.includes) else chain end end def collection_before_scope @collection_before_scope end def current_scope @current_scope ||= if params[:scope] active_admin_config.get_scope_by_id(params[:scope]) else active_admin_config.default_scope(self) end end def apply_pagination(chain) # skip pagination if CSV format was requested return chain if params["format"] == "csv" # skip pagination if already was paginated by scope return chain if chain.respond_to?(:total_pages) page = params[Kaminari.config.param_name] paginate(chain, page, per_page) end def collection_applies(options = {}) only = Array(options.fetch(:only, COLLECTION_APPLIES)) except = Array(options.fetch(:except, [])) COLLECTION_APPLIES & only - except end def in_paginated_batches(&block) ActiveRecord::Base.uncached do (1..paginated_collection.total_pages).each do |page| paginated_collection(page).each do |resource| yield apply_decorator(resource) end end end end def per_page if active_admin_config.paginate dynamic_per_page || configured_per_page else active_admin_config.max_per_page end end def dynamic_per_page params[:per_page] || @per_page end def configured_per_page Array(active_admin_config.per_page).first end # @param resource [ActiveRecord::Base] # @param attributes [Array<Hash] # @return [ActiveRecord::Base] resource # def assign_attributes(resource, attributes) if resource.respond_to?(:assign_attributes) resource.assign_attributes(*attributes) else resource.attributes = attributes[0] end resource end # @param resource [ActiveRecord::Base] # @return [ActiveRecord::Base] resource # def apply_decorations(resource) apply_decorator(resource) end # @return [String] def smart_resource_url if create_another? new_resource_url(create_another: params[:create_another]) else super end end private # @return [Boolean] true if user requested to create one more # resource after creating this one. def create_another? params[:create_another].present? end def paginated_collection(page_no = 1) paginate(collection, page_no, batch_size) end def paginate(chain, page, per_page) page_method_name = Kaminari.config.page_method_name chain.public_send(page_method_name, page).per(per_page) end def batch_size 1000 end end end end
ruby
MIT
b9d630ce22a739d57c9c8b9976807a370e4de140
2026-01-04T15:38:25.641812Z
false
activeadmin/activeadmin
https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/app/controllers/active_admin/resource_controller/scoping.rb
app/controllers/active_admin/resource_controller/scoping.rb
# frozen_string_literal: true module ActiveAdmin class ResourceController < BaseController # This module deals with scoping entire controllers to a relation module Scoping extend ActiveSupport::Concern protected # Override the default InheritedResource #begin_of_association_chain to allow # the scope to be defined in the active admin configuration. # # If scope_to is a proc, we eval it, otherwise we call the method on the controller. # # Collection can be scoped conditionally with an :if or :unless proc. def begin_of_association_chain return nil unless active_admin_config.scope_to?(self) helpers.render_in_context(self, active_admin_config.scope_to_method) end # Overriding from InheritedResources::BaseHelpers # # Returns the method for the association chain when using # the scope_to option def method_for_association_chain active_admin_config.scope_to_association_method || super end end end end
ruby
MIT
b9d630ce22a739d57c9c8b9976807a370e4de140
2026-01-04T15:38:25.641812Z
false
activeadmin/activeadmin
https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/app/controllers/active_admin/resource_controller/streaming.rb
app/controllers/active_admin/resource_controller/streaming.rb
# frozen_string_literal: true require "csv" module ActiveAdmin class ResourceController < BaseController # This module overrides CSV responses to allow large data downloads. # Could be expanded to JSON and XML in the future. # module Streaming def index super do |format| format.csv { stream_csv } yield(format) if block_given? end end protected def stream_resource(&block) headers["X-Accel-Buffering"] = "no" headers["Cache-Control"] = "no-cache" headers["Last-Modified"] = Time.current.httpdate if ActiveAdmin.application.disable_streaming_in.include? Rails.env self.response_body = block[String.new] # rubocop:disable Performance/UnfreezeString to preserve encoding else self.response_body = Enumerator.new(&block) end end def csv_filename "#{resource_collection_name.to_s.tr('_', '-')}-#{Time.zone.now.to_date}.csv" end def stream_csv headers["Content-Type"] = "text/csv; charset=utf-8" # In Rails 5 it's set to HTML?? headers["Content-Disposition"] = %{attachment; filename="#{csv_filename}"} stream_resource(&active_admin_config.csv_builder.method(:build).to_proc.curry[self]) end end end end
ruby
MIT
b9d630ce22a739d57c9c8b9976807a370e4de140
2026-01-04T15:38:25.641812Z
false
activeadmin/activeadmin
https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/app/controllers/active_admin/resource_controller/polymorphic_routes.rb
app/controllers/active_admin/resource_controller/polymorphic_routes.rb
# frozen_string_literal: true require "active_admin/resource" require "active_admin/resource/model" module ActiveAdmin class ResourceController < BaseController module PolymorphicRoutes def polymorphic_url(record_or_hash_or_array, options = {}) super(map_named_resources_for(record_or_hash_or_array), options) end def polymorphic_path(record_or_hash_or_array, options = {}) super(map_named_resources_for(record_or_hash_or_array), options) end private def map_named_resources_for(record_or_hash_or_array) return record_or_hash_or_array unless record_or_hash_or_array.is_a?(Array) record_or_hash_or_array.map { |record| to_named_resource(record) } end def to_named_resource(record) if record.is_a?(resource_class) return ActiveAdmin::Model.new(active_admin_config, record) end belongs_to_resource = active_admin_config.belongs_to_config.try(:resource) if belongs_to_resource && record.is_a?(belongs_to_resource.resource_class) return ActiveAdmin::Model.new(belongs_to_resource, record) end record end end end end
ruby
MIT
b9d630ce22a739d57c9c8b9976807a370e4de140
2026-01-04T15:38:25.641812Z
false
activeadmin/activeadmin
https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/app/controllers/active_admin/resource_controller/action_builder.rb
app/controllers/active_admin/resource_controller/action_builder.rb
# frozen_string_literal: true module ActiveAdmin class ResourceController < BaseController module ActionBuilder extend ActiveSupport::Concern module ClassMethods def clear_member_actions! remove_action_methods(:member) active_admin_config.clear_member_actions! end def clear_collection_actions! remove_action_methods(:collection) active_admin_config.clear_collection_actions! end private def remove_action_methods(actions_type) active_admin_config.public_send(:"#{actions_type}_actions").each do |action| remove_method action.name end end end end end end
ruby
MIT
b9d630ce22a739d57c9c8b9976807a370e4de140
2026-01-04T15:38:25.641812Z
false
activeadmin/activeadmin
https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/app/controllers/active_admin/resource_controller/decorators.rb
app/controllers/active_admin/resource_controller/decorators.rb
# frozen_string_literal: true module ActiveAdmin class ResourceController < BaseController module Decorators protected def apply_decorator(resource) decorate? ? decorator_class.new(resource) : resource end def apply_collection_decorator(collection) if decorate? collection_decorator.decorate collection, with: decorator_class else collection end end def self.undecorate(resource) if resource.respond_to?(:decorated?) && resource.decorated? resource.model else resource end end private def decorate? case action_name when "new", "edit", "create", "update" form = active_admin_config.get_page_presenter :form form && form.options[:decorate] && decorator_class.present? else decorator_class.present? end end def decorator_class active_admin_config.decorator_class end # When using Draper, we wrap the collection draper in a new class that # correctly delegates methods that Active Admin depends on. def collection_decorator if decorator_class Wrapper.wrap decorator_class end end class Wrapper @cache = {} def self.wrap(decorator) collection_decorator = find_collection_decorator(decorator) name = "#{collection_decorator.name} of #{decorator} + ActiveAdmin" @cache[name] ||= wrap! collection_decorator, name end def self.wrap!(parent, name) ::Class.new parent do delegate :reorder, :page, :current_page, :total_pages, :limit_value, :total_count, :offset, :to_key, :group_values, :except, :find_each, :ransack, to: :object define_singleton_method(:name) { name } end end def self.find_collection_decorator(decorator) if decorator.respond_to?(:collection_decorator_class) decorator.collection_decorator_class else CollectionDecorator end end end end end end
ruby
MIT
b9d630ce22a739d57c9c8b9976807a370e4de140
2026-01-04T15:38:25.641812Z
false
activeadmin/activeadmin
https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/features/support/rails.rb
features/support/rails.rb
# frozen_string_literal: true require "cucumber/rails/application" require "cucumber/rails/action_dispatch" require "cucumber/rails/world" require "cucumber/rails/hooks" require "cucumber/rails/capybara" require "cucumber/rails/database/strategy" require "cucumber/rails/database/deletion_strategy" require "cucumber/rails/database/null_strategy" require "cucumber/rails/database/shared_connection_strategy" require "cucumber/rails/database/truncation_strategy" require "cucumber/rails/database" MultiTest.disable_autorun
ruby
MIT
b9d630ce22a739d57c9c8b9976807a370e4de140
2026-01-04T15:38:25.641812Z
false
activeadmin/activeadmin
https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/features/support/simplecov_regular_env.rb
features/support/simplecov_regular_env.rb
# frozen_string_literal: true if ENV["COVERAGE"] == "true" require "simplecov" SimpleCov.command_name ["regular features", ENV["TEST_ENV_NUMBER"]].join(" ").rstrip end require_relative "env"
ruby
MIT
b9d630ce22a739d57c9c8b9976807a370e4de140
2026-01-04T15:38:25.641812Z
false
activeadmin/activeadmin
https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/features/support/simplecov_changes_env.rb
features/support/simplecov_changes_env.rb
# frozen_string_literal: true if ENV["COVERAGE"] == "true" require "simplecov" SimpleCov.command_name "filesystem changes features" end require_relative "env"
ruby
MIT
b9d630ce22a739d57c9c8b9976807a370e4de140
2026-01-04T15:38:25.641812Z
false
activeadmin/activeadmin
https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/features/support/env.rb
features/support/env.rb
# frozen_string_literal: true ENV["RAILS_ENV"] = "test" require "simplecov" if ENV["COVERAGE"] == "true" Dir["#{File.expand_path('../step_definitions', __dir__)}/*.rb"].each do |f| require f end require_relative "../../tasks/test_application" require "#{ActiveAdmin::TestApplication.new.full_app_dir}/config/environment.rb" require_relative "rails" require_relative "../../spec/support/active_support_deprecation" require "rspec/mocks" World(RSpec::Mocks::ExampleMethods) Around "@mocks" do |scenario, block| RSpec::Mocks.setup block.call begin RSpec::Mocks.verify ensure RSpec::Mocks.teardown end end After "@debug" do |scenario| # :nocov: save_and_open_page if scenario.failed? # :nocov: end require "capybara/cuprite" Capybara.register_driver(:cuprite) do |app| Capybara::Cuprite::Driver.new(app, process_timeout: 30, timeout: 30) end Capybara.javascript_driver = :cuprite Capybara.server = :webrick Capybara.asset_host = "http://localhost:3000" # Capybara defaults to XPath selectors rather than Webrat's default of CSS3. In # order to ease the transition to Capybara we set the default here. If you'd # prefer to use XPath just remove this line and adjust any selectors in your # steps to use the XPath syntax. Capybara.default_selector = :css # Database resetting strategy DatabaseCleaner.strategy = :truncation Cucumber::Rails::Database.javascript_strategy = :truncation # Warden helpers to speed up login # See https://github.com/heartcombo/devise/wiki/How-To:-Test-with-Capybara include Warden::Test::Helpers After do Warden.test_reset! end Before do # Reload Active Admin ActiveAdmin.unload! ActiveAdmin.load! end # Force deprecations to raise an exception. ActiveAdmin::DeprecationHelper.behavior = :raise After "@authorization" do |scenario, block| # Reset back to the default auth adapter ActiveAdmin.application.namespace(:admin). authorization_adapter = ActiveAdmin::AuthorizationAdapter end Around "@silent_unpermitted_params_failure" do |scenario, block| original = ActionController::Parameters.action_on_unpermitted_parameters begin ActionController::Parameters.action_on_unpermitted_parameters = false block.call ensure ActionController::Parameters.action_on_unpermitted_parameters = original end end Around "@locale_manipulation" do |scenario, block| I18n.with_locale(:en, &block) end class CustomIndexView < ActiveAdmin::Component def build(page_presenter, collection) add_class "custom-index-view" resource_selection_toggle_panel if active_admin_config.batch_actions.any? collection.each do |obj| instance_exec(obj, &page_presenter.block) end end def self.index_name "custom" end end
ruby
MIT
b9d630ce22a739d57c9c8b9976807a370e4de140
2026-01-04T15:38:25.641812Z
false
activeadmin/activeadmin
https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/features/support/paths.rb
features/support/paths.rb
# frozen_string_literal: true module NavigationHelpers # Maps a name to a path. Used by the # # When /^I go to (.+)$/ do |page_name| # # step definition in web_steps.rb # def path_to(page_name) case page_name when /the dashboard/ "/admin" when /the new post page/ "/admin/posts/new" when /the login page/ "/admin/login" when /the first post custom status page/ "/admin/posts/1/status" when /the last posts page/ "/admin/last_posts" when /the admin password reset form with token "([^"]*)"/ "/admin/password/edit?reset_password_token=#{$1}" # the index page for posts in the user_admin namespace when /^the index page for (.*) in the (.*) namespace$/ send :"#{$2}_#{$1}_path" # same as above, except defaults to admin namespace when /^the index page for (.*)$/ send :"admin_#{$1}_path" when /^the (.*) index page for (.*)$/ send :"admin_#{$2}_path", format: $1 when /^the last author's posts$/ admin_user_posts_path(User.last) when /^the last author's last post page$/ admin_user_post_path(User.last, Post.where(author_id: User.last.id).last) when /^the last post's show page$/ admin_post_path(Post.last) when /^the post's show page$/ admin_post_path(Post.last) when /^the last post's edit page$/ edit_admin_post_path(Post.last) when /^the last author's show page$/ admin_user_path(User.last) # Add more mappings here. # Here is an example that pulls values out of the Regexp: # # when /^(.*)'s profile page$/i # user_profile_path(User.find_by_login($1)) else begin page_name =~ /the (.*) page/ path_components = $1.split(/\s+/) self.send path_components.push("path").join("_") # :nocov: rescue Object raise "Can't find mapping from \"#{page_name}\" to a path.\n" + "Now, go and add a mapping in #{__FILE__}" # :nocov: end end end end World(NavigationHelpers)
ruby
MIT
b9d630ce22a739d57c9c8b9976807a370e4de140
2026-01-04T15:38:25.641812Z
false
activeadmin/activeadmin
https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/features/support/simplecov_reload_env.rb
features/support/simplecov_reload_env.rb
# frozen_string_literal: true if ENV["COVERAGE"] == "true" require "simplecov" SimpleCov.command_name "reload features" end require_relative "env"
ruby
MIT
b9d630ce22a739d57c9c8b9976807a370e4de140
2026-01-04T15:38:25.641812Z
false
activeadmin/activeadmin
https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/features/step_definitions/root_steps.rb
features/step_definitions/root_steps.rb
# frozen_string_literal: true Around "@root" do |scenario, block| previous_root = ActiveAdmin.application.root_to begin block.call ensure ActiveAdmin.application.root_to = previous_root end end
ruby
MIT
b9d630ce22a739d57c9c8b9976807a370e4de140
2026-01-04T15:38:25.641812Z
false
activeadmin/activeadmin
https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/features/step_definitions/i18n_steps.rb
features/step_definitions/i18n_steps.rb
# frozen_string_literal: true When(/^I set my locale to "([^"]*)"$/) do |lang| I18n.locale = lang end
ruby
MIT
b9d630ce22a739d57c9c8b9976807a370e4de140
2026-01-04T15:38:25.641812Z
false
activeadmin/activeadmin
https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/features/step_definitions/factory_steps.rb
features/step_definitions/factory_steps.rb
# frozen_string_literal: true def create_user(name, type = "User") first_name, last_name = name.split(" ") type.camelize.constantize.where(first_name: first_name, last_name: last_name).first_or_create(username: name.tr(" ", "").underscore) end Given(/^(a|\d+)( published)?( unstarred|starred)? posts?(?: with the title "([^"]*)")?(?: and body "([^"]*)")?(?: written by "([^"]*)")?(?: in category "([^"]*)")? exists?$/) do |count, published, starred, title, body, user, category_name| count = count == "a" ? 1 : count.to_i published = Time.now if published starred = starred == " starred" if starred author = create_user(user) if user category = Category.where(name: category_name).first_or_create if category_name title ||= "Hello World %i" count.times do |i| Post.create! title: title % i, body: body, author: author, published_date: published, custom_category_id: category.try(:id), starred: starred end end Given(/^a category named "([^"]*)" exists$/) do |name| Category.create! name: name end Given(/^a (user|publisher) named "([^"]*)" exists$/) do |type, name| create_user name, type end Given(/^a store named "([^"]*)" exists$/) do |name| Store.create! name: name end Given(/^a tag named "([^"]*)" exists$/) do |name| Tag.create! name: name end Given(/^a company named "([^"]*)"(?: with a store named "([^"]*)")? exists$/) do |name, store_name| store = Store.create! name: store_name if store_name Company.create! name: name, stores: [store].compact end Given(/^I create a new post with the title "([^"]*)"$/) do |title| first(:link, "Posts").click click_on "New Post" fill_in "post_title", with: title click_on "Create Post" end
ruby
MIT
b9d630ce22a739d57c9c8b9976807a370e4de140
2026-01-04T15:38:25.641812Z
false
activeadmin/activeadmin
https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/features/step_definitions/action_item_steps.rb
features/step_definitions/action_item_steps.rb
# frozen_string_literal: true Then(/^I should see an action item link to "([^"]*)"$/) do |link| expect(page).to have_css("[data-test-action-items] > a", text: link) end Then(/^I should not see an action item link to "([^"]*)"$/) do |link| expect(page).to have_no_css("[data-test-action-items] > a", text: link) end
ruby
MIT
b9d630ce22a739d57c9c8b9976807a370e4de140
2026-01-04T15:38:25.641812Z
false
activeadmin/activeadmin
https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/features/step_definitions/format_steps.rb
features/step_definitions/format_steps.rb
# frozen_string_literal: true require "csv" Around "@csv" do |scenario, block| default_csv_options = ActiveAdmin.application.csv_options default_disable_streaming_in = ActiveAdmin.application.disable_streaming_in begin block.call ensure ActiveAdmin.application.disable_streaming_in = default_disable_streaming_in ActiveAdmin.application.csv_options = default_csv_options end end Then "I should see nicely formatted datetimes" do expect(page.body).to match(/\w+ \d{1,2}, \d{4} \d{2}:\d{2}/) end Then(/^I should( not)? see a link to download "([^"]*)"$/) do |negate, format| method = negate ? :to_not : :to expect(page).send method, have_css("a", text: format) end # Check first rows of the displayed CSV. Then(/^I should download a CSV file with "([^"]*)" separator for "([^"]*)" containing:$/) do |sep, resource_name, table| body = page.driver.response.body content_type_header, content_disposition_header, last_modified_header = %w[Content-Type Content-Disposition Last-Modified].map do |header_name| page.response_headers[header_name] end expect(content_type_header).to eq "text/csv; charset=utf-8" expect(content_disposition_header).to match(/\Aattachment; filename=".+?\.csv"\z/) expect(last_modified_header).to_not be_nil expect(Date.strptime(last_modified_header, "%a, %d %b %Y %H:%M:%S GMT")).to be_a(Date) csv = CSV.parse(body, col_sep: sep) table.raw.each_with_index do |expected_row, row_index| expected_row.each_with_index do |expected_cell, col_index| cell = csv.try(:[], row_index).try(:[], col_index) if expected_cell.blank? expect(cell).to eq nil else expect(cell || "").to match(/#{expected_cell}/) end end end end Then(/^I should download a CSV file for "([^"]*)" containing:$/) do |resource_name, table| step %{I should download a CSV file with "," separator for "#{resource_name}" containing:}, table end Then(/^the CSV file should contain "([^"]*)" in quotes$/) do |text| expect(page.driver.response.body).to match(/"#{text}"/) end Then(/^the encoding of the CSV file should be "([^"]*)"$/) do |text| expect(page.driver.response.body.encoding).to be Encoding.find(Encoding.aliases[text] || text) end Then(/^the CSV file should start with BOM$/) do expect(page.driver.response.body.bytes).to start_with(239, 187, 191) end Then(/^access denied$/) do expect(page).to have_content(I18n.t("active_admin.access_denied.message")) end
ruby
MIT
b9d630ce22a739d57c9c8b9976807a370e4de140
2026-01-04T15:38:25.641812Z
false
activeadmin/activeadmin
https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/features/step_definitions/web_steps.rb
features/step_definitions/web_steps.rb
# frozen_string_literal: true require "uri" require File.expand_path(File.join(__dir__, "..", "support", "paths")) module WithinHelpers def with_scope(locator) locator ? within(*selector_for(locator)) { yield } : yield end private def selector_for(locator) case locator # Add more mappings here. # Here is an example that pulls values out of the Regexp: # # when /^the (notice|error|info) flash$/ # ".flash.#{$1}" # You can also return an array to use a different selector # type, like: # # when /the header/ # [:xpath, "//header"] when /^the "([^"]*)" sidebar$/ [:css, "##{$1.tr(" ", '').underscore}_sidebar_section"] # This allows you to provide a quoted selector as the scope # for "within" steps as was previously the default for the # web steps: when /^"(.+)"$/ $1 else # :nocov: raise "Can't find mapping from \"#{locator}\" to a selector.\n" + "Now, go and add a mapping in #{__FILE__}" # :nocov: end end end World(WithinHelpers) When(/^(.*) within (.*)$/) do |step_name, parent| with_scope(parent) { step step_name } end Given(/^I am on (.+)$/) do |page_name| visit path_to(page_name) end When(/^I go to (.+)$/) do |page_name| visit path_to(page_name) end When(/^I visit (.+) twice$/) do |page_name| 2.times { visit path_to(page_name) } end When(/^I press "([^"]*)"$/) do |button| click_on(button) end When(/^I follow "([^"]*)"$/) do |link| first(:link, link).click end When(/^I click "(.*?)"$/) do |link| click_on(link) end When(/^I fill in "([^"]*)" with "([^"]*)"$/) do |field, value| fill_in(field, with: value) end When(/^I select "([^"]*)" from "([^"]*)"$/) do |value, field| select(value, from: field) end When(/^I (check|uncheck) "([^"]*)"$/) do |action, field| send action, field end Then(/^I should( not)? see( the element)? "([^"]*)"$/) do |negate, is_css, text| should = negate ? :not_to : :to have = is_css ? have_css(text) : have_content(text) expect(page).send should, have end Then(/^I should see the select "([^"]*)" with options "([^"]+)"?$/) do |label, with_options| expect(page).to have_select(label, with_options: with_options.split(", ")) end Then(/^I should see the field "([^"]*)" of type "([^"]+)"?$/) do |label, of_type| expect(page).to have_field(label, type: of_type) end Then(/^the "([^"]*)" field(?: within (.*))? should contain "([^"]*)"$/) do |field, parent, value| with_scope(parent) do field = find_field(field) value = field.tag_name == "textarea" ? field.text : field.value expect(value).to match(/#{value}/) end end Then(/^the "([^"]*)" select(?: within (.*))? should have "([^"]+)" selected$/) do |label, parent, option| with_scope(parent) do expect(page).to have_select(label, selected: option) end end Then(/^the "([^"]*)" checkbox(?: within (.*))? should( not)? be checked$/) do |label, parent, negate| with_scope(parent) do checkbox = find_field(label) if negate expect(checkbox).not_to be_checked else expect(checkbox).to be_checked end end end Then(/^I should be on (.+)$/) do |page_name| expect(URI.parse(current_url).path).to eq path_to page_name end Then(/^I should see content "(.*?)" above other content "(.*?)"$/) do |top_title, bottom_title| expect(page).to have_css %Q(div:contains('#{top_title}') + div:contains('#{bottom_title}')) end Then(/^I should see a flash with "([^"]*)"$/) do |text| expect(page).to have_content text end
ruby
MIT
b9d630ce22a739d57c9c8b9976807a370e4de140
2026-01-04T15:38:25.641812Z
false
activeadmin/activeadmin
https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/features/step_definitions/pagination_steps.rb
features/step_definitions/pagination_steps.rb
# frozen_string_literal: true Then(/^I should not see pagination$/) do expect(page).to have_no_css "[data-test-pagination]" end Then(/^I should see pagination page (\d+) link$/) do |num| expect(page).to have_css "[data-test-pagination] a", text: num, count: 1 end Then(/^I should see the pagination "Next" link/) do expect(page).to have_css "[data-test-pagination] a", text: "Next" end Then(/^I should not see the pagination "Next" link/) do expect(page).to have_no_css "[data-test-pagination] a", text: "Next" end
ruby
MIT
b9d630ce22a739d57c9c8b9976807a370e4de140
2026-01-04T15:38:25.641812Z
false
activeadmin/activeadmin
https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/features/step_definitions/table_steps.rb
features/step_definitions/table_steps.rb
# frozen_string_literal: true Then(/^I should see (\d+) ([\w]*) in the table$/) do |count, resource_type| expect(page).to have_css(".data-table tr > td:first-child", count: count.to_i) end Then("I should see {string} in the table") do |string| expect(page).to have_css(".data-table tr > td", text: string) end Then("I should not see {string} in the table") do |string| expect(page).to have_no_css(".data-table tr > td", text: string) end Then(/^I should see an id_column link to edit page$/) do expect(page).to have_css(".data-table a[href*='/edit']", text: /^\d+$/) end # TODO: simplify this, if possible? class HtmlTableToTextHelper def initialize(html, table_css_selector = "table") @html = html @selector = table_css_selector end def to_array rows = Nokogiri::HTML(@html).css("#{@selector} tr") rows.map do |row| row.css("th, td").map do |td| cell_to_string(td) end end end private def cell_to_string(td) str = "" input = td.css("input").last if input str += input_to_string(input) end str + td.content.strip.tr("\n", " ") end def input_to_string(input) case input.attribute("type").value when "checkbox" "[ ]" else # :nocov: raise "I don't know what to do with #{input}" # :nocov: end end end module TableMatchHelper # @param table [Array[Array]] # @param expected_table [Array[Array[String]]] # The expected_table values are String. They are converted to # Regexp when they start and end with a '/' # Example: # # assert_table_match( # [["Name", "Date"], ["Philippe", "Feb 08"]], # [["Name", "Date"], ["Philippe", "/\w{3} \d{2}/"]] # ) def assert_tables_match(table, expected_table) expected_table.each_index do |row_index| expected_table[row_index].each_index do |column_index| expected_cell = expected_table[row_index][column_index] cell = table.try(:[], row_index).try(:[], column_index) begin assert_cells_match(cell, expected_cell) rescue # :nocov: puts "Cell at line #{row_index} and column #{column_index}: #{cell.inspect} does not match #{expected_cell.inspect}" puts "Expecting:" table.each { |row| puts row.inspect } puts "to match:" expected_table.each { |row| puts row.inspect } raise $! # :nocov: end end end end def assert_cells_match(cell, expected_cell) if /^\/.*\/$/.match?(expected_cell) expect(cell).to match(/#{expected_cell[1..-2]}/) else expect((cell || "").strip).to eq expected_cell end end end World(TableMatchHelper) # Usage: # # I should see the "invoices" table: # | Invoice # | Date | Total Amount | # | /\d+/ | 27/01/12 | $30.00 | # | /\d+/ | 12/02/12 | $25.00 | # Then(/^I should see the "([^"]*)" table:$/) do |table_id, expected_table| expect(page).to have_css "table##{table_id}" assert_tables_match( HtmlTableToTextHelper.new(page.body, "table##{table_id}").to_array, expected_table.raw ) end
ruby
MIT
b9d630ce22a739d57c9c8b9976807a370e4de140
2026-01-04T15:38:25.641812Z
false
activeadmin/activeadmin
https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/features/step_definitions/configuration_steps.rb
features/step_definitions/configuration_steps.rb
# frozen_string_literal: true module ActiveAdminReloading def load_aa_config(config_content) ActiveSupport::Notifications.instrument ActiveAdmin::Application::BeforeLoadEvent, { active_admin_application: ActiveAdmin.application } eval(config_content) ActiveSupport::Notifications.instrument ActiveAdmin::Application::AfterLoadEvent, { active_admin_application: ActiveAdmin.application } Rails.application.reload_routes! ActiveAdmin.application.namespaces.each(&:reset_menu!) end end World(ActiveAdminReloading) Given(/^a(?:n? (index|show))? configuration of:$/) do |action, config_content| load_aa_config(config_content) case action when "index" step "I am logged in" case resource = config_content.match(/ActiveAdmin\.register (\w+)/)[1] when "Post" step "I am on the index page for posts" when "Category" step "I am on the index page for categories" when "User" step "I am on the index page for users" else # :nocov: raise "#{resource} is not supported" # :nocov: end when "show" case resource = config_content.match(/ActiveAdmin\.register (\w+)/)[1] when "Post" step "I am logged in" step "I am on the index page for posts" step 'I follow "View"' when "User" step "I am logged in" step "I am on the index page for users" step 'I follow "View"' when "Category" step "I am logged in" step "I am on the index page for categories" step 'I follow "View"' when "Tag" step "I am logged in" Tag.create! visit admin_tag_path Tag.last else # :nocov: raise "#{resource} is not supported" # :nocov: end end end
ruby
MIT
b9d630ce22a739d57c9c8b9976807a370e4de140
2026-01-04T15:38:25.641812Z
false
activeadmin/activeadmin
https://github.com/activeadmin/activeadmin/blob/b9d630ce22a739d57c9c8b9976807a370e4de140/features/step_definitions/additional_web_steps.rb
features/step_definitions/additional_web_steps.rb
# frozen_string_literal: true Then(/^I should see a table header with "([^"]*)"$/) do |content| expect(page).to have_xpath "//th", text: content end Then(/^I should not see a table header with "([^"]*)"$/) do |content| expect(page).to have_no_xpath "//th", text: content end Then(/^I should see a sortable table header with "([^"]*)"$/) do |content| expect(page).to have_css "th[data-sortable]", text: content end Then(/^I should not see a sortable table header with "([^"]*)"$/) do |content| expect(page).to have_no_css "th[data-sortable]", text: content end Then(/^I should not see a sortable table header$/) do step %{I should not see "th[data-sortable]"} end Then(/^the table "([^"]*)" should have (\d+) rows/) do |selector, count| trs = page.find(selector).all :css, "tr" expect(trs.size).to eq count.to_i end Then(/^the table "([^"]*)" should have (\d+) columns/) do |selector, count| tds = page.find(selector).find("tr:first").all :css, "td" expect(tds.size).to eq count.to_i end Then(/^there should be (\d+) "([^"]*)" tags?$/) do |count, tag| expect(page.all(:css, tag).size).to eq count.to_i end Then(/^I should see a link to "([^"]*)"$/) do |link| if Capybara.current_driver == Capybara.javascript_driver expect(page).to have_xpath "//a", text: link, wait: 30 else expect(page).to have_xpath "//a", text: link end end Then(/^an "([^"]*)" exception should be raised when I follow "([^"]*)"$/) do |error, link| expect do step "I follow \"#{link}\"" end.to raise_error(error.constantize) end Then(/^I should be in the resource section for (.+)$/) do |resource_name| expect(current_url).to include resource_name.tr(" ", "").underscore.pluralize end Then(/^I should see the page title "([^"]*)"$/) do |title| within("[data-test-page-header]") do expect(page).to have_content title end end Then(/^I should see a fieldset titled "([^"]*)"$/) do |title| expect(page).to have_css "fieldset legend", text: title end Then(/^the "([^"]*)" field should contain the option "([^"]*)"$/) do |field, option| field = find_field(field) expect(field).to have_css "option", text: option end Then(/^I should see the content "([^"]*)"$/) do |content| expect(page).to have_css "[data-test-page-content]", text: content end Then(/^I should see a validation error "([^"]*)"$/) do |error_message| expect(page).to have_css ".inline-errors", text: error_message end Then(/^I should see a table with id "([^"]*)"$/) do |dom_id| page.find("table##{dom_id}") end
ruby
MIT
b9d630ce22a739d57c9c8b9976807a370e4de140
2026-01-04T15:38:25.641812Z
false