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 |
|---|---|---|---|---|---|---|---|---|
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/lib/thor/rake_compat.rb | lib/thor/rake_compat.rb | require "rake"
require "rake/dsl_definition"
class Thor
# Adds a compatibility layer to your Thor classes which allows you to use
# rake package tasks. For example, to use rspec rake tasks, one can do:
#
# require 'thor/rake_compat'
# require 'rspec/core/rake_task'
#
# class Default < Thor
# include Thor::RakeCompat
#
# RSpec::Core::RakeTask.new(:spec) do |t|
# t.spec_opts = ['--options', './.rspec']
# t.spec_files = FileList['spec/**/*_spec.rb']
# end
# end
#
module RakeCompat
include Rake::DSL if defined?(Rake::DSL)
def self.rake_classes
@rake_classes ||= []
end
def self.included(base)
super(base)
# Hack. Make rakefile point to invoker, so rdoc task is generated properly.
rakefile = File.basename(caller[0].match(/(.*):\d+/)[1])
Rake.application.instance_variable_set(:@rakefile, rakefile)
rake_classes << base
end
end
end
# override task on (main), for compatibility with Rake 0.9
instance_eval do
alias rake_namespace namespace
def task(*)
task = super
if klass = Thor::RakeCompat.rake_classes.last # rubocop:disable Lint/AssignmentInCondition
non_namespaced_name = task.name.split(":").last
description = non_namespaced_name
description << task.arg_names.map { |n| n.to_s.upcase }.join(" ")
description.strip!
klass.desc description, Rake.application.last_description || non_namespaced_name
Rake.application.last_description = nil
klass.send :define_method, non_namespaced_name do |*args|
Rake::Task[task.name.to_sym].invoke(*args)
end
end
task
end
def namespace(name)
if klass = Thor::RakeCompat.rake_classes.last # rubocop:disable Lint/AssignmentInCondition
const_name = Thor::Util.camel_case(name.to_s).to_sym
klass.const_set(const_name, Class.new(Thor))
new_klass = klass.const_get(const_name)
Thor::RakeCompat.rake_classes << new_klass
end
super
Thor::RakeCompat.rake_classes.pop
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/lib/thor/group.rb | lib/thor/group.rb | require_relative "base"
# Thor has a special class called Thor::Group. The main difference to Thor class
# is that it invokes all commands at once. It also include some methods that allows
# invocations to be done at the class method, which are not available to Thor
# commands.
class Thor::Group
class << self
# The description for this Thor::Group. If none is provided, but a source root
# exists, tries to find the USAGE one folder above it, otherwise searches
# in the superclass.
#
# ==== Parameters
# description<String>:: The description for this Thor::Group.
#
def desc(description = nil)
if description
@desc = description
else
@desc ||= from_superclass(:desc, nil)
end
end
# Prints help information.
#
# ==== Options
# short:: When true, shows only usage.
#
def help(shell)
shell.say "Usage:"
shell.say " #{banner}\n"
shell.say
class_options_help(shell)
shell.say desc if desc
end
# Stores invocations for this class merging with superclass values.
#
def invocations #:nodoc:
@invocations ||= from_superclass(:invocations, {})
end
# Stores invocation blocks used on invoke_from_option.
#
def invocation_blocks #:nodoc:
@invocation_blocks ||= from_superclass(:invocation_blocks, {})
end
# Invoke the given namespace or class given. It adds an instance
# method that will invoke the klass and command. You can give a block to
# configure how it will be invoked.
#
# The namespace/class given will have its options showed on the help
# usage. Check invoke_from_option for more information.
#
def invoke(*names, &block)
options = names.last.is_a?(Hash) ? names.pop : {}
verbose = options.fetch(:verbose, true)
names.each do |name|
invocations[name] = false
invocation_blocks[name] = block if block_given?
class_eval <<-METHOD, __FILE__, __LINE__ + 1
def _invoke_#{name.to_s.gsub(/\W/, '_')}
klass, command = self.class.prepare_for_invocation(nil, #{name.inspect})
if klass
say_status :invoke, #{name.inspect}, #{verbose.inspect}
block = self.class.invocation_blocks[#{name.inspect}]
_invoke_for_class_method klass, command, &block
else
say_status :error, %(#{name.inspect} [not found]), :red
end
end
METHOD
end
end
# Invoke a thor class based on the value supplied by the user to the
# given option named "name". A class option must be created before this
# method is invoked for each name given.
#
# ==== Examples
#
# class GemGenerator < Thor::Group
# class_option :test_framework, :type => :string
# invoke_from_option :test_framework
# end
#
# ==== Boolean options
#
# In some cases, you want to invoke a thor class if some option is true or
# false. This is automatically handled by invoke_from_option. Then the
# option name is used to invoke the generator.
#
# ==== Preparing for invocation
#
# In some cases you want to customize how a specified hook is going to be
# invoked. You can do that by overwriting the class method
# prepare_for_invocation. The class method must necessarily return a klass
# and an optional command.
#
# ==== Custom invocations
#
# You can also supply a block to customize how the option is going to be
# invoked. The block receives two parameters, an instance of the current
# class and the klass to be invoked.
#
def invoke_from_option(*names, &block)
options = names.last.is_a?(Hash) ? names.pop : {}
verbose = options.fetch(:verbose, :white)
names.each do |name|
unless class_options.key?(name)
raise ArgumentError, "You have to define the option #{name.inspect} " \
"before setting invoke_from_option."
end
invocations[name] = true
invocation_blocks[name] = block if block_given?
class_eval <<-METHOD, __FILE__, __LINE__ + 1
def _invoke_from_option_#{name.to_s.gsub(/\W/, '_')}
return unless options[#{name.inspect}]
value = options[#{name.inspect}]
value = #{name.inspect} if TrueClass === value
klass, command = self.class.prepare_for_invocation(#{name.inspect}, value)
if klass
say_status :invoke, value, #{verbose.inspect}
block = self.class.invocation_blocks[#{name.inspect}]
_invoke_for_class_method klass, command, &block
else
say_status :error, %(\#{value} [not found]), :red
end
end
METHOD
end
end
# Remove a previously added invocation.
#
# ==== Examples
#
# remove_invocation :test_framework
#
def remove_invocation(*names)
names.each do |name|
remove_command(name)
remove_class_option(name)
invocations.delete(name)
invocation_blocks.delete(name)
end
end
# Overwrite class options help to allow invoked generators options to be
# shown recursively when invoking a generator.
#
def class_options_help(shell, groups = {}) #:nodoc:
get_options_from_invocations(groups, class_options) do |klass|
klass.send(:get_options_from_invocations, groups, class_options)
end
super(shell, groups)
end
# Get invocations array and merge options from invocations. Those
# options are added to group_options hash. Options that already exists
# in base_options are not added twice.
#
def get_options_from_invocations(group_options, base_options) #:nodoc:
invocations.each do |name, from_option|
value = if from_option
option = class_options[name]
option.type == :boolean ? name : option.default
else
name
end
next unless value
klass, _ = prepare_for_invocation(name, value)
next unless klass && klass.respond_to?(:class_options)
value = value.to_s
human_name = value.respond_to?(:classify) ? value.classify : value
group_options[human_name] ||= []
group_options[human_name] += klass.class_options.values.select do |class_option|
base_options[class_option.name.to_sym].nil? && class_option.group.nil? &&
!group_options.values.flatten.any? { |i| i.name == class_option.name }
end
yield klass if block_given?
end
end
# Returns commands ready to be printed.
def printable_commands(*)
item = []
item << banner
item << (desc ? "# #{desc.gsub(/\s+/m, ' ')}" : "")
[item]
end
alias_method :printable_tasks, :printable_commands
def handle_argument_error(command, error, _args, arity) #:nodoc:
msg = "#{basename} #{command.name} takes #{arity} argument".dup
msg << "s" if arity > 1
msg << ", but it should not."
raise error, msg
end
# Checks if a specified command exists.
#
# ==== Parameters
# command_name<String>:: The name of the command to check for existence.
#
# ==== Returns
# Boolean:: +true+ if the command exists, +false+ otherwise.
def command_exists?(command_name) #:nodoc:
commands.keys.include?(command_name)
end
protected
# The method responsible for dispatching given the args.
def dispatch(command, given_args, given_opts, config) #:nodoc:
if Thor::HELP_MAPPINGS.include?(given_args.first)
help(config[:shell])
return
end
args, opts = Thor::Options.split(given_args)
opts = given_opts || opts
instance = new(args, opts, config)
yield instance if block_given?
if command
instance.invoke_command(all_commands[command])
else
instance.invoke_all
end
end
# The banner for this class. You can customize it if you are invoking the
# thor class by another ways which is not the Thor::Runner.
def banner
"#{basename} #{self_command.formatted_usage(self, false)}"
end
# Represents the whole class as a command.
def self_command #:nodoc:
Thor::DynamicCommand.new(namespace, class_options)
end
alias_method :self_task, :self_command
def baseclass #:nodoc:
Thor::Group
end
def create_command(meth) #:nodoc:
commands[meth.to_s] = Thor::Command.new(meth, nil, nil, nil, nil)
true
end
alias_method :create_task, :create_command
end
include Thor::Base
protected
# Shortcut to invoke with padding and block handling. Use internally by
# invoke and invoke_from_option class methods.
def _invoke_for_class_method(klass, command = nil, *args, &block) #:nodoc:
with_padding do
if block
case block.arity
when 3
yield(self, klass, command)
when 2
yield(self, klass)
when 1
instance_exec(klass, &block)
end
else
invoke klass, command, *args
end
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/lib/thor/parser.rb | lib/thor/parser.rb | require_relative "parser/argument"
require_relative "parser/arguments"
require_relative "parser/option"
require_relative "parser/options"
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/lib/thor/base.rb | lib/thor/base.rb | require_relative "command"
require_relative "core_ext/hash_with_indifferent_access"
require_relative "error"
require_relative "invocation"
require_relative "nested_context"
require_relative "parser"
require_relative "shell"
require_relative "line_editor"
require_relative "util"
class Thor
autoload :Actions, File.expand_path("actions", __dir__)
autoload :RakeCompat, File.expand_path("rake_compat", __dir__)
autoload :Group, File.expand_path("group", __dir__)
# Shortcuts for help and tree commands.
HELP_MAPPINGS = %w(-h -? --help -D)
TREE_MAPPINGS = %w(-t --tree)
# Thor methods that should not be overwritten by the user.
THOR_RESERVED_WORDS = %w(invoke shell options behavior root destination_root relative_root
action add_file create_file in_root inside run run_ruby_script)
TEMPLATE_EXTNAME = ".tt"
class << self
def deprecation_warning(message) #:nodoc:
unless ENV["THOR_SILENCE_DEPRECATION"]
warn "Deprecation warning: #{message}\n" +
"You can silence deprecations warning by setting the environment variable THOR_SILENCE_DEPRECATION."
end
end
end
module Base
attr_accessor :options, :parent_options, :args
# It receives arguments in an Array and two hashes, one for options and
# other for configuration.
#
# Notice that it does not check if all required arguments were supplied.
# It should be done by the parser.
#
# ==== Parameters
# args<Array[Object]>:: An array of objects. The objects are applied to their
# respective accessors declared with <tt>argument</tt>.
#
# options<Hash>:: An options hash that will be available as self.options.
# The hash given is converted to a hash with indifferent
# access, magic predicates (options.skip?) and then frozen.
#
# config<Hash>:: Configuration for this Thor class.
#
def initialize(args = [], local_options = {}, config = {})
parse_options = self.class.class_options
# The start method splits inbound arguments at the first argument
# that looks like an option (starts with - or --). It then calls
# new, passing in the two halves of the arguments Array as the
# first two parameters.
command_options = config.delete(:command_options) # hook for start
parse_options = parse_options.merge(command_options) if command_options
if local_options.is_a?(Array)
array_options = local_options
hash_options = {}
else
# Handle the case where the class was explicitly instantiated
# with pre-parsed options.
array_options = []
hash_options = local_options
end
# Let Thor::Options parse the options first, so it can remove
# declared options from the array. This will leave us with
# a list of arguments that weren't declared.
current_command = config[:current_command]
stop_on_unknown = self.class.stop_on_unknown_option? current_command
# Give a relation of options.
# After parsing, Thor::Options check whether right relations are kept
relations = if current_command.nil?
{exclusive_option_names: [], at_least_one_option_names: []}
else
current_command.options_relation
end
self.class.class_exclusive_option_names.map { |n| relations[:exclusive_option_names] << n }
self.class.class_at_least_one_option_names.map { |n| relations[:at_least_one_option_names] << n }
disable_required_check = self.class.disable_required_check? current_command
opts = Thor::Options.new(parse_options, hash_options, stop_on_unknown, disable_required_check, relations)
self.options = opts.parse(array_options)
self.options = config[:class_options].merge(options) if config[:class_options]
# If unknown options are disallowed, make sure that none of the
# remaining arguments looks like an option.
opts.check_unknown! if self.class.check_unknown_options?(config)
# Add the remaining arguments from the options parser to the
# arguments passed in to initialize. Then remove any positional
# arguments declared using #argument (this is primarily used
# by Thor::Group). Tis will leave us with the remaining
# positional arguments.
to_parse = args
to_parse += opts.remaining unless self.class.strict_args_position?(config)
thor_args = Thor::Arguments.new(self.class.arguments)
thor_args.parse(to_parse).each { |k, v| __send__("#{k}=", v) }
@args = thor_args.remaining
end
class << self
def included(base) #:nodoc:
super(base)
base.extend ClassMethods
base.send :include, Invocation
base.send :include, Shell
end
# Returns the classes that inherits from Thor or Thor::Group.
#
# ==== Returns
# Array[Class]
#
def subclasses
@subclasses ||= []
end
# Returns the files where the subclasses are kept.
#
# ==== Returns
# Hash[path<String> => Class]
#
def subclass_files
@subclass_files ||= Hash.new { |h, k| h[k] = [] }
end
# Whenever a class inherits from Thor or Thor::Group, we should track the
# class and the file on Thor::Base. This is the method responsible for it.
#
def register_klass_file(klass) #:nodoc:
file = caller[1].match(/(.*):\d+/)[1]
Thor::Base.subclasses << klass unless Thor::Base.subclasses.include?(klass)
file_subclasses = Thor::Base.subclass_files[File.expand_path(file)]
file_subclasses << klass unless file_subclasses.include?(klass)
end
end
module ClassMethods
def attr_reader(*) #:nodoc:
no_commands { super }
end
def attr_writer(*) #:nodoc:
no_commands { super }
end
def attr_accessor(*) #:nodoc:
no_commands { super }
end
# If you want to raise an error for unknown options, call check_unknown_options!
# This is disabled by default to allow dynamic invocations.
def check_unknown_options!
@check_unknown_options = true
end
def check_unknown_options #:nodoc:
@check_unknown_options ||= from_superclass(:check_unknown_options, false)
end
def check_unknown_options?(config) #:nodoc:
!!check_unknown_options
end
# If you want to raise an error when the default value of an option does not match
# the type call check_default_type!
# This will be the default; for compatibility a deprecation warning is issued if necessary.
def check_default_type!
@check_default_type = true
end
# If you want to use defaults that don't match the type of an option,
# either specify `check_default_type: false` or call `allow_incompatible_default_type!`
def allow_incompatible_default_type!
@check_default_type = false
end
def check_default_type #:nodoc:
@check_default_type = from_superclass(:check_default_type, nil) unless defined?(@check_default_type)
@check_default_type
end
# If true, option parsing is suspended as soon as an unknown option or a
# regular argument is encountered. All remaining arguments are passed to
# the command as regular arguments.
def stop_on_unknown_option?(command_name) #:nodoc:
false
end
# If true, option set will not suspend the execution of the command when
# a required option is not provided.
def disable_required_check?(command_name) #:nodoc:
false
end
# If you want only strict string args (useful when cascading thor classes),
# call strict_args_position! This is disabled by default to allow dynamic
# invocations.
def strict_args_position!
@strict_args_position = true
end
def strict_args_position #:nodoc:
@strict_args_position ||= from_superclass(:strict_args_position, false)
end
def strict_args_position?(config) #:nodoc:
!!strict_args_position
end
# Adds an argument to the class and creates an attr_accessor for it.
#
# Arguments are different from options in several aspects. The first one
# is how they are parsed from the command line, arguments are retrieved
# from position:
#
# thor command NAME
#
# Instead of:
#
# thor command --name=NAME
#
# Besides, arguments are used inside your code as an accessor (self.argument),
# while options are all kept in a hash (self.options).
#
# Finally, arguments cannot have type :default or :boolean but can be
# optional (supplying :optional => :true or :required => false), although
# you cannot have a required argument after a non-required argument. If you
# try it, an error is raised.
#
# ==== Parameters
# name<Symbol>:: The name of the argument.
# options<Hash>:: Described below.
#
# ==== Options
# :desc - Description for the argument.
# :required - If the argument is required or not.
# :optional - If the argument is optional or not.
# :type - The type of the argument, can be :string, :hash, :array, :numeric.
# :default - Default value for this argument. It cannot be required and have default values.
# :banner - String to show on usage notes.
#
# ==== Errors
# ArgumentError:: Raised if you supply a required argument after a non required one.
#
def argument(name, options = {})
is_thor_reserved_word?(name, :argument)
no_commands { attr_accessor name }
required = if options.key?(:optional)
!options[:optional]
elsif options.key?(:required)
options[:required]
else
options[:default].nil?
end
remove_argument name
if required
arguments.each do |argument|
next if argument.required?
raise ArgumentError, "You cannot have #{name.to_s.inspect} as required argument after " \
"the non-required argument #{argument.human_name.inspect}."
end
end
options[:required] = required
arguments << Thor::Argument.new(name, options)
end
# Returns this class arguments, looking up in the ancestors chain.
#
# ==== Returns
# Array[Thor::Argument]
#
def arguments
@arguments ||= from_superclass(:arguments, [])
end
# Adds a bunch of options to the set of class options.
#
# class_options :foo => false, :bar => :required, :baz => :string
#
# If you prefer more detailed declaration, check class_option.
#
# ==== Parameters
# Hash[Symbol => Object]
#
def class_options(options = nil)
@class_options ||= from_superclass(:class_options, {})
build_options(options, @class_options) if options
@class_options
end
# Adds an option to the set of class options
#
# ==== Parameters
# name<Symbol>:: The name of the argument.
# options<Hash>:: Described below.
#
# ==== Options
# :desc:: -- Description for the argument.
# :required:: -- If the argument is required or not.
# :default:: -- Default value for this argument.
# :group:: -- The group for this options. Use by class options to output options in different levels.
# :aliases:: -- Aliases for this option. <b>Note:</b> Thor follows a convention of one-dash-one-letter options. Thus aliases like "-something" wouldn't be parsed; use either "\--something" or "-s" instead.
# :type:: -- The type of the argument, can be :string, :hash, :array, :numeric or :boolean.
# :banner:: -- String to show on usage notes.
# :hide:: -- If you want to hide this option from the help.
#
def class_option(name, options = {})
unless [ Symbol, String ].any? { |klass| name.is_a?(klass) }
raise ArgumentError, "Expected a Symbol or String, got #{name.inspect}"
end
build_option(name, options, class_options)
end
# Adds and declares option group for exclusive options in the
# block and arguments. You can declare options as the outside of the block.
#
# ==== Parameters
# Array[Thor::Option.name]
#
# ==== Examples
#
# class_exclusive do
# class_option :one
# class_option :two
# end
#
# Or
#
# class_option :one
# class_option :two
# class_exclusive :one, :two
#
# If you give "--one" and "--two" at the same time ExclusiveArgumentsError
# will be raised.
#
def class_exclusive(*args, &block)
register_options_relation_for(:class_options,
:class_exclusive_option_names, *args, &block)
end
# Adds and declares option group for required at least one of options in the
# block and arguments. You can declare options as the outside of the block.
#
# ==== Examples
#
# class_at_least_one do
# class_option :one
# class_option :two
# end
#
# Or
#
# class_option :one
# class_option :two
# class_at_least_one :one, :two
#
# If you do not give "--one" and "--two" AtLeastOneRequiredArgumentError
# will be raised.
#
# You can use class_at_least_one and class_exclusive at the same time.
#
# class_exclusive do
# class_at_least_one do
# class_option :one
# class_option :two
# end
# end
#
# Then it is required either only one of "--one" or "--two".
#
def class_at_least_one(*args, &block)
register_options_relation_for(:class_options,
:class_at_least_one_option_names, *args, &block)
end
# Returns this class exclusive options array set, looking up in the ancestors chain.
#
# ==== Returns
# Array[Array[Thor::Option.name]]
#
def class_exclusive_option_names
@class_exclusive_option_names ||= from_superclass(:class_exclusive_option_names, [])
end
# Returns this class at least one of required options array set, looking up in the ancestors chain.
#
# ==== Returns
# Array[Array[Thor::Option.name]]
#
def class_at_least_one_option_names
@class_at_least_one_option_names ||= from_superclass(:class_at_least_one_option_names, [])
end
# Removes a previous defined argument. If :undefine is given, undefine
# accessors as well.
#
# ==== Parameters
# names<Array>:: Arguments to be removed
#
# ==== Examples
#
# remove_argument :foo
# remove_argument :foo, :bar, :baz, :undefine => true
#
def remove_argument(*names)
options = names.last.is_a?(Hash) ? names.pop : {}
names.each do |name|
arguments.delete_if { |a| a.name == name.to_s }
undef_method name, "#{name}=" if options[:undefine]
end
end
# Removes a previous defined class option.
#
# ==== Parameters
# names<Array>:: Class options to be removed
#
# ==== Examples
#
# remove_class_option :foo
# remove_class_option :foo, :bar, :baz
#
def remove_class_option(*names)
names.each do |name|
class_options.delete(name)
end
end
# Defines the group. This is used when thor list is invoked so you can specify
# that only commands from a pre-defined group will be shown. Defaults to standard.
#
# ==== Parameters
# name<String|Symbol>
#
def group(name = nil)
if name
@group = name.to_s
else
@group ||= from_superclass(:group, "standard")
end
end
# Returns the commands for this Thor class.
#
# ==== Returns
# Hash:: An ordered hash with commands names as keys and Thor::Command
# objects as values.
#
def commands
@commands ||= Hash.new
end
alias_method :tasks, :commands
# Returns the commands for this Thor class and all subclasses.
#
# ==== Returns
# Hash:: An ordered hash with commands names as keys and Thor::Command
# objects as values.
#
def all_commands
@all_commands ||= from_superclass(:all_commands, Hash.new)
@all_commands.merge!(commands)
end
alias_method :all_tasks, :all_commands
# Removes a given command from this Thor class. This is usually done if you
# are inheriting from another class and don't want it to be available
# anymore.
#
# By default it only remove the mapping to the command. But you can supply
# :undefine => true to undefine the method from the class as well.
#
# ==== Parameters
# name<Symbol|String>:: The name of the command to be removed
# options<Hash>:: You can give :undefine => true if you want commands the method
# to be undefined from the class as well.
#
def remove_command(*names)
options = names.last.is_a?(Hash) ? names.pop : {}
names.each do |name|
commands.delete(name.to_s)
all_commands.delete(name.to_s)
undef_method name if options[:undefine]
end
end
alias_method :remove_task, :remove_command
# All methods defined inside the given block are not added as commands.
#
# So you can do:
#
# class MyScript < Thor
# no_commands do
# def this_is_not_a_command
# end
# end
# end
#
# You can also add the method and remove it from the command list:
#
# class MyScript < Thor
# def this_is_not_a_command
# end
# remove_command :this_is_not_a_command
# end
#
def no_commands(&block)
no_commands_context.enter(&block)
end
alias_method :no_tasks, :no_commands
def no_commands_context
@no_commands_context ||= NestedContext.new
end
def no_commands?
no_commands_context.entered?
end
# Sets the namespace for the Thor or Thor::Group class. By default the
# namespace is retrieved from the class name. If your Thor class is named
# Scripts::MyScript, the help method, for example, will be called as:
#
# thor scripts:my_script -h
#
# If you change the namespace:
#
# namespace :my_scripts
#
# You change how your commands are invoked:
#
# thor my_scripts -h
#
# Finally, if you change your namespace to default:
#
# namespace :default
#
# Your commands can be invoked with a shortcut. Instead of:
#
# thor :my_command
#
def namespace(name = nil)
if name
@namespace = name.to_s
else
@namespace ||= Thor::Util.namespace_from_thor_class(self)
end
end
# Parses the command and options from the given args, instantiate the class
# and invoke the command. This method is used when the arguments must be parsed
# from an array. If you are inside Ruby and want to use a Thor class, you
# can simply initialize it:
#
# script = MyScript.new(args, options, config)
# script.invoke(:command, first_arg, second_arg, third_arg)
#
def start(given_args = ARGV, config = {})
config[:shell] ||= Thor::Base.shell.new
dispatch(nil, given_args.dup, nil, config)
rescue Thor::Error => e
config[:debug] || ENV["THOR_DEBUG"] == "1" ? (raise e) : config[:shell].error(e.message)
exit(false) if exit_on_failure?
rescue Errno::EPIPE
# This happens if a thor command is piped to something like `head`,
# which closes the pipe when it's done reading. This will also
# mean that if the pipe is closed, further unnecessary
# computation will not occur.
exit(true)
end
# Allows to use private methods from parent in child classes as commands.
#
# ==== Parameters
# names<Array>:: Method names to be used as commands
#
# ==== Examples
#
# public_command :foo
# public_command :foo, :bar, :baz
#
def public_command(*names)
names.each do |name|
class_eval "def #{name}(*); super end", __FILE__, __LINE__
end
end
alias_method :public_task, :public_command
def handle_no_command_error(command, has_namespace = $thor_runner) #:nodoc:
raise UndefinedCommandError.new(command, all_commands.keys, (namespace if has_namespace))
end
alias_method :handle_no_task_error, :handle_no_command_error
def handle_argument_error(command, error, args, arity) #:nodoc:
name = [command.ancestor_name, command.name].compact.join(" ")
msg = "ERROR: \"#{basename} #{name}\" was called with ".dup
msg << "no arguments" if args.empty?
msg << "arguments " << args.inspect unless args.empty?
msg << "\nUsage: \"#{banner(command).split("\n").join("\"\n \"")}\""
raise InvocationError, msg
end
# A flag that makes the process exit with status 1 if any error happens.
def exit_on_failure?
Thor.deprecation_warning "Thor exit with status 0 on errors. To keep this behavior, you must define `exit_on_failure?` in `#{self.name}`"
false
end
protected
# Prints the class options per group. If an option does not belong to
# any group, it's printed as Class option.
#
def class_options_help(shell, groups = {}) #:nodoc:
# Group options by group
class_options.each do |_, value|
groups[value.group] ||= []
groups[value.group] << value
end
# Deal with default group
global_options = groups.delete(nil) || []
print_options(shell, global_options)
# Print all others
groups.each do |group_name, options|
print_options(shell, options, group_name)
end
end
# Receives a set of options and print them.
def print_options(shell, options, group_name = nil)
return if options.empty?
list = []
padding = options.map { |o| o.aliases_for_usage.size }.max.to_i
options.each do |option|
next if option.hide
item = [option.usage(padding)]
item.push(option.description ? "# #{option.description}" : "")
list << item
list << ["", "# Default: #{option.print_default}"] if option.show_default?
list << ["", "# Possible values: #{option.enum_to_s}"] if option.enum
end
shell.say(group_name ? "#{group_name} options:" : "Options:")
shell.print_table(list, indent: 2)
shell.say ""
end
# Raises an error if the word given is a Thor reserved word.
def is_thor_reserved_word?(word, type) #:nodoc:
return false unless THOR_RESERVED_WORDS.include?(word.to_s)
raise "#{word.inspect} is a Thor reserved word and cannot be defined as #{type}"
end
# Build an option and adds it to the given scope.
#
# ==== Parameters
# name<Symbol>:: The name of the argument.
# options<Hash>:: Described in both class_option and method_option.
# scope<Hash>:: Options hash that is being built up
def build_option(name, options, scope) #:nodoc:
scope[name] = Thor::Option.new(name, {check_default_type: check_default_type}.merge!(options))
end
# Receives a hash of options, parse them and add to the scope. This is a
# fast way to set a bunch of options:
#
# build_options :foo => true, :bar => :required, :baz => :string
#
# ==== Parameters
# Hash[Symbol => Object]
def build_options(options, scope) #:nodoc:
options.each do |key, value|
scope[key] = Thor::Option.parse(key, value)
end
end
# Finds a command with the given name. If the command belongs to the current
# class, just return it, otherwise dup it and add the fresh copy to the
# current command hash.
def find_and_refresh_command(name) #:nodoc:
if commands[name.to_s]
commands[name.to_s]
elsif command = all_commands[name.to_s] # rubocop:disable Lint/AssignmentInCondition
commands[name.to_s] = command.clone
else
raise ArgumentError, "You supplied :for => #{name.inspect}, but the command #{name.inspect} could not be found."
end
end
alias_method :find_and_refresh_task, :find_and_refresh_command
# Every time someone inherits from a Thor class, register the klass
# and file into baseclass.
def inherited(klass)
super(klass)
Thor::Base.register_klass_file(klass)
klass.instance_variable_set(:@no_commands, 0)
end
# Fire this callback whenever a method is added. Added methods are
# tracked as commands by invoking the create_command method.
def method_added(meth)
super(meth)
meth = meth.to_s
if meth == "initialize"
initialize_added
return
end
# Return if it's not a public instance method
return unless public_method_defined?(meth.to_sym)
return if no_commands? || !create_command(meth)
is_thor_reserved_word?(meth, :command)
Thor::Base.register_klass_file(self)
end
# Retrieves a value from superclass. If it reaches the baseclass,
# returns default.
def from_superclass(method, default = nil)
if self == baseclass || !superclass.respond_to?(method, true)
default
else
value = superclass.send(method)
# Ruby implements `dup` on Object, but raises a `TypeError`
# if the method is called on immediates. As a result, we
# don't have a good way to check whether dup will succeed
# without calling it and rescuing the TypeError.
begin
value.dup
rescue TypeError
value
end
end
end
#
# The basename of the program invoking the thor class.
#
def basename
File.basename($PROGRAM_NAME).split(" ").first
end
# SIGNATURE: Sets the baseclass. This is where the superclass lookup
# finishes.
def baseclass #:nodoc:
end
# SIGNATURE: Creates a new command if valid_command? is true. This method is
# called when a new method is added to the class.
def create_command(meth) #:nodoc:
end
alias_method :create_task, :create_command
# SIGNATURE: Defines behavior when the initialize method is added to the
# class.
def initialize_added #:nodoc:
end
# SIGNATURE: The hook invoked by start.
def dispatch(command, given_args, given_opts, config) #:nodoc:
raise NotImplementedError
end
# Register a relation of options for target(method_option/class_option)
# by args and block.
def register_options_relation_for(target, relation, *args, &block) # :nodoc:
opt = args.pop if args.last.is_a? Hash
opt ||= {}
names = args.map{ |arg| arg.to_s }
names += built_option_names(target, opt, &block) if block_given?
command_scope_member(relation, opt) << names
end
# Get target(method_options or class_options) options
# of before and after by block evaluation.
def built_option_names(target, opt = {}, &block) # :nodoc:
before = command_scope_member(target, opt).map{ |k,v| v.name }
instance_eval(&block)
after = command_scope_member(target, opt).map{ |k,v| v.name }
after - before
end
# Get command scope member by name.
def command_scope_member(name, options = {}) # :nodoc:
if options[:for]
find_and_refresh_command(options[:for]).send(name)
else
send(name)
end
end
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/lib/thor/nested_context.rb | lib/thor/nested_context.rb | class Thor
class NestedContext
def initialize
@depth = 0
end
def enter
push
yield
ensure
pop
end
def entered?
@depth.positive?
end
private
def push
@depth += 1
end
def pop
@depth -= 1
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/lib/thor/runner.rb | lib/thor/runner.rb | require_relative "../thor"
require_relative "group"
require "digest/sha2"
require "pathname"
class Thor::Runner < Thor #:nodoc:
map "-T" => :list, "-i" => :install, "-u" => :update, "-v" => :version
def self.banner(command, all = false, subcommand = false)
"thor " + command.formatted_usage(self, all, subcommand)
end
def self.exit_on_failure?
true
end
# Override Thor#help so it can give information about any class and any method.
#
def help(meth = nil)
if meth && !respond_to?(meth)
initialize_thorfiles(meth)
klass, command = Thor::Util.find_class_and_command_by_namespace(meth)
self.class.handle_no_command_error(command, false) if klass.nil?
klass.start(["-h", command].compact, shell: shell)
else
super
end
end
# If a command is not found on Thor::Runner, method missing is invoked and
# Thor::Runner is then responsible for finding the command in all classes.
#
def method_missing(meth, *args)
meth = meth.to_s
initialize_thorfiles(meth)
klass, command = Thor::Util.find_class_and_command_by_namespace(meth)
self.class.handle_no_command_error(command, false) if klass.nil?
args.unshift(command) if command
klass.start(args, shell: shell)
end
desc "install NAME", "Install an optionally named Thor file into your system commands"
method_options as: :string, relative: :boolean, force: :boolean
def install(name) # rubocop:disable Metrics/MethodLength
initialize_thorfiles
is_uri = name =~ %r{^https?\://}
if is_uri
base = name
package = :file
require "open-uri"
begin
contents = URI.open(name, &:read)
rescue OpenURI::HTTPError
raise Error, "Error opening URI '#{name}'"
end
else
# If a directory name is provided as the argument, look for a 'main.thor'
# command in said directory.
begin
if File.directory?(File.expand_path(name))
base = File.join(name, "main.thor")
package = :directory
contents = File.open(base, &:read)
else
base = name
package = :file
require "open-uri"
contents = URI.open(name, &:read)
end
rescue Errno::ENOENT
raise Error, "Error opening file '#{name}'"
end
end
say "Your Thorfile contains:"
say contents
unless options["force"]
return false if no?("Do you wish to continue [y/N]?")
end
as = options["as"] || begin
first_line = contents.split("\n")[0]
(match = first_line.match(/\s*#\s*module:\s*([^\n]*)/)) ? match[1].strip : nil
end
unless as
basename = File.basename(name)
as = ask("Please specify a name for #{name} in the system repository [#{basename}]:")
as = basename if as.empty?
end
location = if options[:relative] || is_uri
name
else
File.expand_path(name)
end
thor_yaml[as] = {
filename: Digest::SHA256.hexdigest(name + as),
location: location,
namespaces: Thor::Util.namespaces_in_content(contents, base)
}
save_yaml(thor_yaml)
say "Storing thor file in your system repository"
destination = File.join(thor_root, thor_yaml[as][:filename])
if package == :file
File.open(destination, "w") { |f| f.puts contents }
else
require "fileutils"
FileUtils.cp_r(name, destination)
end
thor_yaml[as][:filename] # Indicate success
end
desc "version", "Show Thor version"
def version
require_relative "version"
say "Thor #{Thor::VERSION}"
end
desc "uninstall NAME", "Uninstall a named Thor module"
def uninstall(name)
raise Error, "Can't find module '#{name}'" unless thor_yaml[name]
say "Uninstalling #{name}."
require "fileutils"
FileUtils.rm_rf(File.join(thor_root, (thor_yaml[name][:filename]).to_s))
thor_yaml.delete(name)
save_yaml(thor_yaml)
puts "Done."
end
desc "update NAME", "Update a Thor file from its original location"
def update(name)
raise Error, "Can't find module '#{name}'" if !thor_yaml[name] || !thor_yaml[name][:location]
say "Updating '#{name}' from #{thor_yaml[name][:location]}"
old_filename = thor_yaml[name][:filename]
self.options = options.merge("as" => name)
if File.directory? File.expand_path(name)
require "fileutils"
FileUtils.rm_rf(File.join(thor_root, old_filename))
thor_yaml.delete(old_filename)
save_yaml(thor_yaml)
filename = install(name)
else
filename = install(thor_yaml[name][:location])
end
File.delete(File.join(thor_root, old_filename)) unless filename == old_filename
end
desc "installed", "List the installed Thor modules and commands"
method_options internal: :boolean
def installed
initialize_thorfiles(nil, true)
display_klasses(true, options["internal"])
end
desc "list [SEARCH]", "List the available thor commands (--substring means .*SEARCH)"
method_options substring: :boolean, group: :string, all: :boolean, debug: :boolean
def list(search = "")
initialize_thorfiles
search = ".*#{search}" if options["substring"]
search = /^#{search}.*/i
group = options[:group] || "standard"
klasses = Thor::Base.subclasses.select do |k|
(options[:all] || k.group == group) && k.namespace =~ search
end
display_klasses(false, false, klasses)
end
private
def thor_root
Thor::Util.thor_root
end
def thor_yaml
@thor_yaml ||= begin
yaml_file = File.join(thor_root, "thor.yml")
require "yaml"
yaml = YAML.load_file(yaml_file) if File.exist?(yaml_file)
yaml || {}
end
end
# Save the yaml file. If none exists in thor root, creates one.
#
def save_yaml(yaml)
yaml_file = File.join(thor_root, "thor.yml")
unless File.exist?(yaml_file)
require "fileutils"
FileUtils.mkdir_p(thor_root)
yaml_file = File.join(thor_root, "thor.yml")
FileUtils.touch(yaml_file)
end
File.open(yaml_file, "w") { |f| f.puts yaml.to_yaml }
end
# Load the Thorfiles. If relevant_to is supplied, looks for specific files
# in the thor_root instead of loading them all.
#
# By default, it also traverses the current path until find Thor files, as
# described in thorfiles. This look up can be skipped by supplying
# skip_lookup true.
#
def initialize_thorfiles(relevant_to = nil, skip_lookup = false)
thorfiles(relevant_to, skip_lookup).each do |f|
Thor::Util.load_thorfile(f, nil, options[:debug]) unless Thor::Base.subclass_files.keys.include?(File.expand_path(f))
end
end
# Finds Thorfiles by traversing from your current directory down to the root
# directory of your system. If at any time we find a Thor file, we stop.
#
# We also ensure that system-wide Thorfiles are loaded first, so local
# Thorfiles can override them.
#
# ==== Example
#
# If we start at /Users/wycats/dev/thor ...
#
# 1. /Users/wycats/dev/thor
# 2. /Users/wycats/dev
# 3. /Users/wycats <-- we find a Thorfile here, so we stop
#
# Suppose we start at c:\Documents and Settings\james\dev\thor ...
#
# 1. c:\Documents and Settings\james\dev\thor
# 2. c:\Documents and Settings\james\dev
# 3. c:\Documents and Settings\james
# 4. c:\Documents and Settings
# 5. c:\ <-- no Thorfiles found!
#
def thorfiles(relevant_to = nil, skip_lookup = false)
thorfiles = []
unless skip_lookup
Pathname.pwd.ascend do |path|
thorfiles = Thor::Util.globs_for(path).map { |g| Dir[g] }.flatten
break unless thorfiles.empty?
end
end
files = (relevant_to ? thorfiles_relevant_to(relevant_to) : Thor::Util.thor_root_glob)
files += thorfiles
files -= ["#{thor_root}/thor.yml"]
files.map! do |file|
File.directory?(file) ? File.join(file, "main.thor") : file
end
end
# Load Thorfiles relevant to the given method. If you provide "foo:bar" it
# will load all thor files in the thor.yaml that has "foo" e "foo:bar"
# namespaces registered.
#
def thorfiles_relevant_to(meth)
lookup = [meth, meth.split(":")[0...-1].join(":")]
files = thor_yaml.select do |_, v|
v[:namespaces] && !(v[:namespaces] & lookup).empty?
end
files.map { |_, v| File.join(thor_root, (v[:filename]).to_s) }
end
# Display information about the given klasses. If with_module is given,
# it shows a table with information extracted from the yaml file.
#
def display_klasses(with_modules = false, show_internal = false, klasses = Thor::Base.subclasses)
klasses -= [Thor, Thor::Runner, Thor::Group] unless show_internal
raise Error, "No Thor commands available" if klasses.empty?
show_modules if with_modules && !thor_yaml.empty?
list = Hash.new { |h, k| h[k] = [] }
groups = klasses.select { |k| k.ancestors.include?(Thor::Group) }
# Get classes which inherit from Thor
(klasses - groups).each { |k| list[k.namespace.split(":").first] += k.printable_commands(false) }
# Get classes which inherit from Thor::Base
groups.map! { |k| k.printable_commands(false).first }
list["root"] = groups
# Order namespaces with default coming first
list = list.sort { |a, b| a[0].sub(/^default/, "") <=> b[0].sub(/^default/, "") }
list.each { |n, commands| display_commands(n, commands) unless commands.empty? }
end
def display_commands(namespace, list) #:nodoc:
list.sort! { |a, b| a[0] <=> b[0] }
say shell.set_color(namespace, :blue, true)
say "-" * namespace.size
print_table(list, truncate: true)
say
end
alias_method :display_tasks, :display_commands
def show_modules #:nodoc:
info = []
labels = %w(Modules Namespaces)
info << labels
info << ["-" * labels[0].size, "-" * labels[1].size]
thor_yaml.each do |name, hash|
info << [name, hash[:namespaces].join(", ")]
end
print_table info
say ""
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/lib/thor/shell.rb | lib/thor/shell.rb | require "rbconfig"
class Thor
module Base
class << self
attr_writer :shell
# Returns the shell used in all Thor classes. If you are in a Unix platform
# it will use a colored log, otherwise it will use a basic one without color.
#
def shell
@shell ||= if ENV["THOR_SHELL"] && !ENV["THOR_SHELL"].empty?
Thor::Shell.const_get(ENV["THOR_SHELL"])
elsif RbConfig::CONFIG["host_os"] =~ /mswin|mingw/ && !ENV["ANSICON"]
Thor::Shell::Basic
else
Thor::Shell::Color
end
end
end
end
module Shell
SHELL_DELEGATED_METHODS = [:ask, :error, :set_color, :yes?, :no?, :say, :say_error, :say_status, :print_in_columns, :print_table, :print_wrapped, :file_collision, :terminal_width]
attr_writer :shell
autoload :Basic, File.expand_path("shell/basic", __dir__)
autoload :Color, File.expand_path("shell/color", __dir__)
autoload :HTML, File.expand_path("shell/html", __dir__)
# Add shell to initialize config values.
#
# ==== Configuration
# shell<Object>:: An instance of the shell to be used.
#
# ==== Examples
#
# class MyScript < Thor
# argument :first, :type => :numeric
# end
#
# MyScript.new [1.0], { :foo => :bar }, :shell => Thor::Shell::Basic.new
#
def initialize(args = [], options = {}, config = {})
super
self.shell = config[:shell]
shell.base ||= self if shell.respond_to?(:base)
end
# Holds the shell for the given Thor instance. If no shell is given,
# it gets a default shell from Thor::Base.shell.
def shell
@shell ||= Thor::Base.shell.new
end
# Common methods that are delegated to the shell.
SHELL_DELEGATED_METHODS.each do |method|
module_eval <<-METHOD, __FILE__, __LINE__ + 1
def #{method}(*args,&block)
shell.#{method}(*args,&block)
end
METHOD
end
# Yields the given block with padding.
def with_padding
shell.padding += 1
yield
ensure
shell.padding -= 1
end
protected
# Allow shell to be shared between invocations.
#
def _shared_configuration #:nodoc:
super.merge!(shell: shell)
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/lib/thor/invocation.rb | lib/thor/invocation.rb | class Thor
module Invocation
def self.included(base) #:nodoc:
super(base)
base.extend ClassMethods
end
module ClassMethods
# This method is responsible for receiving a name and find the proper
# class and command for it. The key is an optional parameter which is
# available only in class methods invocations (i.e. in Thor::Group).
def prepare_for_invocation(key, name) #:nodoc:
case name
when Symbol, String
Thor::Util.find_class_and_command_by_namespace(name.to_s, !key)
else
name
end
end
end
# Make initializer aware of invocations and the initialization args.
def initialize(args = [], options = {}, config = {}, &block) #:nodoc:
@_invocations = config[:invocations] || Hash.new { |h, k| h[k] = [] }
@_initializer = [args, options, config]
super
end
# Make the current command chain accessible with in a Thor-(sub)command
def current_command_chain
@_invocations.values.flatten.map(&:to_sym)
end
# Receives a name and invokes it. The name can be a string (either "command" or
# "namespace:command"), a Thor::Command, a Class or a Thor instance. If the
# command cannot be guessed by name, it can also be supplied as second argument.
#
# You can also supply the arguments, options and configuration values for
# the command to be invoked, if none is given, the same values used to
# initialize the invoker are used to initialize the invoked.
#
# When no name is given, it will invoke the default command of the current class.
#
# ==== Examples
#
# class A < Thor
# def foo
# invoke :bar
# invoke "b:hello", ["Erik"]
# end
#
# def bar
# invoke "b:hello", ["Erik"]
# end
# end
#
# class B < Thor
# def hello(name)
# puts "hello #{name}"
# end
# end
#
# You can notice that the method "foo" above invokes two commands: "bar",
# which belongs to the same class and "hello" which belongs to the class B.
#
# By using an invocation system you ensure that a command is invoked only once.
# In the example above, invoking "foo" will invoke "b:hello" just once, even
# if it's invoked later by "bar" method.
#
# When class A invokes class B, all arguments used on A initialization are
# supplied to B. This allows lazy parse of options. Let's suppose you have
# some rspec commands:
#
# class Rspec < Thor::Group
# class_option :mock_framework, :type => :string, :default => :rr
#
# def invoke_mock_framework
# invoke "rspec:#{options[:mock_framework]}"
# end
# end
#
# As you noticed, it invokes the given mock framework, which might have its
# own options:
#
# class Rspec::RR < Thor::Group
# class_option :style, :type => :string, :default => :mock
# end
#
# Since it's not rspec concern to parse mock framework options, when RR
# is invoked all options are parsed again, so RR can extract only the options
# that it's going to use.
#
# If you want Rspec::RR to be initialized with its own set of options, you
# have to do that explicitly:
#
# invoke "rspec:rr", [], :style => :foo
#
# Besides giving an instance, you can also give a class to invoke:
#
# invoke Rspec::RR, [], :style => :foo
#
def invoke(name = nil, *args)
if name.nil?
warn "[Thor] Calling invoke() without argument is deprecated. Please use invoke_all instead.\n#{caller.join("\n")}"
return invoke_all
end
args.unshift(nil) if args.first.is_a?(Array) || args.first.nil?
command, args, opts, config = args
klass, command = _retrieve_class_and_command(name, command)
raise "Missing Thor class for invoke #{name}" unless klass
raise "Expected Thor class, got #{klass}" unless klass <= Thor::Base
args, opts, config = _parse_initialization_options(args, opts, config)
klass.send(:dispatch, command, args, opts, config) do |instance|
instance.parent_options = options
end
end
# Invoke the given command if the given args.
def invoke_command(command, *args) #:nodoc:
current = @_invocations[self.class]
unless current.include?(command.name)
current << command.name
command.run(self, *args)
end
end
alias_method :invoke_task, :invoke_command
# Invoke all commands for the current instance.
def invoke_all #:nodoc:
self.class.all_commands.map { |_, command| invoke_command(command) }
end
# Invokes using shell padding.
def invoke_with_padding(*args)
with_padding { invoke(*args) }
end
protected
# Configuration values that are shared between invocations.
def _shared_configuration #:nodoc:
{invocations: @_invocations}
end
# This method simply retrieves the class and command to be invoked.
# If the name is nil or the given name is a command in the current class,
# use the given name and return self as class. Otherwise, call
# prepare_for_invocation in the current class.
def _retrieve_class_and_command(name, sent_command = nil) #:nodoc:
if name.nil?
[self.class, nil]
elsif self.class.all_commands[name.to_s]
[self.class, name.to_s]
else
klass, command = self.class.prepare_for_invocation(nil, name)
[klass, command || sent_command]
end
end
alias_method :_retrieve_class_and_task, :_retrieve_class_and_command
# Initialize klass using values stored in the @_initializer.
def _parse_initialization_options(args, opts, config) #:nodoc:
stored_args, stored_opts, stored_config = @_initializer
args ||= stored_args.dup
opts ||= stored_opts.dup
config ||= {}
config = stored_config.merge(_shared_configuration).merge!(config)
[args, opts, config]
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/lib/thor/error.rb | lib/thor/error.rb | class Thor
Correctable = if defined?(DidYouMean::SpellChecker) && defined?(DidYouMean::Correctable) # rubocop:disable Naming/ConstantName
Module.new do
def to_s
super + DidYouMean.formatter.message_for(corrections)
end
def corrections
@corrections ||= self.class.const_get(:SpellChecker).new(self).corrections
end
end
end
# Thor::Error is raised when it's caused by wrong usage of thor classes. Those
# errors have their backtrace suppressed and are nicely shown to the user.
#
# Errors that are caused by the developer, like declaring a method which
# overwrites a thor keyword, SHOULD NOT raise a Thor::Error. This way, we
# ensure that developer errors are shown with full backtrace.
class Error < StandardError
end
# Raised when a command was not found.
class UndefinedCommandError < Error
class SpellChecker
attr_reader :error
def initialize(error)
@error = error
end
def corrections
@corrections ||= spell_checker.correct(error.command).map(&:inspect)
end
def spell_checker
DidYouMean::SpellChecker.new(dictionary: error.all_commands)
end
end
attr_reader :command, :all_commands
def initialize(command, all_commands, namespace)
@command = command
@all_commands = all_commands
message = "Could not find command #{command.inspect}"
message = namespace ? "#{message} in #{namespace.inspect} namespace." : "#{message}."
super(message)
end
prepend Correctable if Correctable
end
UndefinedTaskError = UndefinedCommandError
class AmbiguousCommandError < Error
end
AmbiguousTaskError = AmbiguousCommandError
# Raised when a command was found, but not invoked properly.
class InvocationError < Error
end
class UnknownArgumentError < Error
class SpellChecker
attr_reader :error
def initialize(error)
@error = error
end
def corrections
@corrections ||=
error.unknown.flat_map { |unknown| spell_checker.correct(unknown) }.uniq.map(&:inspect)
end
def spell_checker
@spell_checker ||= DidYouMean::SpellChecker.new(dictionary: error.switches)
end
end
attr_reader :switches, :unknown
def initialize(switches, unknown)
@switches = switches
@unknown = unknown
super("Unknown switches #{unknown.map(&:inspect).join(', ')}")
end
prepend Correctable if Correctable
end
class RequiredArgumentMissingError < InvocationError
end
class MalformattedArgumentError < InvocationError
end
class ExclusiveArgumentError < InvocationError
end
class AtLeastOneRequiredArgumentError < InvocationError
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/lib/thor/util.rb | lib/thor/util.rb | require "rbconfig"
class Thor
module Sandbox #:nodoc:
end
# This module holds several utilities:
#
# 1) Methods to convert thor namespaces to constants and vice-versa.
#
# Thor::Util.namespace_from_thor_class(Foo::Bar::Baz) #=> "foo:bar:baz"
#
# 2) Loading thor files and sandboxing:
#
# Thor::Util.load_thorfile("~/.thor/foo")
#
module Util
class << self
# Receives a namespace and search for it in the Thor::Base subclasses.
#
# ==== Parameters
# namespace<String>:: The namespace to search for.
#
def find_by_namespace(namespace)
namespace = "default#{namespace}" if namespace.empty? || namespace =~ /^:/
Thor::Base.subclasses.detect { |klass| klass.namespace == namespace }
end
# Receives a constant and converts it to a Thor namespace. Since Thor
# commands can be added to a sandbox, this method is also responsible for
# removing the sandbox namespace.
#
# This method should not be used in general because it's used to deal with
# older versions of Thor. On current versions, if you need to get the
# namespace from a class, just call namespace on it.
#
# ==== Parameters
# constant<Object>:: The constant to be converted to the thor path.
#
# ==== Returns
# String:: If we receive Foo::Bar::Baz it returns "foo:bar:baz"
#
def namespace_from_thor_class(constant)
constant = constant.to_s.gsub(/^Thor::Sandbox::/, "")
constant = snake_case(constant).squeeze(":")
constant
end
# Given the contents, evaluate it inside the sandbox and returns the
# namespaces defined in the sandbox.
#
# ==== Parameters
# contents<String>
#
# ==== Returns
# Array[Object]
#
def namespaces_in_content(contents, file = __FILE__)
old_constants = Thor::Base.subclasses.dup
Thor::Base.subclasses.clear
load_thorfile(file, contents)
new_constants = Thor::Base.subclasses.dup
Thor::Base.subclasses.replace(old_constants)
new_constants.map!(&:namespace)
new_constants.compact!
new_constants
end
# Returns the thor classes declared inside the given class.
#
def thor_classes_in(klass)
stringfied_constants = klass.constants.map(&:to_s)
Thor::Base.subclasses.select do |subclass|
next unless subclass.name
stringfied_constants.include?(subclass.name.gsub("#{klass.name}::", ""))
end
end
# Receives a string and convert it to snake case. SnakeCase returns snake_case.
#
# ==== Parameters
# String
#
# ==== Returns
# String
#
def snake_case(str)
return str.downcase if str =~ /^[A-Z_]+$/
str.gsub(/\B[A-Z]/, '_\&').squeeze("_") =~ /_*(.*)/
Regexp.last_match(-1).downcase
end
# Receives a string and convert it to camel case. camel_case returns CamelCase.
#
# ==== Parameters
# String
#
# ==== Returns
# String
#
def camel_case(str)
return str if str !~ /_/ && str =~ /[A-Z]+.*/
str.split("_").map(&:capitalize).join
end
# Receives a namespace and tries to retrieve a Thor or Thor::Group class
# from it. It first searches for a class using the all the given namespace,
# if it's not found, removes the highest entry and searches for the class
# again. If found, returns the highest entry as the class name.
#
# ==== Examples
#
# class Foo::Bar < Thor
# def baz
# end
# end
#
# class Baz::Foo < Thor::Group
# end
#
# Thor::Util.namespace_to_thor_class("foo:bar") #=> Foo::Bar, nil # will invoke default command
# Thor::Util.namespace_to_thor_class("baz:foo") #=> Baz::Foo, nil
# Thor::Util.namespace_to_thor_class("foo:bar:baz") #=> Foo::Bar, "baz"
#
# ==== Parameters
# namespace<String>
#
def find_class_and_command_by_namespace(namespace, fallback = true)
if namespace.include?(":") # look for a namespaced command
*pieces, command = namespace.split(":")
namespace = pieces.join(":")
namespace = "default" if namespace.empty?
klass = Thor::Base.subclasses.detect { |thor| thor.namespace == namespace && thor.command_exists?(command) }
end
unless klass # look for a Thor::Group with the right name
klass = Thor::Util.find_by_namespace(namespace)
command = nil
end
if !klass && fallback # try a command in the default namespace
command = namespace
klass = Thor::Util.find_by_namespace("")
end
[klass, command]
end
alias_method :find_class_and_task_by_namespace, :find_class_and_command_by_namespace
# Receives a path and load the thor file in the path. The file is evaluated
# inside the sandbox to avoid namespacing conflicts.
#
def load_thorfile(path, content = nil, debug = false)
content ||= File.read(path)
begin
Thor::Sandbox.class_eval(content, path)
rescue StandardError => e
$stderr.puts("WARNING: unable to load thorfile #{path.inspect}: #{e.message}")
if debug
$stderr.puts(*e.backtrace)
else
$stderr.puts(e.backtrace.first)
end
end
end
def user_home
@@user_home ||= if ENV["HOME"]
ENV["HOME"]
elsif ENV["USERPROFILE"]
ENV["USERPROFILE"]
elsif ENV["HOMEDRIVE"] && ENV["HOMEPATH"]
File.join(ENV["HOMEDRIVE"], ENV["HOMEPATH"])
elsif ENV["APPDATA"]
ENV["APPDATA"]
else
begin
File.expand_path("~")
rescue
if File::ALT_SEPARATOR
"C:/"
else
"/"
end
end
end
end
# Returns the root where thor files are located, depending on the OS.
#
def thor_root
File.join(user_home, ".thor").tr("\\", "/")
end
# Returns the files in the thor root. On Windows thor_root will be something
# like this:
#
# C:\Documents and Settings\james\.thor
#
# If we don't #gsub the \ character, Dir.glob will fail.
#
def thor_root_glob
files = Dir["#{escape_globs(thor_root)}/*"]
files.map! do |file|
File.directory?(file) ? File.join(file, "main.thor") : file
end
end
# Where to look for Thor files.
#
def globs_for(path)
path = escape_globs(path)
["#{path}/Thorfile", "#{path}/*.thor", "#{path}/tasks/*.thor", "#{path}/lib/tasks/**/*.thor"]
end
# Return the path to the ruby interpreter taking into account multiple
# installations and windows extensions.
#
def ruby_command
@ruby_command ||= begin
ruby_name = RbConfig::CONFIG["ruby_install_name"]
ruby = File.join(RbConfig::CONFIG["bindir"], ruby_name)
ruby << RbConfig::CONFIG["EXEEXT"]
# avoid using different name than ruby (on platforms supporting links)
if ruby_name != "ruby" && File.respond_to?(:readlink)
begin
alternate_ruby = File.join(RbConfig::CONFIG["bindir"], "ruby")
alternate_ruby << RbConfig::CONFIG["EXEEXT"]
# ruby is a symlink
if File.symlink? alternate_ruby
linked_ruby = File.readlink alternate_ruby
# symlink points to 'ruby_install_name'
ruby = alternate_ruby if linked_ruby == ruby_name || linked_ruby == ruby
end
rescue NotImplementedError # rubocop:disable Lint/HandleExceptions
# just ignore on windows
end
end
# escape string in case path to ruby executable contain spaces.
ruby.sub!(/.*\s.*/m, '"\&"')
ruby
end
end
# Returns a string that has had any glob characters escaped.
# The glob characters are `* ? { } [ ]`.
#
# ==== Examples
#
# Thor::Util.escape_globs('[apps]') # => '\[apps\]'
#
# ==== Parameters
# String
#
# ==== Returns
# String
#
def escape_globs(path)
path.to_s.gsub(/[*?{}\[\]]/, '\\\\\\&')
end
# Returns a string that has had any HTML characters escaped.
#
# ==== Examples
#
# Thor::Util.escape_html('<div>') # => "<div>"
#
# ==== Parameters
# String
#
# ==== Returns
# String
#
def escape_html(string)
CGI.escapeHTML(string)
end
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/lib/thor/line_editor/readline.rb | lib/thor/line_editor/readline.rb | class Thor
module LineEditor
class Readline < Basic
def self.available?
begin
require "readline"
rescue LoadError
end
Object.const_defined?(:Readline)
end
def readline
if echo?
::Readline.completion_append_character = nil
# rb-readline does not allow Readline.completion_proc= to receive nil.
if complete = completion_proc
::Readline.completion_proc = complete
end
::Readline.readline(prompt, add_to_history?)
else
super
end
end
private
def add_to_history?
options.fetch(:add_to_history, true)
end
def completion_proc
if use_path_completion?
proc { |text| PathCompletion.new(text).matches }
elsif completion_options.any?
proc do |text|
completion_options.select { |option| option.start_with?(text) }
end
end
end
def completion_options
options.fetch(:limited_to, [])
end
def use_path_completion?
options.fetch(:path, false)
end
class PathCompletion
attr_reader :text
private :text
def initialize(text)
@text = text
end
def matches
relative_matches
end
private
def relative_matches
absolute_matches.map { |path| path.sub(base_path, "") }
end
def absolute_matches
Dir[glob_pattern].map do |path|
if File.directory?(path)
"#{path}/"
else
path
end
end
end
def glob_pattern
"#{base_path}#{text}*"
end
def base_path
"#{Dir.pwd}/"
end
end
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/lib/thor/line_editor/basic.rb | lib/thor/line_editor/basic.rb | class Thor
module LineEditor
class Basic
attr_reader :prompt, :options
def self.available?
true
end
def initialize(prompt, options)
@prompt = prompt
@options = options
end
def readline
$stdout.print(prompt)
get_input
end
private
def get_input
if echo?
$stdin.gets
else
# Lazy-load io/console since it is gem-ified as of 2.3
require "io/console"
$stdin.noecho(&:gets)
end
end
def echo?
options.fetch(:echo, true)
end
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/lib/thor/actions/directory.rb | lib/thor/actions/directory.rb | require_relative "empty_directory"
class Thor
module Actions
# Copies recursively the files from source directory to root directory.
# If any of the files finishes with .tt, it's considered to be a template
# and is placed in the destination without the extension .tt. If any
# empty directory is found, it's copied and all .empty_directory files are
# ignored. If any file name is wrapped within % signs, the text within
# the % signs will be executed as a method and replaced with the returned
# value. Let's suppose a doc directory with the following files:
#
# doc/
# components/.empty_directory
# README
# rdoc.rb.tt
# %app_name%.rb
#
# When invoked as:
#
# directory "doc"
#
# It will create a doc directory in the destination with the following
# files (assuming that the `app_name` method returns the value "blog"):
#
# doc/
# components/
# README
# rdoc.rb
# blog.rb
#
# <b>Encoded path note:</b> Since Thor internals use Object#respond_to? to check if it can
# expand %something%, this `something` should be a public method in the class calling
# #directory. If a method is private, Thor stack raises PrivateMethodEncodedError.
#
# ==== Parameters
# source<String>:: the relative path to the source root.
# destination<String>:: the relative path to the destination root.
# config<Hash>:: give :verbose => false to not log the status.
# If :recursive => false, does not look for paths recursively.
# If :mode => :preserve, preserve the file mode from the source.
# If :exclude_pattern => /regexp/, prevents copying files that match that regexp.
#
# ==== Examples
#
# directory "doc"
# directory "doc", "docs", :recursive => false
#
def directory(source, *args, &block)
config = args.last.is_a?(Hash) ? args.pop : {}
destination = args.first || source
action Directory.new(self, source, destination || source, config, &block)
end
class Directory < EmptyDirectory #:nodoc:
attr_reader :source
def initialize(base, source, destination = nil, config = {}, &block)
@source = File.expand_path(Dir[Util.escape_globs(base.find_in_source_paths(source.to_s))].first)
@block = block
super(base, destination, {recursive: true}.merge(config))
end
def invoke!
base.empty_directory given_destination, config
execute!
end
def revoke!
execute!
end
protected
def execute!
lookup = Util.escape_globs(source)
lookup = config[:recursive] ? File.join(lookup, "**") : lookup
lookup = file_level_lookup(lookup)
files(lookup).sort.each do |file_source|
next if File.directory?(file_source)
next if config[:exclude_pattern] && file_source.match(config[:exclude_pattern])
file_destination = File.join(given_destination, file_source.gsub(source, "."))
file_destination.gsub!("/./", "/")
case file_source
when /\.empty_directory$/
dirname = File.dirname(file_destination).gsub(%r{/\.$}, "")
next if dirname == given_destination
base.empty_directory(dirname, config)
when /#{TEMPLATE_EXTNAME}$/
base.template(file_source, file_destination[0..-4], config, &@block)
else
base.copy_file(file_source, file_destination, config, &@block)
end
end
end
def file_level_lookup(previous_lookup)
File.join(previous_lookup, "*")
end
def files(lookup)
Dir.glob(lookup, File::FNM_DOTMATCH)
end
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/lib/thor/actions/create_link.rb | lib/thor/actions/create_link.rb | require_relative "create_file"
class Thor
module Actions
# Create a new file relative to the destination root from the given source.
#
# ==== Parameters
# destination<String>:: the relative path to the destination root.
# source<String|NilClass>:: the relative path to the source root.
# config<Hash>:: give :verbose => false to not log the status.
# :: give :symbolic => false for hard link.
#
# ==== Examples
#
# create_link "config/apache.conf", "/etc/apache.conf"
#
def create_link(destination, *args)
config = args.last.is_a?(Hash) ? args.pop : {}
source = args.first
action CreateLink.new(self, destination, source, config)
end
alias_method :add_link, :create_link
# CreateLink is a subset of CreateFile, which instead of taking a block of
# data, just takes a source string from the user.
#
class CreateLink < CreateFile #:nodoc:
attr_reader :data
# Checks if the content of the file at the destination is identical to the rendered result.
#
# ==== Returns
# Boolean:: true if it is identical, false otherwise.
#
def identical?
source = File.expand_path(render, File.dirname(destination))
exists? && File.identical?(source, destination)
end
def invoke!
invoke_with_conflict_check do
require "fileutils"
FileUtils.mkdir_p(File.dirname(destination))
# Create a symlink by default
config[:symbolic] = true if config[:symbolic].nil?
File.unlink(destination) if exists?
if config[:symbolic]
File.symlink(render, destination)
else
File.link(render, destination)
end
end
given_destination
end
def exists?
super || File.symlink?(destination)
end
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/lib/thor/actions/create_file.rb | lib/thor/actions/create_file.rb | require_relative "empty_directory"
class Thor
module Actions
# Create a new file relative to the destination root with the given data,
# which is the return value of a block or a data string.
#
# ==== Parameters
# destination<String>:: the relative path to the destination root.
# data<String|NilClass>:: the data to append to the file.
# config<Hash>:: give :verbose => false to not log the status.
#
# ==== Examples
#
# create_file "lib/fun_party.rb" do
# hostname = ask("What is the virtual hostname I should use?")
# "vhost.name = #{hostname}"
# end
#
# create_file "config/apache.conf", "your apache config"
#
def create_file(destination, *args, &block)
config = args.last.is_a?(Hash) ? args.pop : {}
data = args.first
action CreateFile.new(self, destination, block || data.to_s, config)
end
alias_method :add_file, :create_file
# CreateFile is a subset of Template, which instead of rendering a file with
# ERB, it gets the content from the user.
#
class CreateFile < EmptyDirectory #:nodoc:
attr_reader :data
def initialize(base, destination, data, config = {})
@data = data
super(base, destination, config)
end
# Checks if the content of the file at the destination is identical to the rendered result.
#
# ==== Returns
# Boolean:: true if it is identical, false otherwise.
#
def identical?
# binread uses ASCII-8BIT, so to avoid false negatives, the string must use the same
exists? && File.binread(destination) == String.new(render).force_encoding("ASCII-8BIT")
end
# Holds the content to be added to the file.
#
def render
@render ||= if data.is_a?(Proc)
data.call
else
data
end
end
def invoke!
invoke_with_conflict_check do
require "fileutils"
FileUtils.mkdir_p(File.dirname(destination))
File.open(destination, "wb", config[:perm]) { |f| f.write render }
end
given_destination
end
protected
# Now on conflict we check if the file is identical or not.
#
def on_conflict_behavior(&block)
if identical?
say_status :identical, :blue
else
options = base.options.merge(config)
force_or_skip_or_conflict(options[:force], options[:skip], &block)
end
end
# If force is true, run the action, otherwise check if it's not being
# skipped. If both are false, show the file_collision menu, if the menu
# returns true, force it, otherwise skip.
#
def force_or_skip_or_conflict(force, skip, &block)
if force
say_status :force, :yellow
yield unless pretend?
elsif skip
say_status :skip, :yellow
else
say_status :conflict, :red
force_or_skip_or_conflict(force_on_collision?, true, &block)
end
end
# Shows the file collision menu to the user and gets the result.
#
def force_on_collision?
base.shell.file_collision(destination) { render }
end
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/lib/thor/actions/file_manipulation.rb | lib/thor/actions/file_manipulation.rb | require "erb"
class Thor
module Actions
# Copies the file from the relative source to the relative destination. If
# the destination is not given it's assumed to be equal to the source.
#
# ==== Parameters
# source<String>:: the relative path to the source root.
# destination<String>:: the relative path to the destination root.
# config<Hash>:: give :verbose => false to not log the status, and
# :mode => :preserve, to preserve the file mode from the source.
#
# ==== Examples
#
# copy_file "README", "doc/README"
#
# copy_file "doc/README"
#
def copy_file(source, *args, &block)
config = args.last.is_a?(Hash) ? args.pop : {}
destination = args.first || source
source = File.expand_path(find_in_source_paths(source.to_s))
resulting_destination = create_file destination, nil, config do
content = File.binread(source)
content = yield(content) if block
content
end
if config[:mode] == :preserve
mode = File.stat(source).mode
chmod(resulting_destination, mode, config)
end
end
# Links the file from the relative source to the relative destination. If
# the destination is not given it's assumed to be equal to the source.
#
# ==== Parameters
# source<String>:: the relative path to the source root.
# destination<String>:: the relative path to the destination root.
# config<Hash>:: give :verbose => false to not log the status.
#
# ==== Examples
#
# link_file "README", "doc/README"
#
# link_file "doc/README"
#
def link_file(source, *args)
config = args.last.is_a?(Hash) ? args.pop : {}
destination = args.first || source
source = File.expand_path(find_in_source_paths(source.to_s))
create_link destination, source, config
end
# Gets the content at the given address and places it at the given relative
# destination. If a block is given instead of destination, the content of
# the url is yielded and used as location.
#
# +get+ relies on open-uri, so passing application user input would provide
# a command injection attack vector.
#
# ==== Parameters
# source<String>:: the address of the given content.
# destination<String>:: the relative path to the destination root.
# config<Hash>:: give :verbose => false to not log the status, and
# :http_headers => <Hash> to add headers to an http request.
#
# ==== Examples
#
# get "http://gist.github.com/103208", "doc/README"
#
# get "http://gist.github.com/103208", "doc/README", :http_headers => {"Content-Type" => "application/json"}
#
# get "http://gist.github.com/103208" do |content|
# content.split("\n").first
# end
#
def get(source, *args, &block)
config = args.last.is_a?(Hash) ? args.pop : {}
destination = args.first
render = if source =~ %r{^https?\://}
require "open-uri"
URI.send(:open, source, config.fetch(:http_headers, {})) { |input| input.binmode.read }
else
source = File.expand_path(find_in_source_paths(source.to_s))
File.open(source) { |input| input.binmode.read }
end
destination ||= if block_given?
block.arity == 1 ? yield(render) : yield
else
File.basename(source)
end
create_file destination, render, config
end
# Gets an ERB template at the relative source, executes it and makes a copy
# at the relative destination. If the destination is not given it's assumed
# to be equal to the source removing .tt from the filename.
#
# ==== Parameters
# source<String>:: the relative path to the source root.
# destination<String>:: the relative path to the destination root.
# config<Hash>:: give :verbose => false to not log the status.
#
# ==== Examples
#
# template "README", "doc/README"
#
# template "doc/README"
#
def template(source, *args, &block)
config = args.last.is_a?(Hash) ? args.pop : {}
destination = args.first || source.sub(/#{TEMPLATE_EXTNAME}$/, "")
source = File.expand_path(find_in_source_paths(source.to_s))
context = config.delete(:context) || instance_eval("binding")
create_file destination, nil, config do
capturable_erb = CapturableERB.new(::File.binread(source), trim_mode: "-", eoutvar: "@output_buffer")
content = capturable_erb.tap do |erb|
erb.filename = source
end.result(context)
content = yield(content) if block
content
end
end
# Changes the mode of the given file or directory.
#
# ==== Parameters
# mode<Integer>:: the file mode
# path<String>:: the name of the file to change mode
# config<Hash>:: give :verbose => false to not log the status.
#
# ==== Example
#
# chmod "script/server", 0755
#
def chmod(path, mode, config = {})
return unless behavior == :invoke
path = File.expand_path(path, destination_root)
say_status :chmod, relative_to_original_destination_root(path), config.fetch(:verbose, true)
unless options[:pretend]
require "fileutils"
FileUtils.chmod_R(mode, path)
end
end
# Prepend text to a file. Since it depends on insert_into_file, it's reversible.
#
# ==== Parameters
# path<String>:: path of the file to be changed
# data<String>:: the data to prepend to the file, can be also given as a block.
# config<Hash>:: give :verbose => false to not log the status.
#
# ==== Example
#
# prepend_to_file 'config/environments/test.rb', 'config.gem "rspec"'
#
# prepend_to_file 'config/environments/test.rb' do
# 'config.gem "rspec"'
# end
#
def prepend_to_file(path, *args, &block)
config = args.last.is_a?(Hash) ? args.pop : {}
config[:after] = /\A/
insert_into_file(path, *(args << config), &block)
end
alias_method :prepend_file, :prepend_to_file
# Append text to a file. Since it depends on insert_into_file, it's reversible.
#
# ==== Parameters
# path<String>:: path of the file to be changed
# data<String>:: the data to append to the file, can be also given as a block.
# config<Hash>:: give :verbose => false to not log the status.
#
# ==== Example
#
# append_to_file 'config/environments/test.rb', 'config.gem "rspec"'
#
# append_to_file 'config/environments/test.rb' do
# 'config.gem "rspec"'
# end
#
def append_to_file(path, *args, &block)
config = args.last.is_a?(Hash) ? args.pop : {}
config[:before] = /\z/
insert_into_file(path, *(args << config), &block)
end
alias_method :append_file, :append_to_file
# Injects text right after the class definition. Since it depends on
# insert_into_file, it's reversible.
#
# ==== Parameters
# path<String>:: path of the file to be changed
# klass<String|Class>:: the class to be manipulated
# data<String>:: the data to append to the class, can be also given as a block.
# config<Hash>:: give :verbose => false to not log the status.
#
# ==== Examples
#
# inject_into_class "app/controllers/application_controller.rb", "ApplicationController", " filter_parameter :password\n"
#
# inject_into_class "app/controllers/application_controller.rb", "ApplicationController" do
# " filter_parameter :password\n"
# end
#
def inject_into_class(path, klass, *args, &block)
config = args.last.is_a?(Hash) ? args.pop : {}
config[:after] = /class #{klass}\n|class #{klass} .*\n/
insert_into_file(path, *(args << config), &block)
end
# Injects text right after the module definition. Since it depends on
# insert_into_file, it's reversible.
#
# ==== Parameters
# path<String>:: path of the file to be changed
# module_name<String|Class>:: the module to be manipulated
# data<String>:: the data to append to the class, can be also given as a block.
# config<Hash>:: give :verbose => false to not log the status.
#
# ==== Examples
#
# inject_into_module "app/helpers/application_helper.rb", "ApplicationHelper", " def help; 'help'; end\n"
#
# inject_into_module "app/helpers/application_helper.rb", "ApplicationHelper" do
# " def help; 'help'; end\n"
# end
#
def inject_into_module(path, module_name, *args, &block)
config = args.last.is_a?(Hash) ? args.pop : {}
config[:after] = /module #{module_name}\n|module #{module_name} .*\n/
insert_into_file(path, *(args << config), &block)
end
# Run a regular expression replacement on a file, raising an error if the
# contents of the file are not changed.
#
# ==== Parameters
# path<String>:: path of the file to be changed
# flag<Regexp|String>:: the regexp or string to be replaced
# replacement<String>:: the replacement, can be also given as a block
# config<Hash>:: give :verbose => false to not log the status, and
# :force => true, to force the replacement regardless of runner behavior.
#
# ==== Example
#
# gsub_file! 'app/controllers/application_controller.rb', /#\s*(filter_parameter_logging :password)/, '\1'
#
# gsub_file! 'README', /rake/, :green do |match|
# match << " no more. Use thor!"
# end
#
def gsub_file!(path, flag, *args, &block)
config = args.last.is_a?(Hash) ? args.pop : {}
return unless behavior == :invoke || config.fetch(:force, false)
path = File.expand_path(path, destination_root)
say_status :gsub, relative_to_original_destination_root(path), config.fetch(:verbose, true)
actually_gsub_file(path, flag, args, true, &block) unless options[:pretend]
end
# Run a regular expression replacement on a file.
#
# ==== Parameters
# path<String>:: path of the file to be changed
# flag<Regexp|String>:: the regexp or string to be replaced
# replacement<String>:: the replacement, can be also given as a block
# config<Hash>:: give :verbose => false to not log the status, and
# :force => true, to force the replacement regardless of runner behavior.
#
# ==== Example
#
# gsub_file 'app/controllers/application_controller.rb', /#\s*(filter_parameter_logging :password)/, '\1'
#
# gsub_file 'README', /rake/, :green do |match|
# match << " no more. Use thor!"
# end
#
def gsub_file(path, flag, *args, &block)
config = args.last.is_a?(Hash) ? args.pop : {}
return unless behavior == :invoke || config.fetch(:force, false)
path = File.expand_path(path, destination_root)
say_status :gsub, relative_to_original_destination_root(path), config.fetch(:verbose, true)
actually_gsub_file(path, flag, args, false, &block) unless options[:pretend]
end
# Uncomment all lines matching a given regex. Preserves indentation before
# the comment hash and removes the hash and any immediate following space.
#
# ==== Parameters
# path<String>:: path of the file to be changed
# flag<Regexp|String>:: the regexp or string used to decide which lines to uncomment
# config<Hash>:: give :verbose => false to not log the status.
#
# ==== Example
#
# uncomment_lines 'config/initializers/session_store.rb', /active_record/
#
def uncomment_lines(path, flag, *args)
flag = flag.respond_to?(:source) ? flag.source : flag
gsub_file(path, /^(\s*)#[[:blank:]]?(.*#{flag})/, '\1\2', *args)
end
# Comment all lines matching a given regex. It will leave the space
# which existed before the beginning of the line in tact and will insert
# a single space after the comment hash.
#
# ==== Parameters
# path<String>:: path of the file to be changed
# flag<Regexp|String>:: the regexp or string used to decide which lines to comment
# config<Hash>:: give :verbose => false to not log the status.
#
# ==== Example
#
# comment_lines 'config/initializers/session_store.rb', /cookie_store/
#
def comment_lines(path, flag, *args)
flag = flag.respond_to?(:source) ? flag.source : flag
gsub_file(path, /^(\s*)([^#\n]*#{flag})/, '\1# \2', *args)
end
# Removes a file at the given location.
#
# ==== Parameters
# path<String>:: path of the file to be changed
# config<Hash>:: give :verbose => false to not log the status.
#
# ==== Example
#
# remove_file 'README'
# remove_file 'app/controllers/application_controller.rb'
#
def remove_file(path, config = {})
return unless behavior == :invoke
path = File.expand_path(path, destination_root)
say_status :remove, relative_to_original_destination_root(path), config.fetch(:verbose, true)
if !options[:pretend] && (File.exist?(path) || File.symlink?(path))
require "fileutils"
::FileUtils.rm_rf(path)
end
end
alias_method :remove_dir, :remove_file
attr_accessor :output_buffer
private :output_buffer, :output_buffer=
private
def concat(string)
@output_buffer.concat(string)
end
def capture(*args)
with_output_buffer { yield(*args) }
end
def with_output_buffer(buf = "".dup) #:nodoc:
raise ArgumentError, "Buffer cannot be a frozen object" if buf.frozen?
old_buffer = output_buffer
self.output_buffer = buf
yield
output_buffer
ensure
self.output_buffer = old_buffer
end
def actually_gsub_file(path, flag, args, error_on_no_change, &block)
content = File.binread(path)
success = content.gsub!(flag, *args, &block)
if success.nil? && error_on_no_change
raise Thor::Error, "The content of #{path} did not change"
end
File.open(path, "wb") { |file| file.write(content) }
end
# Thor::Actions#capture depends on what kind of buffer is used in ERB.
# Thus CapturableERB fixes ERB to use String buffer.
class CapturableERB < ERB
def set_eoutvar(compiler, eoutvar = "_erbout")
compiler.put_cmd = "#{eoutvar}.concat"
compiler.insert_cmd = "#{eoutvar}.concat"
compiler.pre_cmd = ["#{eoutvar} = ''.dup"]
compiler.post_cmd = [eoutvar]
end
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/lib/thor/actions/inject_into_file.rb | lib/thor/actions/inject_into_file.rb | require_relative "empty_directory"
class Thor
module Actions
WARNINGS = {unchanged_no_flag: "File unchanged! Either the supplied flag value not found or the content has already been inserted!"}
# Injects the given content into a file, raising an error if the contents of
# the file are not changed. Different from gsub_file, this method is reversible.
#
# ==== Parameters
# destination<String>:: Relative path to the destination root
# data<String>:: Data to add to the file. Can be given as a block.
# config<Hash>:: give :verbose => false to not log the status and the flag
# for injection (:after or :before) or :force => true for
# insert two or more times the same content.
#
# ==== Examples
#
# insert_into_file "config/environment.rb", "config.gem :thor", :after => "Rails::Initializer.run do |config|\n"
#
# insert_into_file "config/environment.rb", :after => "Rails::Initializer.run do |config|\n" do
# gems = ask "Which gems would you like to add?"
# gems.split(" ").map{ |gem| " config.gem :#{gem}" }.join("\n")
# end
#
def insert_into_file!(destination, *args, &block)
data = block_given? ? block : args.shift
config = args.shift || {}
config[:after] = /\z/ unless config.key?(:before) || config.key?(:after)
config = config.merge({error_on_no_change: true})
action InjectIntoFile.new(self, destination, data, config)
end
alias_method :inject_into_file!, :insert_into_file!
# Injects the given content into a file. Different from gsub_file, this
# method is reversible.
#
# ==== Parameters
# destination<String>:: Relative path to the destination root
# data<String>:: Data to add to the file. Can be given as a block.
# config<Hash>:: give :verbose => false to not log the status and the flag
# for injection (:after or :before) or :force => true for
# insert two or more times the same content.
#
# ==== Examples
#
# insert_into_file "config/environment.rb", "config.gem :thor", :after => "Rails::Initializer.run do |config|\n"
#
# insert_into_file "config/environment.rb", :after => "Rails::Initializer.run do |config|\n" do
# gems = ask "Which gems would you like to add?"
# gems.split(" ").map{ |gem| " config.gem :#{gem}" }.join("\n")
# end
#
def insert_into_file(destination, *args, &block)
data = block_given? ? block : args.shift
config = args.shift || {}
config[:after] = /\z/ unless config.key?(:before) || config.key?(:after)
action InjectIntoFile.new(self, destination, data, config)
end
alias_method :inject_into_file, :insert_into_file
class InjectIntoFile < EmptyDirectory #:nodoc:
attr_reader :replacement, :flag, :behavior
def initialize(base, destination, data, config)
super(base, destination, {verbose: true}.merge(config))
@behavior, @flag = if @config.key?(:after)
[:after, @config.delete(:after)]
else
[:before, @config.delete(:before)]
end
@replacement = data.is_a?(Proc) ? data.call : data
@flag = Regexp.escape(@flag) unless @flag.is_a?(Regexp)
@error_on_no_change = @config.fetch(:error_on_no_change, false)
end
def invoke!
content = if @behavior == :after
'\0' + replacement
else
replacement + '\0'
end
if exists?
if replace!(/#{flag}/, content, config[:force])
say_status(:invoke)
elsif @error_on_no_change
raise Thor::Error, "The content of #{destination} did not change"
elsif replacement_present?
say_status(:unchanged, color: :blue)
else
say_status(:unchanged, warning: WARNINGS[:unchanged_no_flag], color: :red)
end
else
unless pretend?
raise Thor::Error, "The file #{ destination } does not appear to exist"
end
end
end
def revoke!
say_status :revoke
regexp = if @behavior == :after
content = '\1\2'
/(#{flag})(.*)(#{Regexp.escape(replacement)})/m
else
content = '\2\3'
/(#{Regexp.escape(replacement)})(.*)(#{flag})/m
end
replace!(regexp, content, true)
end
protected
def say_status(behavior, warning: nil, color: nil)
status = if behavior == :invoke
if flag == /\A/
:prepend
elsif flag == /\z/
:append
else
:insert
end
elsif warning
warning
elsif behavior == :unchanged
:unchanged
else
:subtract
end
super(status, (color || config[:verbose]))
end
def content
@content ||= File.read(destination)
end
def replacement_present?
content.include?(replacement)
end
# Adds the content to the file.
#
def replace!(regexp, string, force)
if force || !replacement_present?
success = content.gsub!(regexp, string)
File.open(destination, "wb") { |file| file.write(content) } unless pretend?
success
end
end
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/lib/thor/actions/empty_directory.rb | lib/thor/actions/empty_directory.rb | class Thor
module Actions
# Creates an empty directory.
#
# ==== Parameters
# destination<String>:: the relative path to the destination root.
# config<Hash>:: give :verbose => false to not log the status.
#
# ==== Examples
#
# empty_directory "doc"
#
def empty_directory(destination, config = {})
action EmptyDirectory.new(self, destination, config)
end
# Class which holds create directory logic. This is the base class for
# other actions like create_file and directory.
#
# This implementation is based in Templater actions, created by Jonas Nicklas
# and Michael S. Klishin under MIT LICENSE.
#
class EmptyDirectory #:nodoc:
attr_reader :base, :destination, :given_destination, :relative_destination, :config
# Initializes given the source and destination.
#
# ==== Parameters
# base<Thor::Base>:: A Thor::Base instance
# source<String>:: Relative path to the source of this file
# destination<String>:: Relative path to the destination of this file
# config<Hash>:: give :verbose => false to not log the status.
#
def initialize(base, destination, config = {})
@base = base
@config = {verbose: true}.merge(config)
self.destination = destination
end
# Checks if the destination file already exists.
#
# ==== Returns
# Boolean:: true if the file exists, false otherwise.
#
def exists?
::File.exist?(destination)
end
def invoke!
invoke_with_conflict_check do
require "fileutils"
::FileUtils.mkdir_p(destination)
end
end
def revoke!
say_status :remove, :red
require "fileutils"
::FileUtils.rm_rf(destination) if !pretend? && exists?
given_destination
end
protected
# Shortcut for pretend.
#
def pretend?
base.options[:pretend]
end
# Sets the absolute destination value from a relative destination value.
# It also stores the given and relative destination. Let's suppose our
# script is being executed on "dest", it sets the destination root to
# "dest". The destination, given_destination and relative_destination
# are related in the following way:
#
# inside "bar" do
# empty_directory "baz"
# end
#
# destination #=> dest/bar/baz
# relative_destination #=> bar/baz
# given_destination #=> baz
#
def destination=(destination)
return unless destination
@given_destination = convert_encoded_instructions(destination.to_s)
@destination = ::File.expand_path(@given_destination, base.destination_root)
@relative_destination = base.relative_to_original_destination_root(@destination)
end
# Filenames in the encoded form are converted. If you have a file:
#
# %file_name%.rb
#
# It calls #file_name from the base and replaces %-string with the
# return value (should be String) of #file_name:
#
# user.rb
#
# The method referenced can be either public or private.
#
def convert_encoded_instructions(filename)
filename.gsub(/%(.*?)%/) do |initial_string|
method = $1.strip
base.respond_to?(method, true) ? base.send(method) : initial_string
end
end
# Receives a hash of options and just execute the block if some
# conditions are met.
#
def invoke_with_conflict_check(&block)
if exists?
on_conflict_behavior(&block)
else
yield unless pretend?
say_status :create, :green
end
destination
rescue Errno::EISDIR, Errno::EEXIST
on_file_clash_behavior
end
def on_file_clash_behavior
say_status :file_clash, :red
end
# What to do when the destination file already exists.
#
def on_conflict_behavior
say_status :exist, :blue
end
# Shortcut to say_status shell method.
#
def say_status(status, color)
base.shell.say_status status, relative_destination, color if config[:verbose]
end
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/lib/thor/core_ext/hash_with_indifferent_access.rb | lib/thor/core_ext/hash_with_indifferent_access.rb | class Thor
module CoreExt #:nodoc:
# A hash with indifferent access and magic predicates.
#
# hash = Thor::CoreExt::HashWithIndifferentAccess.new 'foo' => 'bar', 'baz' => 'bee', 'force' => true
#
# hash[:foo] #=> 'bar'
# hash['foo'] #=> 'bar'
# hash.foo? #=> true
#
class HashWithIndifferentAccess < ::Hash #:nodoc:
def initialize(hash = {})
super()
hash.each do |key, value|
self[convert_key(key)] = value
end
end
def [](key)
super(convert_key(key))
end
def []=(key, value)
super(convert_key(key), value)
end
def delete(key)
super(convert_key(key))
end
def except(*keys)
dup.tap do |hash|
keys.each { |key| hash.delete(convert_key(key)) }
end
end
def fetch(key, *args)
super(convert_key(key), *args)
end
def slice(*keys)
super(*keys.map{ |key| convert_key(key) })
end
def key?(key)
super(convert_key(key))
end
def values_at(*indices)
indices.map { |key| self[convert_key(key)] }
end
def merge(other)
dup.merge!(other)
end
def merge!(other)
other.each do |key, value|
self[convert_key(key)] = value
end
self
end
def reverse_merge(other)
self.class.new(other).merge(self)
end
def reverse_merge!(other_hash)
replace(reverse_merge(other_hash))
end
def replace(other_hash)
super(other_hash)
end
# Convert to a Hash with String keys.
def to_hash
Hash.new(default).merge!(self)
end
protected
def convert_key(key)
key.is_a?(Symbol) ? key.to_s : key
end
# Magic predicates. For instance:
#
# options.force? # => !!options['force']
# options.shebang # => "/usr/lib/local/ruby"
# options.test_framework?(:rspec) # => options[:test_framework] == :rspec
#
def method_missing(method, *args)
method = method.to_s
if method =~ /^(\w+)\?$/
if args.empty?
!!self[$1]
else
self[$1] == args.first
end
else
self[method]
end
end
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/lib/thor/shell/lcs_diff.rb | lib/thor/shell/lcs_diff.rb | module LCSDiff
protected
# Overwrite show_diff to show diff with colors if Diff::LCS is
# available.
def show_diff(destination, content) #:nodoc:
if diff_lcs_loaded? && ENV["THOR_DIFF"].nil? && ENV["RAILS_DIFF"].nil?
actual = File.binread(destination).to_s.split("\n")
content = content.to_s.split("\n")
Diff::LCS.sdiff(actual, content).each do |diff|
output_diff_line(diff)
end
else
super
end
end
private
def output_diff_line(diff) #:nodoc:
case diff.action
when "-"
say "- #{diff.old_element.chomp}", :red, true
when "+"
say "+ #{diff.new_element.chomp}", :green, true
when "!"
say "- #{diff.old_element.chomp}", :red, true
say "+ #{diff.new_element.chomp}", :green, true
else
say " #{diff.old_element.chomp}", nil, true
end
end
# Check if Diff::LCS is loaded. If it is, use it to create pretty output
# for diff.
def diff_lcs_loaded? #:nodoc:
return true if defined?(Diff::LCS)
return @diff_lcs_loaded unless @diff_lcs_loaded.nil?
@diff_lcs_loaded = begin
require "diff/lcs"
true
rescue LoadError
false
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/lib/thor/shell/column_printer.rb | lib/thor/shell/column_printer.rb | require_relative "terminal"
class Thor
module Shell
class ColumnPrinter
attr_reader :stdout, :options
def initialize(stdout, options = {})
@stdout = stdout
@options = options
@indent = options[:indent].to_i
end
def print(array)
return if array.empty?
colwidth = (array.map { |el| el.to_s.size }.max || 0) + 2
array.each_with_index do |value, index|
# Don't output trailing spaces when printing the last column
if ((((index + 1) % (Terminal.terminal_width / colwidth))).zero? && !index.zero?) || index + 1 == array.length
stdout.puts value
else
stdout.printf("%-#{colwidth}s", value)
end
end
end
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/lib/thor/shell/color.rb | lib/thor/shell/color.rb | # frozen_string_literal: true
require_relative "basic"
require_relative "lcs_diff"
class Thor
module Shell
# Inherit from Thor::Shell::Basic and add set_color behavior. Check
# Thor::Shell::Basic to see all available methods.
#
class Color < Basic
include LCSDiff
# Embed in a String to clear all previous ANSI sequences.
CLEAR = "\e[0m"
# The start of an ANSI bold sequence.
BOLD = "\e[1m"
# Set the terminal's foreground ANSI color to black.
BLACK = "\e[30m"
# Set the terminal's foreground ANSI color to red.
RED = "\e[31m"
# Set the terminal's foreground ANSI color to green.
GREEN = "\e[32m"
# Set the terminal's foreground ANSI color to yellow.
YELLOW = "\e[33m"
# Set the terminal's foreground ANSI color to blue.
BLUE = "\e[34m"
# Set the terminal's foreground ANSI color to magenta.
MAGENTA = "\e[35m"
# Set the terminal's foreground ANSI color to cyan.
CYAN = "\e[36m"
# Set the terminal's foreground ANSI color to white.
WHITE = "\e[37m"
# Set the terminal's background ANSI color to black.
ON_BLACK = "\e[40m"
# Set the terminal's background ANSI color to red.
ON_RED = "\e[41m"
# Set the terminal's background ANSI color to green.
ON_GREEN = "\e[42m"
# Set the terminal's background ANSI color to yellow.
ON_YELLOW = "\e[43m"
# Set the terminal's background ANSI color to blue.
ON_BLUE = "\e[44m"
# Set the terminal's background ANSI color to magenta.
ON_MAGENTA = "\e[45m"
# Set the terminal's background ANSI color to cyan.
ON_CYAN = "\e[46m"
# Set the terminal's background ANSI color to white.
ON_WHITE = "\e[47m"
# Set color by using a string or one of the defined constants. If a third
# option is set to true, it also adds bold to the string. This is based
# on Highline implementation and it automatically appends CLEAR to the end
# of the returned String.
#
# Pass foreground, background and bold options to this method as
# symbols.
#
# Example:
#
# set_color "Hi!", :red, :on_white, :bold
#
# The available colors are:
#
# :bold
# :black
# :red
# :green
# :yellow
# :blue
# :magenta
# :cyan
# :white
# :on_black
# :on_red
# :on_green
# :on_yellow
# :on_blue
# :on_magenta
# :on_cyan
# :on_white
def set_color(string, *colors)
if colors.compact.empty? || !can_display_colors?
string
elsif colors.all? { |color| color.is_a?(Symbol) || color.is_a?(String) }
ansi_colors = colors.map { |color| lookup_color(color) }
"#{ansi_colors.join}#{string}#{CLEAR}"
else
# The old API was `set_color(color, bold=boolean)`. We
# continue to support the old API because you should never
# break old APIs unnecessarily :P
foreground, bold = colors
foreground = self.class.const_get(foreground.to_s.upcase) if foreground.is_a?(Symbol)
bold = bold ? BOLD : ""
"#{bold}#{foreground}#{string}#{CLEAR}"
end
end
protected
def can_display_colors?
are_colors_supported? && !are_colors_disabled?
end
def are_colors_supported?
stdout.tty? && ENV["TERM"] != "dumb"
end
def are_colors_disabled?
!ENV["NO_COLOR"].nil? && !ENV["NO_COLOR"].empty?
end
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/lib/thor/shell/basic.rb | lib/thor/shell/basic.rb | require_relative "column_printer"
require_relative "table_printer"
require_relative "wrapped_printer"
class Thor
module Shell
class Basic
attr_accessor :base
attr_reader :padding
# Initialize base, mute and padding to nil.
#
def initialize #:nodoc:
@base = nil
@mute = false
@padding = 0
@always_force = false
end
# Mute everything that's inside given block
#
def mute
@mute = true
yield
ensure
@mute = false
end
# Check if base is muted
#
def mute?
@mute
end
# Sets the output padding, not allowing less than zero values.
#
def padding=(value)
@padding = [0, value].max
end
# Sets the output padding while executing a block and resets it.
#
def indent(count = 1)
orig_padding = padding
self.padding = padding + count
yield
self.padding = orig_padding
end
# Asks something to the user and receives a response.
#
# If a default value is specified it will be presented to the user
# and allows them to select that value with an empty response. This
# option is ignored when limited answers are supplied.
#
# If asked to limit the correct responses, you can pass in an
# array of acceptable answers. If one of those is not supplied,
# they will be shown a message stating that one of those answers
# must be given and re-asked the question.
#
# If asking for sensitive information, the :echo option can be set
# to false to mask user input from $stdin.
#
# If the required input is a path, then set the path option to
# true. This will enable tab completion for file paths relative
# to the current working directory on systems that support
# Readline.
#
# ==== Example
# ask("What is your name?")
#
# ask("What is the planet furthest from the sun?", :default => "Neptune")
#
# ask("What is your favorite Neopolitan flavor?", :limited_to => ["strawberry", "chocolate", "vanilla"])
#
# ask("What is your password?", :echo => false)
#
# ask("Where should the file be saved?", :path => true)
#
def ask(statement, *args)
options = args.last.is_a?(Hash) ? args.pop : {}
color = args.first
if options[:limited_to]
ask_filtered(statement, color, options)
else
ask_simply(statement, color, options)
end
end
# Say (print) something to the user. If the sentence ends with a whitespace
# or tab character, a new line is not appended (print + flush). Otherwise
# are passed straight to puts (behavior got from Highline).
#
# ==== Example
# say("I know you knew that.")
#
def say(message = "", color = nil, force_new_line = (message.to_s !~ /( |\t)\Z/))
return if quiet?
buffer = prepare_message(message, *color)
buffer << "\n" if force_new_line && !message.to_s.end_with?("\n")
stdout.print(buffer)
stdout.flush
end
# Say (print) an error to the user. If the sentence ends with a whitespace
# or tab character, a new line is not appended (print + flush). Otherwise
# are passed straight to puts (behavior got from Highline).
#
# ==== Example
# say_error("error: something went wrong")
#
def say_error(message = "", color = nil, force_new_line = (message.to_s !~ /( |\t)\Z/))
return if quiet?
buffer = prepare_message(message, *color)
buffer << "\n" if force_new_line && !message.to_s.end_with?("\n")
stderr.print(buffer)
stderr.flush
end
# Say a status with the given color and appends the message. Since this
# method is used frequently by actions, it allows nil or false to be given
# in log_status, avoiding the message from being shown. If a Symbol is
# given in log_status, it's used as the color.
#
def say_status(status, message, log_status = true)
return if quiet? || log_status == false
spaces = " " * (padding + 1)
status = status.to_s.rjust(12)
margin = " " * status.length + spaces
color = log_status.is_a?(Symbol) ? log_status : :green
status = set_color status, color, true if color
message = message.to_s.chomp.gsub(/(?<!\A)^/, margin)
buffer = "#{status}#{spaces}#{message}\n"
stdout.print(buffer)
stdout.flush
end
# Asks the user a question and returns true if the user replies "y" or
# "yes".
#
def yes?(statement, color = nil)
!!(ask(statement, color, add_to_history: false) =~ is?(:yes))
end
# Asks the user a question and returns true if the user replies "n" or
# "no".
#
def no?(statement, color = nil)
!!(ask(statement, color, add_to_history: false) =~ is?(:no))
end
# Prints values in columns
#
# ==== Parameters
# Array[String, String, ...]
#
def print_in_columns(array)
printer = ColumnPrinter.new(stdout)
printer.print(array)
end
# Prints a table.
#
# ==== Parameters
# Array[Array[String, String, ...]]
#
# ==== Options
# indent<Integer>:: Indent the first column by indent value.
# colwidth<Integer>:: Force the first column to colwidth spaces wide.
# borders<Boolean>:: Adds ascii borders.
#
def print_table(array, options = {}) # rubocop:disable Metrics/MethodLength
printer = TablePrinter.new(stdout, options)
printer.print(array)
end
# Prints a long string, word-wrapping the text to the current width of the
# terminal display. Ideal for printing heredocs.
#
# ==== Parameters
# String
#
# ==== Options
# indent<Integer>:: Indent each line of the printed paragraph by indent value.
#
def print_wrapped(message, options = {})
printer = WrappedPrinter.new(stdout, options)
printer.print(message)
end
# Deals with file collision and returns true if the file should be
# overwritten and false otherwise. If a block is given, it uses the block
# response as the content for the diff.
#
# ==== Parameters
# destination<String>:: the destination file to solve conflicts
# block<Proc>:: an optional block that returns the value to be used in diff and merge
#
def file_collision(destination)
return true if @always_force
options = block_given? ? "[Ynaqdhm]" : "[Ynaqh]"
loop do
answer = ask(
%[Overwrite #{destination}? (enter "h" for help) #{options}],
add_to_history: false
)
case answer
when nil
say ""
return true
when is?(:yes), is?(:force), ""
return true
when is?(:no), is?(:skip)
return false
when is?(:always)
return @always_force = true
when is?(:quit)
say "Aborting..."
raise SystemExit
when is?(:diff)
show_diff(destination, yield) if block_given?
say "Retrying..."
when is?(:merge)
if block_given? && !merge_tool.empty?
merge(destination, yield)
return nil
end
say "Please specify merge tool to `THOR_MERGE` env."
else
say file_collision_help(block_given?)
end
end
end
# Called if something goes wrong during the execution. This is used by Thor
# internally and should not be used inside your scripts. If something went
# wrong, you can always raise an exception. If you raise a Thor::Error, it
# will be rescued and wrapped in the method below.
#
def error(statement)
stderr.puts statement
end
# Apply color to the given string with optional bold. Disabled in the
# Thor::Shell::Basic class.
#
def set_color(string, *) #:nodoc:
string
end
protected
def prepare_message(message, *color)
spaces = " " * padding
spaces + set_color(message.to_s, *color)
end
def can_display_colors?
false
end
def lookup_color(color)
return color unless color.is_a?(Symbol)
self.class.const_get(color.to_s.upcase)
end
def stdout
$stdout
end
def stderr
$stderr
end
def is?(value) #:nodoc:
value = value.to_s
if value.size == 1
/\A#{value}\z/i
else
/\A(#{value}|#{value[0, 1]})\z/i
end
end
def file_collision_help(block_given) #:nodoc:
help = <<-HELP
Y - yes, overwrite
n - no, do not overwrite
a - all, overwrite this and all others
q - quit, abort
h - help, show this help
HELP
if block_given
help << <<-HELP
d - diff, show the differences between the old and the new
m - merge, run merge tool
HELP
end
help
end
def show_diff(destination, content) #:nodoc:
require "tempfile"
Tempfile.open(File.basename(destination), File.dirname(destination), binmode: true) do |temp|
temp.write content
temp.rewind
system(*diff_tool, destination, temp.path)
end
end
def quiet? #:nodoc:
mute? || (base && base.options[:quiet])
end
def unix?
Terminal.unix?
end
def ask_simply(statement, color, options)
default = options[:default]
message = [statement, ("(#{default})" if default), nil].uniq.join(" ")
message = prepare_message(message, *color)
result = Thor::LineEditor.readline(message, options)
return unless result
result = result.strip
if default && result == ""
default
else
result
end
end
def ask_filtered(statement, color, options)
answer_set = options[:limited_to]
case_insensitive = options.fetch(:case_insensitive, false)
correct_answer = nil
until correct_answer
answers = answer_set.join(", ")
answer = ask_simply("#{statement} [#{answers}]", color, options)
correct_answer = answer_match(answer_set, answer, case_insensitive)
say("Your response must be one of: [#{answers}]. Please try again.") unless correct_answer
end
correct_answer
end
def answer_match(possibilities, answer, case_insensitive)
if case_insensitive
possibilities.detect{ |possibility| possibility.downcase == answer.downcase }
else
possibilities.detect{ |possibility| possibility == answer }
end
end
def merge(destination, content) #:nodoc:
require "tempfile"
Tempfile.open([File.basename(destination), File.extname(destination)], File.dirname(destination)) do |temp|
temp.write content
temp.rewind
system(*merge_tool, temp.path, destination)
end
end
def merge_tool #:nodoc:
@merge_tool ||= begin
require "shellwords"
Shellwords.split(ENV["THOR_MERGE"] || "git difftool --no-index")
end
end
def diff_tool #:nodoc:
@diff_cmd ||= begin
require "shellwords"
Shellwords.split(ENV["THOR_DIFF"] || ENV["RAILS_DIFF"] || "diff -u")
end
end
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/lib/thor/shell/terminal.rb | lib/thor/shell/terminal.rb | class Thor
module Shell
module Terminal
DEFAULT_TERMINAL_WIDTH = 80
class << self
# This code was copied from Rake, available under MIT-LICENSE
# Copyright (c) 2003, 2004 Jim Weirich
def terminal_width
result = if ENV["THOR_COLUMNS"]
ENV["THOR_COLUMNS"].to_i
else
unix? ? dynamic_width : DEFAULT_TERMINAL_WIDTH
end
result < 10 ? DEFAULT_TERMINAL_WIDTH : result
rescue
DEFAULT_TERMINAL_WIDTH
end
def unix?
RUBY_PLATFORM =~ /(aix|darwin|linux|(net|free|open)bsd|cygwin|solaris)/i
end
private
# Calculate the dynamic width of the terminal
def dynamic_width
@dynamic_width ||= (dynamic_width_stty.nonzero? || dynamic_width_tput)
end
def dynamic_width_stty
`stty size 2>/dev/null`.split[1].to_i
end
def dynamic_width_tput
`tput cols 2>/dev/null`.to_i
end
end
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/lib/thor/shell/wrapped_printer.rb | lib/thor/shell/wrapped_printer.rb | require_relative "column_printer"
require_relative "terminal"
class Thor
module Shell
class WrappedPrinter < ColumnPrinter
def print(message)
width = Terminal.terminal_width - @indent
paras = message.split("\n\n")
paras.map! do |unwrapped|
words = unwrapped.split(" ")
counter = words.first.length
words.inject do |memo, word|
word = word.gsub(/\n\005/, "\n").gsub(/\005/, "\n")
counter = 0 if word.include? "\n"
if (counter + word.length + 1) < width
memo = "#{memo} #{word}"
counter += (word.length + 1)
else
memo = "#{memo}\n#{word}"
counter = word.length
end
memo
end
end.compact!
paras.each do |para|
para.split("\n").each do |line|
stdout.puts line.insert(0, " " * @indent)
end
stdout.puts unless para == paras.last
end
end
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/lib/thor/shell/table_printer.rb | lib/thor/shell/table_printer.rb | require_relative "column_printer"
require_relative "terminal"
class Thor
module Shell
class TablePrinter < ColumnPrinter
BORDER_SEPARATOR = :separator
def initialize(stdout, options = {})
super
@formats = []
@maximas = []
@colwidth = options[:colwidth]
@truncate = options[:truncate] == true ? Terminal.terminal_width : options[:truncate]
@padding = 1
end
def print(array)
return if array.empty?
prepare(array)
print_border_separator if options[:borders]
array.each do |row|
if options[:borders] && row == BORDER_SEPARATOR
print_border_separator
next
end
sentence = "".dup
row.each_with_index do |column, index|
sentence << format_cell(column, row.size, index)
end
sentence = truncate(sentence)
sentence << "|" if options[:borders]
stdout.puts indentation + sentence
end
print_border_separator if options[:borders]
end
private
def prepare(array)
array = array.reject{|row| row == BORDER_SEPARATOR }
@formats << "%-#{@colwidth + 2}s".dup if @colwidth
start = @colwidth ? 1 : 0
colcount = array.max { |a, b| a.size <=> b.size }.size
start.upto(colcount - 1) do |index|
maxima = array.map { |row| row[index] ? row[index].to_s.size : 0 }.max
@maximas << maxima
@formats << if options[:borders]
"%-#{maxima}s".dup
elsif index == colcount - 1
# Don't output 2 trailing spaces when printing the last column
"%-s".dup
else
"%-#{maxima + 2}s".dup
end
end
@formats << "%s"
end
def format_cell(column, row_size, index)
maxima = @maximas[index]
f = if column.is_a?(Numeric)
if options[:borders]
# With borders we handle padding separately
"%#{maxima}s"
elsif index == row_size - 1
# Don't output 2 trailing spaces when printing the last column
"%#{maxima}s"
else
"%#{maxima}s "
end
else
@formats[index]
end
cell = "".dup
cell << "|" + " " * @padding if options[:borders]
cell << f % column.to_s
cell << " " * @padding if options[:borders]
cell
end
def print_border_separator
separator = @maximas.map do |maxima|
"+" + "-" * (maxima + 2 * @padding)
end
stdout.puts indentation + separator.join + "+"
end
def truncate(string)
return string unless @truncate
chars = string.chars.to_a
if chars.length <= @truncate
chars.join
else
chars[0, @truncate - 3 - @indent].join + "..."
end
end
def indentation
" " * @indent
end
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/lib/thor/shell/html.rb | lib/thor/shell/html.rb | require_relative "basic"
require_relative "lcs_diff"
class Thor
module Shell
# Inherit from Thor::Shell::Basic and add set_color behavior. Check
# Thor::Shell::Basic to see all available methods.
#
class HTML < Basic
include LCSDiff
# The start of an HTML bold sequence.
BOLD = "font-weight: bold"
# Set the terminal's foreground HTML color to black.
BLACK = "color: black"
# Set the terminal's foreground HTML color to red.
RED = "color: red"
# Set the terminal's foreground HTML color to green.
GREEN = "color: green"
# Set the terminal's foreground HTML color to yellow.
YELLOW = "color: yellow"
# Set the terminal's foreground HTML color to blue.
BLUE = "color: blue"
# Set the terminal's foreground HTML color to magenta.
MAGENTA = "color: magenta"
# Set the terminal's foreground HTML color to cyan.
CYAN = "color: cyan"
# Set the terminal's foreground HTML color to white.
WHITE = "color: white"
# Set the terminal's background HTML color to black.
ON_BLACK = "background-color: black"
# Set the terminal's background HTML color to red.
ON_RED = "background-color: red"
# Set the terminal's background HTML color to green.
ON_GREEN = "background-color: green"
# Set the terminal's background HTML color to yellow.
ON_YELLOW = "background-color: yellow"
# Set the terminal's background HTML color to blue.
ON_BLUE = "background-color: blue"
# Set the terminal's background HTML color to magenta.
ON_MAGENTA = "background-color: magenta"
# Set the terminal's background HTML color to cyan.
ON_CYAN = "background-color: cyan"
# Set the terminal's background HTML color to white.
ON_WHITE = "background-color: white"
# Set color by using a string or one of the defined constants. If a third
# option is set to true, it also adds bold to the string. This is based
# on Highline implementation and it automatically appends CLEAR to the end
# of the returned String.
#
def set_color(string, *colors)
if colors.all? { |color| color.is_a?(Symbol) || color.is_a?(String) }
html_colors = colors.map { |color| lookup_color(color) }
"<span style=\"#{html_colors.join('; ')};\">#{Thor::Util.escape_html(string)}</span>"
else
color, bold = colors
html_color = self.class.const_get(color.to_s.upcase) if color.is_a?(Symbol)
styles = [html_color]
styles << BOLD if bold
"<span style=\"#{styles.join('; ')};\">#{Thor::Util.escape_html(string)}</span>"
end
end
# Ask something to the user and receives a response.
#
# ==== Example
# ask("What is your name?")
#
# TODO: Implement #ask for Thor::Shell::HTML
def ask(statement, color = nil)
raise NotImplementedError, "Implement #ask for Thor::Shell::HTML"
end
protected
def can_display_colors?
true
end
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/lib/thor/parser/options.rb | lib/thor/parser/options.rb | class Thor
class Options < Arguments #:nodoc:
LONG_RE = /^(--\w+(?:-\w+)*)$/
SHORT_RE = /^(-[a-z])$/i
EQ_RE = /^(--\w+(?:-\w+)*|-[a-z])=(.*)$/i
SHORT_SQ_RE = /^-([a-z]{2,})$/i # Allow either -x -v or -xv style for single char args
SHORT_NUM = /^(-[a-z])#{NUMERIC}$/i
OPTS_END = "--".freeze
# Receives a hash and makes it switches.
def self.to_switches(options)
options.map do |key, value|
case value
when true
"--#{key}"
when Array
"--#{key} #{value.map(&:inspect).join(' ')}"
when Hash
"--#{key} #{value.map { |k, v| "#{k}:#{v}" }.join(' ')}"
when nil, false
nil
else
"--#{key} #{value.inspect}"
end
end.compact.join(" ")
end
# Takes a hash of Thor::Option and a hash with defaults.
#
# If +stop_on_unknown+ is true, #parse will stop as soon as it encounters
# an unknown option or a regular argument.
def initialize(hash_options = {}, defaults = {}, stop_on_unknown = false, disable_required_check = false, relations = {})
@stop_on_unknown = stop_on_unknown
@exclusives = (relations[:exclusive_option_names] || []).select{|array| !array.empty?}
@at_least_ones = (relations[:at_least_one_option_names] || []).select{|array| !array.empty?}
@disable_required_check = disable_required_check
options = hash_options.values
super(options)
# Add defaults
defaults.each do |key, value|
@assigns[key.to_s] = value
@non_assigned_required.delete(hash_options[key])
end
@shorts = {}
@switches = {}
@extra = []
@stopped_parsing_after_extra_index = nil
@is_treated_as_value = false
options.each do |option|
@switches[option.switch_name] = option
option.aliases.each do |name|
@shorts[name] ||= option.switch_name
end
end
end
def remaining
@extra
end
def peek
return super unless @parsing_options
result = super
if result == OPTS_END
shift
@parsing_options = false
@stopped_parsing_after_extra_index ||= @extra.size
super
else
result
end
end
def shift
@is_treated_as_value = false
super
end
def unshift(arg, is_value: false)
@is_treated_as_value = is_value
super(arg)
end
def parse(args) # rubocop:disable Metrics/MethodLength
@pile = args.dup
@is_treated_as_value = false
@parsing_options = true
while peek
if parsing_options?
match, is_switch = current_is_switch?
shifted = shift
if is_switch
case shifted
when SHORT_SQ_RE
unshift($1.split("").map { |f| "-#{f}" })
next
when EQ_RE
unshift($2, is_value: true)
switch = $1
when SHORT_NUM
unshift($2)
switch = $1
when LONG_RE, SHORT_RE
switch = $1
end
switch = normalize_switch(switch)
option = switch_option(switch)
result = parse_peek(switch, option)
assign_result!(option, result)
elsif @stop_on_unknown
@parsing_options = false
@extra << shifted
@stopped_parsing_after_extra_index ||= @extra.size
@extra << shift while peek
break
elsif match
@extra << shifted
@extra << shift while peek && peek !~ /^-/
else
@extra << shifted
end
else
@extra << shift
end
end
check_requirement! unless @disable_required_check
check_exclusive!
check_at_least_one!
assigns = Thor::CoreExt::HashWithIndifferentAccess.new(@assigns)
assigns.freeze
assigns
end
def check_exclusive!
opts = @assigns.keys
# When option A and B are exclusive, if A and B are given at the same time,
# the difference of argument array size will decrease.
found = @exclusives.find{ |ex| (ex - opts).size < ex.size - 1 }
if found
names = names_to_switch_names(found & opts).map{|n| "'#{n}'"}
class_name = self.class.name.split("::").last.downcase
fail ExclusiveArgumentError, "Found exclusive #{class_name} #{names.join(", ")}"
end
end
def check_at_least_one!
opts = @assigns.keys
# When at least one is required of the options A and B,
# if the both options were not given, none? would be true.
found = @at_least_ones.find{ |one_reqs| one_reqs.none?{ |o| opts.include? o} }
if found
names = names_to_switch_names(found).map{|n| "'#{n}'"}
class_name = self.class.name.split("::").last.downcase
fail AtLeastOneRequiredArgumentError, "Not found at least one of required #{class_name} #{names.join(", ")}"
end
end
def check_unknown!
to_check = @stopped_parsing_after_extra_index ? @extra[0...@stopped_parsing_after_extra_index] : @extra
# an unknown option starts with - or -- and has no more --'s afterward.
unknown = to_check.select { |str| str =~ /^--?(?:(?!--).)*$/ }
raise UnknownArgumentError.new(@switches.keys, unknown) unless unknown.empty?
end
protected
# Option names changes to swith name or human name
def names_to_switch_names(names = [])
@switches.map do |_, o|
if names.include? o.name
o.respond_to?(:switch_name) ? o.switch_name : o.human_name
else
nil
end
end.compact
end
def assign_result!(option, result)
if option.repeatable && option.type == :hash
(@assigns[option.human_name] ||= {}).merge!(result)
elsif option.repeatable
(@assigns[option.human_name] ||= []) << result
else
@assigns[option.human_name] = result
end
end
# Check if the current value in peek is a registered switch.
#
# Two booleans are returned. The first is true if the current value
# starts with a hyphen; the second is true if it is a registered switch.
def current_is_switch?
return [false, false] if @is_treated_as_value
case peek
when LONG_RE, SHORT_RE, EQ_RE, SHORT_NUM
[true, switch?($1)]
when SHORT_SQ_RE
[true, $1.split("").any? { |f| switch?("-#{f}") }]
else
[false, false]
end
end
def current_is_switch_formatted?
return false if @is_treated_as_value
case peek
when LONG_RE, SHORT_RE, EQ_RE, SHORT_NUM, SHORT_SQ_RE
true
else
false
end
end
def current_is_value?
return true if @is_treated_as_value
peek && (!parsing_options? || super)
end
def switch?(arg)
!switch_option(normalize_switch(arg)).nil?
end
def switch_option(arg)
if match = no_or_skip?(arg) # rubocop:disable Lint/AssignmentInCondition
@switches[arg] || @switches["--#{match}"]
else
@switches[arg]
end
end
# Check if the given argument is actually a shortcut.
#
def normalize_switch(arg)
(@shorts[arg] || arg).tr("_", "-")
end
def parsing_options?
peek
@parsing_options
end
# Parse boolean values which can be given as --foo=true or --foo for true values, or
# --foo=false, --no-foo or --skip-foo for false values.
#
def parse_boolean(switch)
if current_is_value?
if ["true", "TRUE", "t", "T", true].include?(peek)
shift
true
elsif ["false", "FALSE", "f", "F", false].include?(peek)
shift
false
else
@switches.key?(switch) || !no_or_skip?(switch)
end
else
@switches.key?(switch) || !no_or_skip?(switch)
end
end
# Parse the value at the peek analyzing if it requires an input or not.
#
def parse_peek(switch, option)
if parsing_options? && (current_is_switch_formatted? || last?)
if option.boolean?
# No problem for boolean types
elsif no_or_skip?(switch)
return nil # User set value to nil
elsif option.string? && !option.required?
# Return the default if there is one, else the human name
return option.lazy_default || option.default || option.human_name
elsif option.lazy_default
return option.lazy_default
else
raise MalformattedArgumentError, "No value provided for option '#{switch}'"
end
end
@non_assigned_required.delete(option)
send(:"parse_#{option.type}", switch)
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/lib/thor/parser/arguments.rb | lib/thor/parser/arguments.rb | class Thor
class Arguments #:nodoc:
NUMERIC = /[-+]?(\d*\.\d+|\d+)/
# Receives an array of args and returns two arrays, one with arguments
# and one with switches.
#
def self.split(args)
arguments = []
args.each do |item|
break if item.is_a?(String) && item =~ /^-/
arguments << item
end
[arguments, args[Range.new(arguments.size, -1)]]
end
def self.parse(*args)
to_parse = args.pop
new(*args).parse(to_parse)
end
# Takes an array of Thor::Argument objects.
#
def initialize(arguments = [])
@assigns = {}
@non_assigned_required = []
@switches = arguments
arguments.each do |argument|
if !argument.default.nil?
@assigns[argument.human_name] = argument.default.dup
elsif argument.required?
@non_assigned_required << argument
end
end
end
def parse(args)
@pile = args.dup
@switches.each do |argument|
break unless peek
@non_assigned_required.delete(argument)
@assigns[argument.human_name] = send(:"parse_#{argument.type}", argument.human_name)
end
check_requirement!
@assigns
end
def remaining
@pile
end
private
def no_or_skip?(arg)
arg =~ /^--(no|skip)-([-\w]+)$/
$2
end
def last?
@pile.empty?
end
def peek
@pile.first
end
def shift
@pile.shift
end
def unshift(arg)
if arg.is_a?(Array)
@pile = arg + @pile
else
@pile.unshift(arg)
end
end
def current_is_value?
peek && peek.to_s !~ /^-{1,2}\S+/
end
# Runs through the argument array getting strings that contains ":" and
# mark it as a hash:
#
# [ "name:string", "age:integer" ]
#
# Becomes:
#
# { "name" => "string", "age" => "integer" }
#
def parse_hash(name)
return shift if peek.is_a?(Hash)
hash = {}
while current_is_value? && peek.include?(":")
key, value = shift.split(":", 2)
raise MalformattedArgumentError, "You can't specify '#{key}' more than once in option '#{name}'; got #{key}:#{hash[key]} and #{key}:#{value}" if hash.include? key
hash[key] = value
end
hash
end
# Runs through the argument array getting all strings until no string is
# found or a switch is found.
#
# ["a", "b", "c"]
#
# And returns it as an array:
#
# ["a", "b", "c"]
#
def parse_array(name)
return shift if peek.is_a?(Array)
array = []
while current_is_value?
value = shift
if !value.empty?
validate_enum_value!(name, value, "Expected all values of '%s' to be one of %s; got %s")
end
array << value
end
array
end
# Check if the peek is numeric format and return a Float or Integer.
# Check if the peek is included in enum if enum is provided.
# Otherwise raises an error.
#
def parse_numeric(name)
return shift if peek.is_a?(Numeric)
unless peek =~ NUMERIC && $& == peek
raise MalformattedArgumentError, "Expected numeric value for '#{name}'; got #{peek.inspect}"
end
value = $&.index(".") ? shift.to_f : shift.to_i
validate_enum_value!(name, value, "Expected '%s' to be one of %s; got %s")
value
end
# Parse string:
# for --string-arg, just return the current value in the pile
# for --no-string-arg, nil
# Check if the peek is included in enum if enum is provided. Otherwise raises an error.
#
def parse_string(name)
if no_or_skip?(name)
nil
else
value = shift
validate_enum_value!(name, value, "Expected '%s' to be one of %s; got %s")
value
end
end
# Raises an error if the switch is an enum and the values aren't included on it.
#
def validate_enum_value!(name, value, message)
return unless @switches.is_a?(Hash)
switch = @switches[name]
return unless switch
if switch.enum && !switch.enum.include?(value)
raise MalformattedArgumentError, message % [name, switch.enum_to_s, value]
end
end
# Raises an error if @non_assigned_required array is not empty.
#
def check_requirement!
return if @non_assigned_required.empty?
names = @non_assigned_required.map do |o|
o.respond_to?(:switch_name) ? o.switch_name : o.human_name
end.join("', '")
class_name = self.class.name.split("::").last.downcase
raise RequiredArgumentMissingError, "No value provided for required #{class_name} '#{names}'"
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/lib/thor/parser/option.rb | lib/thor/parser/option.rb | class Thor
class Option < Argument #:nodoc:
attr_reader :aliases, :group, :lazy_default, :hide, :repeatable
VALID_TYPES = [:boolean, :numeric, :hash, :array, :string]
def initialize(name, options = {})
@check_default_type = options[:check_default_type]
options[:required] = false unless options.key?(:required)
@repeatable = options.fetch(:repeatable, false)
super
@lazy_default = options[:lazy_default]
@group = options[:group].to_s.capitalize if options[:group]
@aliases = normalize_aliases(options[:aliases])
@hide = options[:hide]
end
# This parse quick options given as method_options. It makes several
# assumptions, but you can be more specific using the option method.
#
# parse :foo => "bar"
# #=> Option foo with default value bar
#
# parse [:foo, :baz] => "bar"
# #=> Option foo with default value bar and alias :baz
#
# parse :foo => :required
# #=> Required option foo without default value
#
# parse :foo => 2
# #=> Option foo with default value 2 and type numeric
#
# parse :foo => :numeric
# #=> Option foo without default value and type numeric
#
# parse :foo => true
# #=> Option foo with default value true and type boolean
#
# The valid types are :boolean, :numeric, :hash, :array and :string. If none
# is given a default type is assumed. This default type accepts arguments as
# string (--foo=value) or booleans (just --foo).
#
# By default all options are optional, unless :required is given.
#
def self.parse(key, value)
if key.is_a?(Array)
name, *aliases = key
else
name = key
aliases = []
end
name = name.to_s
default = value
type = case value
when Symbol
default = nil
if VALID_TYPES.include?(value)
value
elsif required = (value == :required) # rubocop:disable Lint/AssignmentInCondition
:string
end
when TrueClass, FalseClass
:boolean
when Numeric
:numeric
when Hash, Array, String
value.class.name.downcase.to_sym
end
new(name.to_s, required: required, type: type, default: default, aliases: aliases)
end
def switch_name
@switch_name ||= dasherized? ? name : dasherize(name)
end
def human_name
@human_name ||= dasherized? ? undasherize(name) : name
end
def usage(padding = 0)
sample = if banner && !banner.to_s.empty?
"#{switch_name}=#{banner}".dup
else
switch_name
end
sample = "[#{sample}]".dup unless required?
if boolean? && name != "force" && !name.match(/\A(no|skip)[\-_]/)
sample << ", [#{dasherize('no-' + human_name)}], [#{dasherize('skip-' + human_name)}]"
end
aliases_for_usage.ljust(padding) + sample
end
def aliases_for_usage
if aliases.empty?
""
else
"#{aliases.join(', ')}, "
end
end
def show_default?
case default
when TrueClass, FalseClass
true
else
super
end
end
VALID_TYPES.each do |type|
class_eval <<-RUBY, __FILE__, __LINE__ + 1
def #{type}?
self.type == #{type.inspect}
end
RUBY
end
protected
def validate!
raise ArgumentError, "An option cannot be boolean and required." if boolean? && required?
validate_default_type!
end
def validate_default_type!
default_type = case @default
when nil
return
when TrueClass, FalseClass
required? ? :string : :boolean
when Numeric
:numeric
when Symbol
:string
when Hash, Array, String
@default.class.name.downcase.to_sym
end
expected_type = (@repeatable && @type != :hash) ? :array : @type
if default_type != expected_type
err = "Expected #{expected_type} default value for '#{switch_name}'; got #{@default.inspect} (#{default_type})"
if @check_default_type
raise ArgumentError, err
elsif @check_default_type == nil
Thor.deprecation_warning "#{err}.\n" +
"This will be rejected in the future unless you explicitly pass the options `check_default_type: false`" +
" or call `allow_incompatible_default_type!` in your code"
end
end
end
def dasherized?
name.index("-") == 0
end
def undasherize(str)
str.sub(/^-{1,2}/, "")
end
def dasherize(str)
(str.length > 1 ? "--" : "-") + str.tr("_", "-")
end
private
def normalize_aliases(aliases)
Array(aliases).map { |short| short.to_s.sub(/^(?!\-)/, "-") }
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
rails/thor | https://github.com/rails/thor/blob/b2d98fea78fd993b936fc434a3ad722e73ad6bc5/lib/thor/parser/argument.rb | lib/thor/parser/argument.rb | class Thor
class Argument #:nodoc:
VALID_TYPES = [:numeric, :hash, :array, :string]
attr_reader :name, :description, :enum, :required, :type, :default, :banner
alias_method :human_name, :name
def initialize(name, options = {})
class_name = self.class.name.split("::").last
type = options[:type]
raise ArgumentError, "#{class_name} name can't be nil." if name.nil?
raise ArgumentError, "Type :#{type} is not valid for #{class_name.downcase}s." if type && !valid_type?(type)
@name = name.to_s
@description = options[:desc]
@required = options.key?(:required) ? options[:required] : true
@type = (type || :string).to_sym
@default = options[:default]
@banner = options[:banner] || default_banner
@enum = options[:enum]
validate! # Trigger specific validations
end
def print_default
if @type == :array and @default.is_a?(Array)
@default.map(&:dump).join(" ")
else
@default
end
end
def usage
required? ? banner : "[#{banner}]"
end
def required?
required
end
def show_default?
case default
when Array, String, Hash
!default.empty?
else
default
end
end
def enum_to_s
if enum.respond_to? :join
enum.join(", ")
else
"#{enum.first}..#{enum.last}"
end
end
protected
def validate!
raise ArgumentError, "An argument cannot be required and have default value." if required? && !default.nil?
raise ArgumentError, "An argument cannot have an enum other than an enumerable." if @enum && !@enum.is_a?(Enumerable)
end
def valid_type?(type)
self.class::VALID_TYPES.include?(type.to_sym)
end
def default_banner
case type
when :boolean
nil
when :string, :default
human_name.upcase
when :numeric
"N"
when :hash
"key:value"
when :array
"one two three"
end
end
end
end
| ruby | MIT | b2d98fea78fd993b936fc434a3ad722e73ad6bc5 | 2026-01-04T15:43:28.376179Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/spec/console.rb | spec/console.rb | Bundler.setup
require 'factory_bot'
require 'faker'
require 'ransack'
Dir[File.expand_path('../../spec/{helpers,support,factories}/*.rb', __FILE__)]
.each do |f|
require f
end
Faker::Config.random = Random.new(0)
Schema.create
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/spec/spec_helper.rb | spec/spec_helper.rb | require 'ransack'
require 'factory_bot'
require 'faker'
require 'action_controller'
require 'ransack/helpers'
require 'pry'
require 'simplecov'
require 'byebug'
require 'rspec'
SimpleCov.start
I18n.enforce_available_locales = false
Time.zone = 'Eastern Time (US & Canada)'
I18n.load_path += Dir[File.join(File.dirname(__FILE__), 'support', '*.yml')]
Dir[File.expand_path('../{helpers,support,factories}/*.rb', __FILE__)]
.each { |f| require f }
Faker::Config.random = Random.new(0)
RSpec.configure do |config|
config.alias_it_should_behave_like_to :it_has_behavior, 'has behavior'
config.include FactoryBot::Syntax::Methods
config.before(:suite) do
message = "Running Ransack specs with #{
ActiveRecord::Base.connection.adapter_name
}, Active Record #{::ActiveRecord::VERSION::STRING}, Arel #{Arel::VERSION
} and Ruby #{RUBY_VERSION}"
line = '=' * message.length
puts line, message, line
Schema.create
SubDB::Schema.create if defined?(SubDB)
end
config.include RansackHelper
config.include PolyamorousHelper
end
RSpec::Matchers.define :be_like do |expected|
match do |actual|
actual.gsub(/^\s+|\s+$/, '').gsub(/\s+/, ' ').strip ==
expected.gsub(/^\s+|\s+$/, '').gsub(/\s+/, ' ').strip
end
end
RSpec::Matchers.define :have_attribute_method do |expected|
match do |actual|
actual.attribute_method?(expected)
end
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/spec/support/schema.rb | spec/support/schema.rb | require 'active_record'
require 'activerecord-postgis-adapter'
case ENV['DB'].try(:downcase)
when 'mysql', 'mysql2'
# To test with MySQL: `DB=mysql bundle exec rake spec`
ActiveRecord::Base.establish_connection(
adapter: 'mysql2',
database: 'ransack',
username: ENV.fetch("MYSQL_USERNAME") { "root" },
password: ENV.fetch("MYSQL_PASSWORD") { "" },
encoding: 'utf8'
)
when 'pg', 'postgres', 'postgresql'
# To test with PostgreSQL: `DB=postgresql bundle exec rake spec`
ActiveRecord::Base.establish_connection(
adapter: 'postgresql',
database: 'ransack',
username: ENV.fetch("DATABASE_USERNAME") { "postgres" },
password: ENV.fetch("DATABASE_PASSWORD") { "" },
host: ENV.fetch("DATABASE_HOST") { "localhost" },
min_messages: 'warning'
)
when 'postgis'
# To test with PostGIS: `DB=postgis bundle exec rake spec`
ActiveRecord::Base.establish_connection(
adapter: 'postgis',
postgis_extension: 'postgis',
database: 'ransack',
username: ENV.fetch("DATABASE_USERNAME") { "postgres" },
password: ENV.fetch("DATABASE_PASSWORD") { "" },
host: ENV.fetch("DATABASE_HOST") { "localhost" },
min_messages: 'warning'
)
else
# Otherwise, assume SQLite3: `bundle exec rake spec`
ActiveRecord::Base.establish_connection(
adapter: 'sqlite3',
database: ':memory:'
)
end
# This is just a test app with no sensitive data, so we explicitly allowlist all
# attributes and associations for search. In general, end users should
# explicitly authorize each model, but this shows a way to configure the
# unrestricted default behavior of versions prior to Ransack 4.
#
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
def self.ransackable_attributes(auth_object = nil)
authorizable_ransackable_attributes
end
def self.ransackable_associations(auth_object = nil)
authorizable_ransackable_associations
end
end
class Person < ApplicationRecord
default_scope { order(id: :desc) }
belongs_to :parent, class_name: 'Person', foreign_key: :parent_id
has_many :children, class_name: 'Person', foreign_key: :parent_id
has_many :articles
has_many :story_articles
has_many :published_articles, ->{ where(published: true) },
class_name: "Article"
has_many :comments
has_many :authored_article_comments, through: :articles,
source: :comments, foreign_key: :person_id
has_many :notes, as: :notable
scope :restricted, lambda { where("restricted = 1") }
scope :active, lambda { where("active = 1") }
scope :over_age, lambda { |y| where(["age > ?", y]) }
scope :of_age, lambda { |of_age|
of_age ? where("age >= ?", 18) : where("age < ?", 18)
}
scope :sort_by_reverse_name_asc, lambda { order(Arel.sql("REVERSE(name) ASC")) }
scope :sort_by_reverse_name_desc, lambda { order("REVERSE(name) DESC") }
alias_attribute :full_name, :name
ransack_alias :term, :name_or_email
ransack_alias :daddy, :parent_name
ransacker :reversed_name, formatter: proc { |v| v.reverse } do |parent|
parent.table[:name]
end
ransacker :array_people_ids,
formatter: proc { |v| Person.first(2).map(&:id) } do |parent|
parent.table[:id]
end
ransacker :array_where_people_ids,
formatter: proc { |v| Person.where(id: v).map(&:id) } do |parent|
parent.table[:id]
end
ransacker :array_people_names,
formatter: proc { |v| Person.first(2).map { |p| p.id.to_s } } do |parent|
parent.table[:name]
end
ransacker :array_where_people_names,
formatter: proc { |v| Person.where(id: v).map { |p| p.id.to_s } } do |parent|
parent.table[:name]
end
ransacker :doubled_name do |parent|
Arel::Nodes::InfixOperation.new(
'||', parent.table[:name], parent.table[:name]
)
end
ransacker :sql_literal_id, type: :integer do
Arel.sql('people.id')
end
ransacker :name_case_insensitive, type: :string do
arel_table[:name].lower
end
ransacker :with_arguments, args: [:parent, :ransacker_args] do |parent, args|
min, max = args
query = <<-SQL
(SELECT MAX(articles.title)
FROM articles
WHERE articles.person_id = people.id
AND LENGTH(articles.body) BETWEEN #{min} AND #{max}
GROUP BY articles.person_id
)
SQL
.squish
Arel.sql(query)
end
ransacker :article_tags, formatter: proc { |id|
if Tag.exists?(id)
joins(articles: :tags)
.where(tags: { id: id })
.distinct
.select(:id).arel
end
} do |parent|
parent.table[:id]
end
def self.ransackable_attributes(auth_object = nil)
if auth_object == :admin
authorizable_ransackable_attributes - ['only_sort']
else
authorizable_ransackable_attributes - ['only_sort', 'only_admin']
end
end
def self.ransortable_attributes(auth_object = nil)
if auth_object == :admin
column_names + _ransackers.keys - ['only_search']
else
column_names + _ransackers.keys - ['only_search', 'only_admin']
end
end
end
class Musician < Person
end
class Article < ApplicationRecord
belongs_to :person
has_many :comments
has_and_belongs_to_many :tags
has_many :notes, as: :notable
has_many :recent_notes, as: :notable
alias_attribute :content, :body
default_scope { where("'default_scope' = 'default_scope'") }
scope :latest_comment_cont, lambda { |msg|
join = <<-SQL
(LEFT OUTER JOIN (
SELECT
comments.*,
row_number() OVER (PARTITION BY comments.article_id ORDER BY comments.id DESC) AS rownum
FROM comments
) AS latest_comment
ON latest_comment.article_id = article.id
AND latest_comment.rownum = 1
)
SQL
.squish
joins(join).where("latest_comment.body ILIKE ?", "%#{msg}%")
}
ransacker :title_type, formatter: lambda { |tuples|
title, type = JSON.parse(tuples)
Arel::Nodes::Grouping.new(
[
Arel::Nodes.build_quoted(title),
Arel::Nodes.build_quoted(type)
]
)
} do |_parent|
articles = Article.arel_table
Arel::Nodes::Grouping.new(
%i[title type].map do |field|
Arel::Nodes::NamedFunction.new(
'COALESCE',
[
Arel::Nodes::NamedFunction.new('TRIM', [articles[field]]),
Arel::Nodes.build_quoted('')
]
)
end
)
end
end
class StoryArticle < Article
end
class Recommendation < ApplicationRecord
belongs_to :person
belongs_to :target_person, class_name: 'Person'
belongs_to :article
end
module Namespace
class Article < ::Article
end
end
module Namespace
class Article < ::Article
end
end
class Comment < ApplicationRecord
belongs_to :article
belongs_to :person
has_and_belongs_to_many :tags
default_scope { where(disabled: false) }
end
class Tag < ApplicationRecord
has_and_belongs_to_many :articles
has_and_belongs_to_many :comments
end
class Note < ApplicationRecord
belongs_to :notable, polymorphic: true
end
class RecentNote < ApplicationRecord
DEFAULT_NOTABLE_ID = 1
self.table_name = "notes"
default_scope { where(notable_id: DEFAULT_NOTABLE_ID) }
belongs_to :notable, polymorphic: true
end
class Account < ApplicationRecord
belongs_to :agent_account, class_name: "Account"
belongs_to :trade_account, class_name: "Account"
end
class Address < ApplicationRecord
has_one :organization
end
class Organization < ApplicationRecord
belongs_to :address
has_many :employees
end
class Employee < ApplicationRecord
belongs_to :organization
has_one :address, through: :organization
end
module Schema
def self.create
ActiveRecord::Migration.verbose = false
ActiveRecord::Schema.define do
create_table :people, force: true do |t|
t.integer :parent_id
t.string :name
t.string :email
t.string :only_search
t.string :only_sort
t.string :only_admin
t.string :new_start
t.string :stop_end
t.integer :salary
t.date :life_start
t.boolean :awesome, default: false
t.boolean :terms_and_conditions, default: false
t.boolean :true_or_false, default: true
t.timestamps null: false
end
create_table :articles, force: true do |t|
t.integer :person_id
t.string :title
t.text :subject_header
t.text :body
t.string :type
t.boolean :published, default: true
end
create_table :comments, force: true do |t|
t.integer :article_id
t.integer :person_id
t.text :body
t.boolean :disabled, default: false
end
create_table :tags, force: true do |t|
t.string :name
end
create_table :articles_tags, force: true, id: false do |t|
t.integer :article_id
t.integer :tag_id
end
create_table :comments_tags, force: true, id: false do |t|
t.integer :comment_id
t.integer :tag_id
end
create_table :notes, force: true do |t|
t.integer :notable_id
t.string :notable_type
t.string :note
end
create_table :recommendations, force: true do |t|
t.integer :person_id
t.integer :target_person_id
t.integer :article_id
end
create_table :accounts, force: true do |t|
t.belongs_to :agent_account
t.belongs_to :trade_account
end
create_table :addresses, force: true do |t|
t.string :city
end
create_table :organizations, force: true do |t|
t.string :name
t.integer :address_id
end
create_table :employees, force: true do |t|
t.string :name
t.integer :organization_id
end
end
10.times do
person = FactoryBot.create(:person)
FactoryBot.create(:note, :for_person, notable: person)
3.times do
article = FactoryBot.create(:article, person: person)
3.times do
article.tags = [FactoryBot.create(:tag), FactoryBot.create(:tag), FactoryBot.create(:tag)]
end
FactoryBot.create(:note, :for_article, notable: article)
10.times do
FactoryBot.create(:comment, article: article, person: person)
end
end
end
FactoryBot.create(:comment,
body: 'First post!',
article: FactoryBot.create(:article, title: 'Hello, world!')
)
end
end
module SubDB
class Base < ApplicationRecord
self.abstract_class = true
establish_connection(
adapter: 'sqlite3',
database: ':memory:'
)
end
class OperationHistory < Base
end
module Schema
def self.create
s = ::ActiveRecord::Schema.new
s.instance_variable_set(:@connection, SubDB::Base.connection)
s.verbose = false
s.define({}) do
create_table :operation_histories, force: true do |t|
t.string :operation_type
t.integer :people_id
end
end
end
end
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/spec/helpers/ransack_helper.rb | spec/helpers/ransack_helper.rb | module RansackHelper
def quote_table_name(table)
ActiveRecord::Base.connection.quote_table_name(table)
end
def quote_column_name(column)
ActiveRecord::Base.connection.quote_column_name(column)
end
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/spec/helpers/polyamorous_helper.rb | spec/helpers/polyamorous_helper.rb | module PolyamorousHelper
def new_join_association(reflection, children, klass)
Polyamorous::JoinAssociation.new reflection, children, klass
end
def new_join_dependency(klass, associations = {})
Polyamorous::JoinDependency.new klass, klass.arel_table, associations, Polyamorous::InnerJoin
end
def new_join(name, type = Polyamorous::InnerJoin, klass = nil)
Polyamorous::Join.new name, type, klass
end
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/spec/factories/notes.rb | spec/factories/notes.rb | FactoryBot.define do
factory :note do
note { Faker::Lorem.words(number: 7).join(' ') }
trait :for_person do
association :notable, factory: :person
end
trait :for_article do
association :notable, factory: :article
end
end
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/spec/factories/comments.rb | spec/factories/comments.rb | FactoryBot.define do
factory :comment do
association :article
association :person
body { Faker::Lorem.paragraph }
end
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/spec/factories/articles.rb | spec/factories/articles.rb | FactoryBot.define do
factory :article do
association :person
title { Faker::Lorem.sentence }
body { Faker::Lorem.paragraph }
end
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/spec/factories/people.rb | spec/factories/people.rb | FactoryBot.define do
factory :person do
name { Faker::Name.name }
email { "test@example.com" }
sequence(:salary) { |n| 30000 + (n * 1000) }
only_sort { Faker::Lorem.words(number: 3).join(' ') }
only_search { Faker::Lorem.words(number: 3).join(' ') }
only_admin { Faker::Lorem.words(number: 3).join(' ') }
end
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/spec/factories/tags.rb | spec/factories/tags.rb | FactoryBot.define do
factory :tag do
name { Faker::Lorem.words(number: 3).join(' ') }
end
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/spec/ransack/search_spec.rb | spec/ransack/search_spec.rb | require 'spec_helper'
module Ransack
describe Search do
describe '#initialize' do
it 'removes empty conditions before building' do
expect_any_instance_of(Search).to receive(:build).with({})
Search.new(Person, name_eq: '')
end
it 'keeps conditions with a false value before building' do
expect_any_instance_of(Search).to receive(:build)
.with({ 'name_eq' => false })
Search.new(Person, name_eq: false)
end
it 'keeps conditions with a value before building' do
expect_any_instance_of(Search).to receive(:build)
.with({ 'name_eq' => 'foobar' })
Search.new(Person, name_eq: 'foobar')
end
context 'whitespace stripping' do
context 'when whitespace_strip option is true' do
before do
Ransack.configure { |c| c.strip_whitespace = true }
end
it 'strips leading & trailing whitespace before building' do
expect_any_instance_of(Search).to receive(:build)
.with({ 'name_eq' => 'foobar' })
Search.new(Person, name_eq: ' foobar ')
end
end
context 'when whitespace_strip option is false' do
before do
Ransack.configure { |c| c.strip_whitespace = false }
end
it 'doesn\'t strip leading & trailing whitespace before building' do
expect_any_instance_of(Search).to receive(:build)
.with({ 'name_eq' => ' foobar ' })
Search.new(Person, name_eq: ' foobar ')
end
end
it 'strips leading & trailing whitespace when strip_whitespace search parameter is true' do
expect_any_instance_of(Search).to receive(:build)
.with({ 'name_eq' => 'foobar' })
Search.new(Person, { name_eq: ' foobar ' }, { strip_whitespace: true })
end
it 'doesn\'t strip leading & trailing whitespace when strip_whitespace search parameter is false' do
expect_any_instance_of(Search).to receive(:build)
.with({ 'name_eq' => ' foobar ' })
Search.new(Person, { name_eq: ' foobar ' }, { strip_whitespace: false })
end
end
it 'removes empty suffixed conditions before building' do
expect_any_instance_of(Search).to receive(:build).with({})
Search.new(Person, name_eq_any: [''])
end
it 'keeps suffixed conditions with a false value before building' do
expect_any_instance_of(Search).to receive(:build)
.with({ 'name_eq_any' => [false] })
Search.new(Person, name_eq_any: [false])
end
it 'keeps suffixed conditions with a value before building' do
expect_any_instance_of(Search).to receive(:build)
.with({ 'name_eq_any' => ['foobar'] })
Search.new(Person, name_eq_any: ['foobar'])
end
it 'does not raise exception for string :params argument' do
expect { Search.new(Person, '') }.not_to raise_error
end
it 'accepts a context option' do
shared_context = Context.for(Person)
s1 = Search.new(Person, { name_eq: 'A' }, context: shared_context)
s2 = Search.new(Person, { name_eq: 'B' }, context: shared_context)
expect(s1.context).to be s2.context
end
end
describe '#build' do
it 'creates conditions for top-level attributes' do
s = Search.new(Person, name_eq: 'Ernie')
condition = s.base[:name_eq]
expect(condition).to be_a Nodes::Condition
expect(condition.predicate.name).to eq 'eq'
expect(condition.attributes.first.name).to eq 'name'
expect(condition.value).to eq 'Ernie'
end
it 'creates conditions for association attributes' do
s = Search.new(Person, children_name_eq: 'Ernie')
condition = s.base[:children_name_eq]
expect(condition).to be_a Nodes::Condition
expect(condition.predicate.name).to eq 'eq'
expect(condition.attributes.first.name).to eq 'children_name'
expect(condition.value).to eq 'Ernie'
end
it 'creates conditions for polymorphic belongs_to association attributes' do
s = Search.new(Note, notable_of_Person_type_name_eq: 'Ernie')
condition = s.base[:notable_of_Person_type_name_eq]
expect(condition).to be_a Nodes::Condition
expect(condition.predicate.name).to eq 'eq'
expect(condition.attributes.first.name)
.to eq 'notable_of_Person_type_name'
expect(condition.value).to eq 'Ernie'
end
it 'creates conditions for multiple polymorphic belongs_to association
attributes' do
s = Search.new(Note,
notable_of_Person_type_name_or_notable_of_Article_type_title_eq: 'Ernie')
condition = s.
base[:notable_of_Person_type_name_or_notable_of_Article_type_title_eq]
expect(condition).to be_a Nodes::Condition
expect(condition.predicate.name).to eq 'eq'
expect(condition.attributes.first.name)
.to eq 'notable_of_Person_type_name'
expect(condition.attributes.last.name)
.to eq 'notable_of_Article_type_title'
expect(condition.value).to eq 'Ernie'
end
it 'creates conditions for aliased attributes',
if: Ransack::SUPPORTS_ATTRIBUTE_ALIAS do
s = Search.new(Person, full_name_eq: 'Ernie')
condition = s.base[:full_name_eq]
expect(condition).to be_a Nodes::Condition
expect(condition.predicate.name).to eq 'eq'
expect(condition.attributes.first.name).to eq 'full_name'
expect(condition.value).to eq 'Ernie'
end
it 'preserves default scope and conditions for associations' do
s = Search.new(Person, published_articles_title_eq: 'Test')
expect(s.result.to_sql).to include 'default_scope'
expect(s.result.to_sql).to include 'published'
end
# The failure/oversight in Ransack::Nodes::Condition#arel_predicate or deeper is beyond my understanding of the structures
it 'preserves (inverts) default scope and conditions for negative subqueries' do
# the positive case (published_articles_title_eq) is
# SELECT "people".* FROM "people"
# LEFT OUTER JOIN "articles" ON "articles"."person_id" = "people"."id"
# AND "articles"."published" = 't'
# AND ('default_scope' = 'default_scope')
# WHERE "articles"."title" = 'Test' ORDER BY "people"."id" DESC
#
# negative case was
# SELECT "people".* FROM "people" WHERE "people"."id" NOT IN (
# SELECT "articles"."person_id" FROM "articles"
# WHERE "articles"."person_id" = "people"."id"
# AND NOT ("articles"."title" != 'Test')
# ) ORDER BY "people"."id" DESC
#
# Should have been like
# SELECT "people".* FROM "people" WHERE "people"."id" NOT IN (
# SELECT "articles"."person_id" FROM "articles"
# WHERE "articles"."person_id" = "people"."id"
# AND "articles"."title" = 'Test' AND "articles"."published" = 't' AND ('default_scope' = 'default_scope')
# ) ORDER BY "people"."id" DESC
#
# With tenanting (eg default_scope with column reference), NOT IN should be like
# SELECT "people".* FROM "people" WHERE "people"."tenant_id" = 'tenant_id' AND "people"."id" NOT IN (
# SELECT "articles"."person_id" FROM "articles"
# WHERE "articles"."person_id" = "people"."id"
# AND "articles"."tenant_id" = 'tenant_id'
# AND "articles"."title" = 'Test' AND "articles"."published" = 't' AND ('default_scope' = 'default_scope')
# ) ORDER BY "people"."id" DESC
s = Search.new(Person, published_articles_title_not_eq: 'Test')
expect(s.result.to_sql).to include 'default_scope'
expect(s.result.to_sql).to include 'published'
end
it 'discards empty conditions' do
s = Search.new(Person, children_name_eq: '')
condition = s.base[:children_name_eq]
expect(condition).to be_nil
end
it 'accepts base grouping condition as an option' do
expect(Nodes::Grouping).to receive(:new).with(kind_of(Context), 'or')
Search.new(Person, {}, { grouping: 'or' })
end
it 'accepts arrays of groupings' do
s = Search.new(Person,
g: [
{ m: 'or', name_eq: 'Ernie', children_name_eq: 'Ernie' },
{ m: 'or', name_eq: 'Bert', children_name_eq: 'Bert' },
]
)
ors = s.groupings
expect(ors.size).to eq(2)
or1, or2 = ors
expect(or1).to be_a Nodes::Grouping
expect(or1.combinator).to eq 'or'
expect(or2).to be_a Nodes::Grouping
expect(or2.combinator).to eq 'or'
end
it 'accepts attributes hashes for groupings' do
s = Search.new(Person,
g: {
'0' => { m: 'or', name_eq: 'Ernie', children_name_eq: 'Ernie' },
'1' => { m: 'or', name_eq: 'Bert', children_name_eq: 'Bert' },
}
)
ors = s.groupings
expect(ors.size).to eq(2)
or1, or2 = ors
expect(or1).to be_a Nodes::Grouping
expect(or1.combinator).to eq 'or'
expect(or2).to be_a Nodes::Grouping
expect(or2.combinator).to eq 'or'
end
it 'accepts attributes hashes for conditions' do
s = Search.new(Person,
c: {
'0' => { a: ['name'], p: 'eq', v: ['Ernie'] },
'1' => {
a: ['children_name', 'parent_name'],
p: 'eq', v: ['Ernie'], m: 'or'
}
}
)
conditions = s.base.conditions
expect(conditions.size).to eq(2)
expect(conditions.map { |c| c.class })
.to eq [Nodes::Condition, Nodes::Condition]
end
it 'creates conditions for custom predicates that take arrays' do
Ransack.configure do |config|
config.add_predicate 'ary_pred', wants_array: true
end
s = Search.new(Person, name_ary_pred: ['Ernie', 'Bert'])
condition = s.base[:name_ary_pred]
expect(condition).to be_a Nodes::Condition
expect(condition.predicate.name).to eq 'ary_pred'
expect(condition.attributes.first.name).to eq 'name'
expect(condition.value).to eq ['Ernie', 'Bert']
end
it 'does not evaluate the query on #inspect' do
s = Search.new(Person, children_id_in: [1, 2, 3])
expect(s.inspect).not_to match /ActiveRecord/
end
context 'with an invalid condition' do
subject { Search.new(Person, unknown_attr_eq: 'Ernie') }
context 'when ignore_unknown_conditions configuration option is false' do
before do
Ransack.configure { |c| c.ignore_unknown_conditions = false }
end
specify { expect { subject }.to raise_error ArgumentError }
specify { expect { subject }.to raise_error InvalidSearchError }
end
context 'when ignore_unknown_conditions configuration option is true' do
before do
Ransack.configure { |c| c.ignore_unknown_conditions = true }
end
specify { expect { subject }.not_to raise_error }
end
subject(:with_ignore_unknown_conditions_false) {
Search.new(Person,
{ unknown_attr_eq: 'Ernie' },
{ ignore_unknown_conditions: false }
)
}
subject(:with_ignore_unknown_conditions_true) {
Search.new(Person,
{ unknown_attr_eq: 'Ernie' },
{ ignore_unknown_conditions: true }
)
}
context 'when ignore_unknown_conditions search parameter is absent' do
specify { expect { subject }.not_to raise_error }
end
context 'when ignore_unknown_conditions search parameter is false' do
specify { expect { with_ignore_unknown_conditions_false }.to raise_error ArgumentError }
specify { expect { with_ignore_unknown_conditions_false }.to raise_error InvalidSearchError }
end
context 'when ignore_unknown_conditions search parameter is true' do
specify { expect { with_ignore_unknown_conditions_true }.not_to raise_error }
end
end
it 'does not modify the parameters' do
params = { name_eq: '' }
expect { Search.new(Person, params) }.not_to change { params }
end
context 'with empty search parameters' do
it 'handles completely empty parameters' do
search = Search.new(Person, {})
expect(search.result.to_sql).not_to match(/WHERE/)
end
it 'handles nil parameters' do
search = Search.new(Person, nil)
expect(search.result.to_sql).not_to match(/WHERE/)
end
end
context 'with whitespace-only values' do
before do
Ransack.configure { |c| c.strip_whitespace = true }
end
it 'removes whitespace-only values' do
expect_any_instance_of(Search).to receive(:build).with({})
Search.new(Person, name_eq: ' ')
end
it 'keeps values with content after whitespace stripping' do
expect_any_instance_of(Search).to receive(:build).with({ 'name_eq' => 'test' })
Search.new(Person, name_eq: ' test ')
end
end
context 'with special characters in values' do
it 'handles values with special regex characters' do
search = Search.new(Person, name_cont: 'test[(){}^$|?*+.\\')
expect { search.result }.not_to raise_error
end
it 'handles values with SQL injection attempts' do
search = Search.new(Person, name_cont: "'; DROP TABLE people; --")
expect { search.result }.not_to raise_error
end
end
context "ransackable_scope" do
around(:each) do |example|
Person.define_singleton_method(:name_eq) do |name|
self.where(name: name)
end
begin
example.run
ensure
Person.singleton_class.undef_method :name_eq
end
end
it "is prioritized over base predicates" do
allow(Person).to receive(:ransackable_scopes)
.and_return(Person.ransackable_scopes + [:name_eq])
s = Search.new(Person, name_eq: "Johny")
expect(s.instance_variable_get(:@scope_args)["name_eq"]).to eq("Johny")
expect(s.base[:name_eq]).to be_nil
end
end
context "ransackable_scope with array arguments" do
around(:each) do |example|
Person.define_singleton_method(:domestic) do |countries|
self.where(name: countries)
end
Person.define_singleton_method(:flexible_scope) do |*args|
self.where(id: args)
end
Person.define_singleton_method(:two_param_scope) do |param1, param2|
self.where(name: param1, id: param2)
end
begin
example.run
ensure
Person.singleton_class.undef_method :domestic
Person.singleton_class.undef_method :flexible_scope
Person.singleton_class.undef_method :two_param_scope
end
end
it "handles scopes that take arrays as single arguments (arity 1)" do
allow(Person).to receive(:ransackable_scopes)
.and_return(Person.ransackable_scopes + [:domestic])
# This should not raise ArgumentError
expect {
s = Search.new(Person, domestic: ['US', 'JP'])
s.result # This triggers the actual scope call
}.not_to raise_error
s = Search.new(Person, domestic: ['US', 'JP'])
expect(s.instance_variable_get(:@scope_args)["domestic"]).to eq("US")
end
it "handles scopes with flexible arity (negative arity)" do
allow(Person).to receive(:ransackable_scopes)
.and_return(Person.ransackable_scopes + [:flexible_scope])
expect {
s = Search.new(Person, flexible_scope: ['US', 'JP'])
s.result
}.not_to raise_error
end
it "handles scopes with arity > 1" do
allow(Person).to receive(:ransackable_scopes)
.and_return(Person.ransackable_scopes + [:two_param_scope])
expect {
s = Search.new(Person, two_param_scope: ['param1', 'param2'])
s.result
}.not_to raise_error
end
it "still supports the workaround with nested arrays" do
allow(Person).to receive(:ransackable_scopes)
.and_return(Person.ransackable_scopes + [:domestic])
# The workaround from the issue should still work
expect {
s = Search.new(Person, domestic: [['US', 'JP']])
s.result
}.not_to raise_error
end
end
end
describe '#result' do
let(:people_name_field) {
"#{quote_table_name("people")}.#{quote_column_name("name")}"
}
let(:children_people_name_field) {
"#{quote_table_name("children_people")}.#{quote_column_name("name")}"
}
let(:notable_type_field) {
"#{quote_table_name("notes")}.#{quote_column_name("notable_type")}"
}
it 'evaluates conditions contextually' do
s = Search.new(Person, children_name_eq: 'Ernie')
expect(s.result).to be_an ActiveRecord::Relation
expect(s.result.to_sql).to match /#{
children_people_name_field} = 'Ernie'/
end
it 'use appropriate table alias' do
s = Search.new(Person, {
name_eq: "person_name_query",
articles_title_eq: "person_article_title_query",
parent_name_eq: "parent_name_query",
parent_articles_title_eq: 'parents_article_title_query'
}).result
real_query = remove_quotes_and_backticks(s.to_sql)
expect(real_query)
.to match(%r{LEFT OUTER JOIN articles ON (\('default_scope' = 'default_scope'\) AND )?articles.person_id = people.id})
expect(real_query)
.to match(%r{LEFT OUTER JOIN articles articles_people ON (\('default_scope' = 'default_scope'\) AND )?articles_people.person_id = parents_people.id})
expect(real_query)
.to include "people.name = 'person_name_query'"
expect(real_query)
.to include "articles.title = 'person_article_title_query'"
expect(real_query)
.to include "parents_people.name = 'parent_name_query'"
expect(real_query)
.to include "articles_people.title = 'parents_article_title_query'"
end
it 'evaluates conditions for multiple `belongs_to` associations to the same table contextually' do
s = Search.new(
Recommendation,
person_name_eq: 'Ernie',
target_person_parent_name_eq: 'Test'
).result
expect(s).to be_an ActiveRecord::Relation
real_query = remove_quotes_and_backticks(s.to_sql)
expected_query = <<-SQL
SELECT recommendations.* FROM recommendations
LEFT OUTER JOIN people ON people.id = recommendations.person_id
LEFT OUTER JOIN people target_people_recommendations
ON target_people_recommendations.id = recommendations.target_person_id
LEFT OUTER JOIN people parents_people
ON parents_people.id = target_people_recommendations.parent_id
WHERE (people.name = 'Ernie' AND parents_people.name = 'Test')
SQL
.squish
expect(real_query).to eq expected_query
end
it 'evaluates compound conditions contextually' do
s = Search.new(Person, children_name_or_name_eq: 'Ernie').result
expect(s).to be_an ActiveRecord::Relation
expect(s.to_sql).to match /#{children_people_name_field
} = 'Ernie' OR #{people_name_field} = 'Ernie'/
end
it 'evaluates polymorphic belongs_to association conditions contextually' do
s = Search.new(Note, notable_of_Person_type_name_eq: 'Ernie').result
expect(s).to be_an ActiveRecord::Relation
expect(s.to_sql).to match /#{people_name_field} = 'Ernie'/
expect(s.to_sql).to match /#{notable_type_field} = 'Person'/
end
it 'evaluates nested conditions' do
s = Search.new(Person, children_name_eq: 'Ernie',
g: [
{ m: 'or', name_eq: 'Ernie', children_children_name_eq: 'Ernie' }
]
).result
expect(s).to be_an ActiveRecord::Relation
first, last = s.to_sql.split(/ AND /)
expect(first).to match /#{children_people_name_field} = 'Ernie'/
expect(last).to match /#{
people_name_field} = 'Ernie' OR #{
quote_table_name("children_people_2")}.#{
quote_column_name("name")} = 'Ernie'/
end
it 'evaluates arrays of groupings' do
s = Search.new(Person,
g: [
{ m: 'or', name_eq: 'Ernie', children_name_eq: 'Ernie' },
{ m: 'or', name_eq: 'Bert', children_name_eq: 'Bert' }
]
).result
expect(s).to be_an ActiveRecord::Relation
first, last = s.to_sql.split(/ AND /)
expect(first).to match /#{people_name_field} = 'Ernie' OR #{
children_people_name_field} = 'Ernie'/
expect(last).to match /#{people_name_field} = 'Bert' OR #{
children_people_name_field} = 'Bert'/
end
it 'returns distinct records when passed distinct: true' do
s = Search.new(Person,
g: [
{ m: 'or', comments_body_cont: 'e', articles_comments_body_cont: 'e' }
]
)
all_or_load, uniq_or_distinct = :load, :distinct
expect(s.result.send(all_or_load).size)
.to eq(8998)
expect(s.result(distinct: true).size)
.to eq(10)
expect(s.result.send(all_or_load).send(uniq_or_distinct))
.to eq s.result(distinct: true).send(all_or_load)
end
it 'evaluates joins with belongs_to join' do
s = Person.joins(:parent).ransack(parent_name_eq: 'Ernie').result(distinct: true)
expect(s).to be_an ActiveRecord::Relation
end
private
def remove_quotes_and_backticks(str)
str.gsub(/["`]/, '')
end
end
describe '#sorts=' do
before do
@s = Search.new(Person)
end
it 'doesn\'t creates sorts' do
@s.sorts = ''
expect(@s.sorts.size).to eq(0)
end
it 'creates sorts based on a single attribute/direction' do
@s.sorts = 'id desc'
expect(@s.sorts.size).to eq(1)
sort = @s.sorts.first
expect(sort).to be_a Nodes::Sort
expect(sort.name).to eq 'id'
expect(sort.dir).to eq 'desc'
end
it 'creates sorts based on a single attribute and uppercase direction' do
@s.sorts = 'id DESC'
expect(@s.sorts.size).to eq(1)
sort = @s.sorts.first
expect(sort).to be_a Nodes::Sort
expect(sort.name).to eq 'id'
expect(sort.dir).to eq 'desc'
end
it 'creates sorts based on a single attribute and without direction' do
@s.sorts = 'id'
expect(@s.sorts.size).to eq(1)
sort = @s.sorts.first
expect(sort).to be_a Nodes::Sort
expect(sort.name).to eq 'id'
expect(sort.dir).to eq 'asc'
end
it 'creates sorts based on a single alias/direction' do
@s.sorts = 'daddy desc'
expect(@s.sorts.size).to eq(1)
sort = @s.sorts.first
expect(sort).to be_a Nodes::Sort
expect(sort.name).to eq 'parent_name'
expect(sort.dir).to eq 'desc'
end
it 'creates sorts based on a single alias and uppercase direction' do
@s.sorts = 'daddy DESC'
expect(@s.sorts.size).to eq(1)
sort = @s.sorts.first
expect(sort).to be_a Nodes::Sort
expect(sort.name).to eq 'parent_name'
expect(sort.dir).to eq 'desc'
end
it 'creates sorts based on a single alias and without direction' do
@s.sorts = 'daddy'
expect(@s.sorts.size).to eq(1)
sort = @s.sorts.first
expect(sort).to be_a Nodes::Sort
expect(sort.name).to eq 'parent_name'
expect(sort.dir).to eq 'asc'
end
it 'creates sorts based on attributes, alias and directions in array format' do
@s.sorts = ['id desc', { name: 'daddy', dir: 'asc' }]
expect(@s.sorts.size).to eq(2)
sort1, sort2 = @s.sorts
expect(sort1).to be_a Nodes::Sort
expect(sort1.name).to eq 'id'
expect(sort1.dir).to eq 'desc'
expect(sort2).to be_a Nodes::Sort
expect(sort2.name).to eq 'parent_name'
expect(sort2.dir).to eq 'asc'
end
it 'creates sorts based on attributes, alias and uppercase directions in array format' do
@s.sorts = ['id DESC', { name: 'daddy', dir: 'ASC' }]
expect(@s.sorts.size).to eq(2)
sort1, sort2 = @s.sorts
expect(sort1).to be_a Nodes::Sort
expect(sort1.name).to eq 'id'
expect(sort1.dir).to eq 'desc'
expect(sort2).to be_a Nodes::Sort
expect(sort2.name).to eq 'parent_name'
expect(sort2.dir).to eq 'asc'
end
it 'creates sorts based on attributes, alias and different directions
in array format' do
@s.sorts = ['id DESC', { name: 'daddy', dir: nil }]
expect(@s.sorts.size).to eq(2)
sort1, sort2 = @s.sorts
expect(sort1).to be_a Nodes::Sort
expect(sort1.name).to eq 'id'
expect(sort1.dir).to eq 'desc'
expect(sort2).to be_a Nodes::Sort
expect(sort2.name).to eq 'parent_name'
expect(sort2.dir).to eq 'asc'
end
it 'creates sorts based on attributes, alias and directions in hash format' do
@s.sorts = {
'0' => { name: 'id', dir: 'desc' },
'1' => { name: 'daddy', dir: 'asc' }
}
expect(@s.sorts.size).to eq(2)
expect(@s.sorts).to be_all { |s| Nodes::Sort === s }
id_sort = @s.sorts.detect { |s| s.name == 'id' }
daddy_sort = @s.sorts.detect { |s| s.name == 'parent_name' }
expect(id_sort.dir).to eq 'desc'
expect(daddy_sort.dir).to eq 'asc'
end
it 'creates sorts based on attributes, alias and uppercase directions
in hash format' do
@s.sorts = {
'0' => { name: 'id', dir: 'DESC' },
'1' => { name: 'daddy', dir: 'ASC' }
}
expect(@s.sorts.size).to eq(2)
expect(@s.sorts).to be_all { |s| Nodes::Sort === s }
id_sort = @s.sorts.detect { |s| s.name == 'id' }
daddy_sort = @s.sorts.detect { |s| s.name == 'parent_name' }
expect(id_sort.dir).to eq 'desc'
expect(daddy_sort.dir).to eq 'asc'
end
it 'creates sorts based on attributes, alias and different directions
in hash format' do
@s.sorts = {
'0' => { name: 'id', dir: 'DESC' },
'1' => { name: 'daddy', dir: nil }
}
expect(@s.sorts.size).to eq(2)
expect(@s.sorts).to be_all { |s| Nodes::Sort === s }
id_sort = @s.sorts.detect { |s| s.name == 'id' }
daddy_sort = @s.sorts.detect { |s| s.name == 'parent_name' }
expect(id_sort.dir).to eq 'desc'
expect(daddy_sort.dir).to eq 'asc'
end
it 'overrides existing sort' do
@s.sorts = 'id asc'
expect(@s.result.first.id).to eq 1
end
it 'raises ArgumentError when an invalid argument is sent' do
expect do
@s.sorts = 1234
end.to raise_error(ArgumentError, "Invalid argument (Integer) supplied to sorts=")
end
it 'raises InvalidSearchError when an invalid argument is sent' do
expect do
@s.sorts = 1234
end.to raise_error(Ransack::InvalidSearchError, "Invalid argument (Integer) supplied to sorts=")
end
it "PG's sort option", if: ::ActiveRecord::Base.connection.adapter_name == "PostgreSQL" do
default = Ransack.options.clone
s = Search.new(Person, s: 'name asc')
expect(s.result.to_sql).to eq "SELECT \"people\".* FROM \"people\" ORDER BY \"people\".\"name\" ASC"
Ransack.configure { |c| c.postgres_fields_sort_option = :nulls_first }
s = Search.new(Person, s: 'name asc')
expect(s.result.to_sql).to eq "SELECT \"people\".* FROM \"people\" ORDER BY \"people\".\"name\" ASC NULLS FIRST"
s = Search.new(Person, s: 'name desc')
expect(s.result.to_sql).to eq "SELECT \"people\".* FROM \"people\" ORDER BY \"people\".\"name\" DESC NULLS LAST"
Ransack.configure { |c| c.postgres_fields_sort_option = :nulls_last }
s = Search.new(Person, s: 'name asc')
expect(s.result.to_sql).to eq "SELECT \"people\".* FROM \"people\" ORDER BY \"people\".\"name\" ASC NULLS LAST"
s = Search.new(Person, s: 'name desc')
expect(s.result.to_sql).to eq "SELECT \"people\".* FROM \"people\" ORDER BY \"people\".\"name\" DESC NULLS FIRST"
Ransack.options = default
end
it "PG's sort option with double name", if: ::ActiveRecord::Base.connection.adapter_name == "PostgreSQL" do
default = Ransack.options.clone
s = Search.new(Person, s: 'doubled_name asc')
expect(s.result.to_sql).to eq "SELECT \"people\".* FROM \"people\" ORDER BY \"people\".\"name\" || \"people\".\"name\" ASC"
Ransack.configure { |c| c.postgres_fields_sort_option = :nulls_first }
s = Search.new(Person, s: 'doubled_name asc')
expect(s.result.to_sql).to eq "SELECT \"people\".* FROM \"people\" ORDER BY \"people\".\"name\" || \"people\".\"name\" ASC NULLS FIRST"
s = Search.new(Person, s: 'doubled_name desc')
expect(s.result.to_sql).to eq "SELECT \"people\".* FROM \"people\" ORDER BY \"people\".\"name\" || \"people\".\"name\" DESC NULLS LAST"
Ransack.configure { |c| c.postgres_fields_sort_option = :nulls_last }
s = Search.new(Person, s: 'doubled_name asc')
expect(s.result.to_sql).to eq "SELECT \"people\".* FROM \"people\" ORDER BY \"people\".\"name\" || \"people\".\"name\" ASC NULLS LAST"
s = Search.new(Person, s: 'doubled_name desc')
expect(s.result.to_sql).to eq "SELECT \"people\".* FROM \"people\" ORDER BY \"people\".\"name\" || \"people\".\"name\" DESC NULLS FIRST"
Ransack.configure { |c| c.postgres_fields_sort_option = :nulls_always_first }
s = Search.new(Person, s: 'doubled_name asc')
expect(s.result.to_sql).to eq "SELECT \"people\".* FROM \"people\" ORDER BY \"people\".\"name\" || \"people\".\"name\" ASC NULLS FIRST"
s = Search.new(Person, s: 'doubled_name desc')
expect(s.result.to_sql).to eq "SELECT \"people\".* FROM \"people\" ORDER BY \"people\".\"name\" || \"people\".\"name\" DESC NULLS FIRST"
Ransack.configure { |c| c.postgres_fields_sort_option = :nulls_always_last }
s = Search.new(Person, s: 'doubled_name asc')
expect(s.result.to_sql).to eq "SELECT \"people\".* FROM \"people\" ORDER BY \"people\".\"name\" || \"people\".\"name\" ASC NULLS LAST"
s = Search.new(Person, s: 'doubled_name desc')
expect(s.result.to_sql).to eq "SELECT \"people\".* FROM \"people\" ORDER BY \"people\".\"name\" || \"people\".\"name\" DESC NULLS LAST"
Ransack.options = default
end
end
describe '#method_missing' do
before do
@s = Search.new(Person)
end
it 'raises NoMethodError when sent an invalid attribute' do
expect { @s.blah }.to raise_error NoMethodError
end
it 'sets condition attributes when sent valid attributes' do
@s.name_eq = 'Ernie'
expect(@s.name_eq).to eq 'Ernie'
end
it 'allows chaining to access nested conditions' do
@s.groupings = [
{ m: 'or', name_eq: 'Ernie', children_name_eq: 'Ernie' }
]
expect(@s.groupings.first.children_name_eq).to eq 'Ernie'
end
end
end
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/spec/ransack/predicate_spec.rb | spec/ransack/predicate_spec.rb | require 'spec_helper'
module Ransack
TRUE_VALUES = [true, 1, '1', 't', 'T', 'true', 'TRUE'].to_set
FALSE_VALUES = [false, 0, '0', 'f', 'F', 'false', 'FALSE'].to_set
describe Predicate do
before do
@s = Search.new(Person)
end
shared_examples 'wildcard escaping' do |method, regexp|
it 'automatically converts integers to strings' do
subject.parent_id_cont = 1
expect { subject.result }.to_not raise_error
end
it "escapes '%', '.', '_' and '\\\\' in value" do
subject.send(:"#{method}=", '%._\\')
expect(subject.result.to_sql).to match(regexp)
end
end
describe 'eq' do
it 'generates an equality condition for boolean true values' do
test_boolean_equality_for(true)
end
it 'generates an equality condition for boolean false values' do
test_boolean_equality_for(false)
end
it 'does not generate a condition for nil' do
@s.awesome_eq = nil
expect(@s.result.to_sql).not_to match /WHERE/
end
it 'generates a = condition with a huge integer value' do
val = 123456789012345678901
@s.salary_eq = val
field = "#{quote_table_name("people")}.#{quote_column_name("salary")}"
expect(@s.result.to_sql).to match /#{field} = #{val}/
end
end
describe 'lteq' do
it 'generates a <= condition with an integer column' do
val = 1000
@s.salary_lteq = val
field = "#{quote_table_name("people")}.#{quote_column_name("salary")}"
expect(@s.result.to_sql).to match /#{field} <= #{val}/
end
it 'generates a <= condition with a string column' do
val = 'jane@doe.com'
@s.email_lteq = val
field = "#{quote_table_name("people")}.#{quote_column_name("email")}"
expect(@s.result.to_sql).to match /#{field} <= '#{val}'/
end
it 'does not generate a condition for nil' do
@s.salary_lteq = nil
expect(@s.result.to_sql).not_to match /WHERE/
end
it 'generates a <= condition with a huge integer value' do
val = 123456789012345678901
@s.salary_lteq = val
field = "#{quote_table_name("people")}.#{quote_column_name("salary")}"
expect(@s.result.to_sql).to match /#{field} <= #{val}/
end
end
describe 'lt' do
it 'generates a < condition with an integer column' do
val = 2000
@s.salary_lt = val
field = "#{quote_table_name("people")}.#{quote_column_name("salary")}"
expect(@s.result.to_sql).to match /#{field} < #{val}/
end
it 'generates a < condition with a string column' do
val = 'jane@doe.com'
@s.email_lt = val
field = "#{quote_table_name("people")}.#{quote_column_name("email")}"
expect(@s.result.to_sql).to match /#{field} < '#{val}'/
end
it 'does not generate a condition for nil' do
@s.salary_lt = nil
expect(@s.result.to_sql).not_to match /WHERE/
end
it 'generates a = condition with a huge integer value' do
val = 123456789012345678901
@s.salary_lt = val
field = "#{quote_table_name("people")}.#{quote_column_name("salary")}"
expect(@s.result.to_sql).to match /#{field} < #{val}/
end
end
describe 'gteq' do
it 'generates a >= condition with an integer column' do
val = 300
@s.salary_gteq = val
field = "#{quote_table_name("people")}.#{quote_column_name("salary")}"
expect(@s.result.to_sql).to match /#{field} >= #{val}/
end
it 'generates a >= condition with a string column' do
val = 'jane@doe.com'
@s.email_gteq = val
field = "#{quote_table_name("people")}.#{quote_column_name("email")}"
expect(@s.result.to_sql).to match /#{field} >= '#{val}'/
end
it 'does not generate a condition for nil' do
@s.salary_gteq = nil
expect(@s.result.to_sql).not_to match /WHERE/
end
it 'generates a >= condition with a huge integer value' do
val = 123456789012345678901
@s.salary_gteq = val
field = "#{quote_table_name("people")}.#{quote_column_name("salary")}"
expect(@s.result.to_sql).to match /#{field} >= #{val}/
end
end
describe 'gt' do
it 'generates a > condition with an integer column' do
val = 400
@s.salary_gt = val
field = "#{quote_table_name("people")}.#{quote_column_name("salary")}"
expect(@s.result.to_sql).to match /#{field} > #{val}/
end
it 'generates a > condition with a string column' do
val = 'jane@doe.com'
@s.email_gt = val
field = "#{quote_table_name("people")}.#{quote_column_name("email")}"
expect(@s.result.to_sql).to match /#{field} > '#{val}'/
end
it 'does not generate a condition for nil' do
@s.salary_gt = nil
expect(@s.result.to_sql).not_to match /WHERE/
end
it 'generates a > condition with a huge integer value' do
val = 123456789012345678901
@s.salary_gt = val
field = "#{quote_table_name("people")}.#{quote_column_name("salary")}"
expect(@s.result.to_sql).to match /#{field} > #{val}/
end
end
describe 'cont' do
it_has_behavior 'wildcard escaping', :name_cont,
(case ActiveRecord::Base.connection.adapter_name
when "PostGIS", "PostgreSQL"
/"people"."name" ILIKE '%\\%\\.\\_\\\\%'/
when "Mysql2"
/`people`.`name` LIKE '%\\\\%.\\\\_\\\\\\\\%'/
else
/"people"."name" LIKE '%%._\\%'/
end) do
subject { @s }
end
it 'generates a LIKE query with value surrounded by %' do
@s.name_cont = 'ric'
field = "#{quote_table_name("people")}.#{quote_column_name("name")}"
expect(@s.result.to_sql).to match /#{field} I?LIKE '%ric%'/
end
end
describe 'not_cont' do
it_has_behavior 'wildcard escaping', :name_not_cont,
(case ActiveRecord::Base.connection.adapter_name
when "PostGIS", "PostgreSQL"
/"people"."name" NOT ILIKE '%\\%\\.\\_\\\\%'/
when "Mysql2"
/`people`.`name` NOT LIKE '%\\\\%.\\\\_\\\\\\\\%'/
else
/"people"."name" NOT LIKE '%%._\\%'/
end) do
subject { @s }
end
it 'generates a NOT LIKE query with value surrounded by %' do
@s.name_not_cont = 'ric'
field = "#{quote_table_name("people")}.#{quote_column_name("name")}"
expect(@s.result.to_sql).to match /#{field} NOT I?LIKE '%ric%'/
end
end
describe 'i_cont' do
it_has_behavior 'wildcard escaping', :name_i_cont,
(case ActiveRecord::Base.connection.adapter_name
when "PostGIS"
/LOWER\("people"."name"\) ILIKE '%\\%\\.\\_\\\\%'/
when "PostgreSQL"
/"people"."name" ILIKE '%\\%\\.\\_\\\\%'/
when "Mysql2"
/LOWER\(`people`.`name`\) LIKE '%\\\\%.\\\\_\\\\\\\\%'/
else
/LOWER\("people"."name"\) LIKE '%%._\\%'/
end) do
subject { @s }
end
it 'generates a LIKE query with LOWER(column) and value surrounded by %' do
@s.name_i_cont = 'Ric'
field = "#{quote_table_name("people")}.#{quote_column_name("name")}"
expect(@s.result.to_sql).to match /[LOWER\(]?#{field}\)? I?LIKE '%ric%'/
end
end
describe 'not_i_cont' do
it_has_behavior 'wildcard escaping', :name_not_i_cont,
(case ActiveRecord::Base.connection.adapter_name
when "PostGIS"
/LOWER\("people"."name"\) NOT ILIKE '%\\%\\.\\_\\\\%'/
when "PostgreSQL"
/"people"."name" NOT ILIKE '%\\%\\.\\_\\\\%'/
when "Mysql2"
/LOWER\(`people`.`name`\) NOT LIKE '%\\\\%.\\\\_\\\\\\\\%'/
else
/LOWER\("people"."name"\) NOT LIKE '%%._\\%'/
end) do
subject { @s }
end
it 'generates a NOT LIKE query with LOWER(column) and value surrounded by %' do
@s.name_not_i_cont = 'Ric'
field = "#{quote_table_name("people")}.#{quote_column_name("name")}"
expect(@s.result.to_sql).to match /[LOWER\(]?#{field}\)? NOT I?LIKE '%ric%'/
end
end
describe 'start' do
it 'generates a LIKE query with value followed by %' do
@s.name_start = 'Er'
field = "#{quote_table_name("people")}.#{quote_column_name("name")}"
expect(@s.result.to_sql).to match /#{field} I?LIKE 'Er%'/
end
it "works with attribute names ending with '_start'" do
@s.new_start_start = 'hEy'
field = "#{quote_table_name("people")}.#{quote_column_name("new_start")}"
expect(@s.result.to_sql).to match /#{field} I?LIKE 'hEy%'/
end
it "works with attribute names ending with '_end'" do
@s.stop_end_start = 'begin'
field = "#{quote_table_name("people")}.#{quote_column_name("stop_end")}"
expect(@s.result.to_sql).to match /#{field} I?LIKE 'begin%'/
end
end
describe 'not_start' do
it 'generates a NOT LIKE query with value followed by %' do
@s.name_not_start = 'Eri'
field = "#{quote_table_name("people")}.#{quote_column_name("name")}"
expect(@s.result.to_sql).to match /#{field} NOT I?LIKE 'Eri%'/
end
it "works with attribute names ending with '_start'" do
@s.new_start_not_start = 'hEy'
field = "#{quote_table_name("people")}.#{quote_column_name("new_start")}"
expect(@s.result.to_sql).to match /#{field} NOT I?LIKE 'hEy%'/
end
it "works with attribute names ending with '_end'" do
@s.stop_end_not_start = 'begin'
field = "#{quote_table_name("people")}.#{quote_column_name("stop_end")}"
expect(@s.result.to_sql).to match /#{field} NOT I?LIKE 'begin%'/
end
end
describe 'end' do
it 'generates a LIKE query with value preceded by %' do
@s.name_end = 'Miller'
field = "#{quote_table_name("people")}.#{quote_column_name("name")}"
expect(@s.result.to_sql).to match /#{field} I?LIKE '%Miller'/
end
it "works with attribute names ending with '_start'" do
@s.new_start_end = 'finish'
field = "#{quote_table_name("people")}.#{quote_column_name("new_start")}"
expect(@s.result.to_sql).to match /#{field} I?LIKE '%finish'/
end
it "works with attribute names ending with '_end'" do
@s.stop_end_end = 'Ending'
field = "#{quote_table_name("people")}.#{quote_column_name("stop_end")}"
expect(@s.result.to_sql).to match /#{field} I?LIKE '%Ending'/
end
end
describe 'not_end' do
it 'generates a NOT LIKE query with value preceded by %' do
@s.name_not_end = 'Miller'
field = "#{quote_table_name("people")}.#{quote_column_name("name")}"
expect(@s.result.to_sql).to match /#{field} NOT I?LIKE '%Miller'/
end
it "works with attribute names ending with '_start'" do
@s.new_start_not_end = 'finish'
field = "#{quote_table_name("people")}.#{quote_column_name("new_start")}"
expect(@s.result.to_sql).to match /#{field} NOT I?LIKE '%finish'/
end
it "works with attribute names ending with '_end'" do
@s.stop_end_not_end = 'Ending'
field = "#{quote_table_name("people")}.#{quote_column_name("stop_end")}"
expect(@s.result.to_sql).to match /#{field} NOT I?LIKE '%Ending'/
end
end
describe 'true' do
it 'generates an equality condition for boolean true' do
@s.awesome_true = true
field = "#{quote_table_name("people")}.#{quote_column_name("awesome")}"
expect(@s.result.to_sql).to match /#{field} = #{
ActiveRecord::Base.connection.quoted_true}/
end
it 'generates an inequality condition for boolean true' do
@s.awesome_true = false
field = "#{quote_table_name("people")}.#{quote_column_name("awesome")}"
expect(@s.result.to_sql).to match /#{field} != #{
ActiveRecord::Base.connection.quoted_true}/
end
end
describe 'not_true' do
it 'generates an inequality condition for boolean true' do
@s.awesome_not_true = true
field = "#{quote_table_name("people")}.#{quote_column_name("awesome")}"
expect(@s.result.to_sql).to match /#{field} != #{
ActiveRecord::Base.connection.quoted_true}/
end
it 'generates an equality condition for boolean true' do
@s.awesome_not_true = false
field = "#{quote_table_name("people")}.#{quote_column_name("awesome")}"
expect(@s.result.to_sql).to match /#{field} = #{
ActiveRecord::Base.connection.quoted_true}/
end
end
describe 'false' do
it 'generates an equality condition for boolean false' do
@s.awesome_false = true
field = "#{quote_table_name("people")}.#{quote_column_name("awesome")}"
expect(@s.result.to_sql).to match /#{field} = #{
ActiveRecord::Base.connection.quoted_false}/
end
it 'generates an inequality condition for boolean false' do
@s.awesome_false = false
field = "#{quote_table_name("people")}.#{quote_column_name("awesome")}"
expect(@s.result.to_sql).to match /#{field} != #{
ActiveRecord::Base.connection.quoted_false}/
end
end
describe 'not_false' do
it 'generates an inequality condition for boolean false' do
@s.awesome_not_false = true
field = "#{quote_table_name("people")}.#{quote_column_name("awesome")}"
expect(@s.result.to_sql).to match /#{field} != #{
ActiveRecord::Base.connection.quoted_false}/
end
it 'generates an equality condition for boolean false' do
@s.awesome_not_false = false
field = "#{quote_table_name("people")}.#{quote_column_name("awesome")}"
expect(@s.result.to_sql).to match /#{field} = #{
ActiveRecord::Base.connection.quoted_false}/
end
end
describe 'null' do
it 'generates a value IS NULL query' do
@s.name_null = true
field = "#{quote_table_name("people")}.#{quote_column_name("name")}"
expect(@s.result.to_sql).to match /#{field} IS NULL/
end
it 'generates a value IS NOT NULL query when assigned false' do
@s.name_null = false
field = "#{quote_table_name("people")}.#{quote_column_name("name")}"
expect(@s.result.to_sql).to match /#{field} IS NOT NULL/
end
end
describe 'not_null' do
it 'generates a value IS NOT NULL query' do
@s.name_not_null = true
field = "#{quote_table_name("people")}.#{quote_column_name("name")}"
expect(@s.result.to_sql).to match /#{field} IS NOT NULL/
end
it 'generates a value IS NULL query when assigned false' do
@s.name_not_null = false
field = "#{quote_table_name("people")}.#{quote_column_name("name")}"
expect(@s.result.to_sql).to match /#{field} IS NULL/
end
describe 'with association query' do
it 'generates a value IS NOT NULL query' do
@s.comments_id_not_null = true
sql = @s.result.to_sql
parent_field = "#{quote_table_name("people")}.#{quote_column_name("id")}"
expect(sql).to match /#{parent_field} IN/
field = "#{quote_table_name("comments")}.#{quote_column_name("id")}"
expect(sql).to match /#{field} IS NOT NULL/
expect(sql).not_to match /AND NOT/
end
it 'generates a value IS NULL query when assigned false' do
@s.comments_id_not_null = false
sql = @s.result.to_sql
parent_field = "#{quote_table_name("people")}.#{quote_column_name("id")}"
expect(sql).to match /#{parent_field} NOT IN/
field = "#{quote_table_name("comments")}.#{quote_column_name("id")}"
expect(sql).to match /#{field} IS NULL/
expect(sql).to match /AND NOT/
end
end
end
describe 'present' do
it %q[generates a value IS NOT NULL AND value != '' query] do
@s.name_present = true
field = "#{quote_table_name("people")}.#{quote_column_name("name")}"
expect(@s.result.to_sql).to match /#{field} IS NOT NULL AND #{field} != ''/
end
it %q[generates a value IS NULL OR value = '' query when assigned false] do
@s.name_present = false
field = "#{quote_table_name("people")}.#{quote_column_name("name")}"
expect(@s.result.to_sql).to match /#{field} IS NULL OR #{field} = ''/
end
end
describe 'blank' do
it %q[generates a value IS NULL OR value = '' query] do
@s.name_blank = true
field = "#{quote_table_name("people")}.#{quote_column_name("name")}"
expect(@s.result.to_sql).to match /#{field} IS NULL OR #{field} = ''/
end
it %q[generates a value IS NOT NULL AND value != '' query when assigned false] do
@s.name_blank = false
field = "#{quote_table_name("people")}.#{quote_column_name("name")}"
expect(@s.result.to_sql).to match /#{field} IS NOT NULL AND #{field} != ''/
end
end
context "defining custom predicates" do
describe "with 'not_in' arel predicate" do
before do
Ransack.configure { |c| c.add_predicate "not_in_csv", arel_predicate: "not_in", formatter: proc { |v| v.split(",") } }
end
it 'generates a value IS NOT NULL query' do
@s.name_not_in_csv = ["a", "b"]
field = "#{quote_table_name("people")}.#{quote_column_name("name")}"
expect(@s.result.to_sql).to match /#{field} NOT IN \('a', 'b'\)/
end
end
end
private
def test_boolean_equality_for(boolean_value)
query = expected_query(boolean_value)
test_values_for(boolean_value).each do |value|
s = Search.new(Person, awesome_eq: value)
expect(s.result.to_sql).to match query
end
end
def test_values_for(boolean_value)
case boolean_value
when true
TRUE_VALUES
when false
FALSE_VALUES
end
end
def expected_query(value, attribute = 'awesome', operator = '=')
field = "#{quote_table_name("people")}.#{quote_column_name(attribute)}"
quoted_value = ActiveRecord::Base.connection.quote(value)
/#{field} #{operator} #{quoted_value}/
end
end
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/spec/ransack/configuration_spec.rb | spec/ransack/configuration_spec.rb | require 'spec_helper'
module Ransack
describe Configuration do
it 'yields Ransack on configure' do
Ransack.configure { |config| expect(config).to eq Ransack }
end
it 'adds predicates' do
Ransack.configure do |config|
config.add_predicate :test_predicate
end
expect(Ransack.predicates).to have_key 'test_predicate'
expect(Ransack.predicates).to have_key 'test_predicate_any'
expect(Ransack.predicates).to have_key 'test_predicate_all'
end
it 'avoids creating compound predicates if compounds: false' do
Ransack.configure do |config|
config.add_predicate(
:test_predicate_without_compound,
compounds: false
)
end
expect(Ransack.predicates)
.to have_key 'test_predicate_without_compound'
expect(Ransack.predicates)
.not_to have_key 'test_predicate_without_compound_any'
expect(Ransack.predicates)
.not_to have_key 'test_predicate_without_compound_all'
end
it 'should have default value for search key' do
expect(Ransack.options[:search_key]).to eq :q
end
it 'changes default search key parameter' do
default = Ransack.options.clone
Ransack.configure { |c| c.search_key = :query }
expect(Ransack.options[:search_key]).to eq :query
Ransack.options = default
end
it 'should have default value for strip_whitespace' do
expect(Ransack.options[:strip_whitespace]).to eq true
end
it 'changes default search key parameter' do
default = Ransack.options.clone
Ransack.configure { |c| c.strip_whitespace = false }
expect(Ransack.options[:strip_whitespace]).to eq false
Ransack.options = default
end
it 'should have default values for arrows' do
expect(Ransack.options[:up_arrow]).to eq '▼'
expect(Ransack.options[:down_arrow]).to eq '▲'
expect(Ransack.options[:default_arrow]).to eq nil
end
it 'changes the default value for the up arrow only' do
default, new_up_arrow = Ransack.options.clone, 'U+02191'
Ransack.configure { |c| c.custom_arrows = { up_arrow: new_up_arrow } }
expect(Ransack.options[:down_arrow]).to eq default[:down_arrow]
expect(Ransack.options[:up_arrow]).to eq new_up_arrow
Ransack.options = default
end
it 'changes the default value for the down arrow only' do
default, new_down_arrow = Ransack.options.clone, '<i class="down"></i>'
Ransack.configure { |c| c.custom_arrows = { down_arrow: new_down_arrow } }
expect(Ransack.options[:up_arrow]).to eq default[:up_arrow]
expect(Ransack.options[:down_arrow]).to eq new_down_arrow
Ransack.options = default
end
it 'changes the default value for the default arrow only' do
default, new_default_arrow = Ransack.options.clone, '<i class="default"></i>'
Ransack.configure { |c| c.custom_arrows = { default_arrow: new_default_arrow } }
expect(Ransack.options[:up_arrow]).to eq default[:up_arrow]
expect(Ransack.options[:down_arrow]).to eq default[:down_arrow]
expect(Ransack.options[:default_arrow]).to eq new_default_arrow
Ransack.options = default
end
it 'changes the default value for all arrows' do
default = Ransack.options.clone
new_up_arrow = '<i class="fa fa-long-arrow-up"></i>'
new_down_arrow = 'U+02193'
new_default_arrow = 'defaultarrow'
Ransack.configure do |c|
c.custom_arrows = { up_arrow: new_up_arrow, down_arrow: new_down_arrow, default_arrow: new_default_arrow }
end
expect(Ransack.options[:up_arrow]).to eq new_up_arrow
expect(Ransack.options[:down_arrow]).to eq new_down_arrow
expect(Ransack.options[:default_arrow]).to eq new_default_arrow
Ransack.options = default
end
it 'consecutive arrow customizations respect previous customizations' do
default = Ransack.options.clone
Ransack.configure { |c| c.custom_arrows = { up_arrow: 'up' } }
expect(Ransack.options[:down_arrow]).to eq default[:down_arrow]
Ransack.configure { |c| c.custom_arrows = { down_arrow: 'DOWN' } }
expect(Ransack.options[:up_arrow]).to eq 'up'
Ransack.configure { |c| c.custom_arrows = { up_arrow: '<i>U-Arrow</i>' } }
expect(Ransack.options[:down_arrow]).to eq 'DOWN'
Ransack.configure { |c| c.custom_arrows = { down_arrow: 'down arrow-2' } }
expect(Ransack.options[:up_arrow]).to eq '<i>U-Arrow</i>'
Ransack.options = default
end
it 'adds predicates that take arrays, overriding compounds' do
Ransack.configure do |config|
config.add_predicate(
:test_array_predicate,
wants_array: true,
compounds: true
)
end
expect(Ransack.predicates['test_array_predicate'].wants_array).to eq true
expect(Ransack.predicates).not_to have_key 'test_array_predicate_any'
expect(Ransack.predicates).not_to have_key 'test_array_predicate_all'
end
describe '`wants_array` option takes precedence over Arel predicate' do
it 'implicitly wants an array for in/not in predicates' do
Ransack.configure do |config|
config.add_predicate(
:test_in_predicate,
arel_predicate: 'in'
)
config.add_predicate(
:test_not_in_predicate,
arel_predicate: 'not_in'
)
end
expect(Ransack.predicates['test_in_predicate'].wants_array)
.to eq true
expect(Ransack.predicates['test_not_in_predicate'].wants_array)
.to eq true
end
it 'explicitly does not want array for in/not_in predicates' do
Ransack.configure do |config|
config.add_predicate(
:test_in_predicate_no_array,
arel_predicate: 'in',
wants_array: false
)
config.add_predicate(
:test_not_in_predicate_no_array,
arel_predicate: 'not_in',
wants_array: false
)
end
expect(Ransack.predicates['test_in_predicate_no_array'].wants_array)
.to eq false
expect(Ransack.predicates['test_not_in_predicate_no_array'].wants_array)
.to eq false
end
end
it "PG's sort option", if: ::ActiveRecord::Base.connection.adapter_name == "PostgreSQL" do
default = Ransack.options.clone
Ransack.configure { |c| c.postgres_fields_sort_option = :nulls_first }
expect(Ransack.options[:postgres_fields_sort_option]).to eq :nulls_first
Ransack.options = default
end
end
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/spec/ransack/ransacker_spec.rb | spec/ransack/ransacker_spec.rb | require 'spec_helper'
module Ransack
describe Ransacker do
let(:klass) { Person }
let(:name) { :test_ransacker }
let(:opts) { {} }
describe '#initialize' do
context 'with minimal options' do
subject { Ransacker.new(klass, name, opts) }
it 'sets the name' do
expect(subject.name).to eq(name)
end
it 'sets default type to string' do
expect(subject.type).to eq(:string)
end
it 'sets default args to [:parent]' do
expect(subject.args).to eq([:parent])
end
end
context 'with custom options' do
let(:opts) { { type: :integer, args: [:parent, :custom_arg], formatter: proc { |v| v.to_i } } }
subject { Ransacker.new(klass, name, opts) }
it 'sets the custom type' do
expect(subject.type).to eq(:integer)
end
it 'sets the custom args' do
expect(subject.args).to eq([:parent, :custom_arg])
end
it 'sets the formatter' do
expect(subject.formatter).to eq(opts[:formatter])
end
end
context 'with callable option' do
let(:callable) { proc { |parent| parent.table[:id] } }
let(:opts) { { callable: callable } }
subject { Ransacker.new(klass, name, opts) }
it 'initializes successfully' do
expect(subject).to be_a(Ransacker)
end
end
end
describe 'basic functionality' do
subject { Ransacker.new(klass, name, opts) }
it 'responds to required methods' do
expect(subject).to respond_to(:name)
expect(subject).to respond_to(:type)
expect(subject).to respond_to(:args)
expect(subject).to respond_to(:formatter)
expect(subject).to respond_to(:attr_from)
expect(subject).to respond_to(:call)
end
end
end
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/spec/ransack/translate_spec.rb | spec/ransack/translate_spec.rb | require 'spec_helper'
module Ransack
describe Translate do
describe '.attribute' do
it 'translate namespaced attribute like AR does' do
ar_translation = ::Namespace::Article.human_attribute_name(:title)
ransack_translation = Ransack::Translate.attribute(
:title,
context: ::Namespace::Article.ransack.context
)
expect(ransack_translation).to eq ar_translation
end
end
end
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/spec/ransack/invalid_search_error_spec.rb | spec/ransack/invalid_search_error_spec.rb | require 'spec_helper'
module Ransack
describe InvalidSearchError do
it 'inherits from ArgumentError' do
expect(InvalidSearchError.superclass).to eq(ArgumentError)
end
it 'can be instantiated with a message' do
error = InvalidSearchError.new('Test error message')
expect(error.message).to eq('Test error message')
end
it 'can be instantiated without a message' do
error = InvalidSearchError.new
expect(error.message).to eq('Ransack::InvalidSearchError')
end
it 'can be raised and caught' do
expect { raise InvalidSearchError.new('Test') }.to raise_error(InvalidSearchError, 'Test')
end
it 'can be raised and caught as ArgumentError' do
expect { raise InvalidSearchError.new('Test') }.to raise_error(ArgumentError, 'Test')
end
end
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/spec/ransack/helpers/form_builder_spec.rb | spec/ransack/helpers/form_builder_spec.rb | require 'spec_helper'
module Ransack
module Helpers
describe FormBuilder do
router = ActionDispatch::Routing::RouteSet.new
router.draw do
resources :people, :comments, :notes
end
include router.url_helpers
# FIXME: figure out a cleaner way to get this behavior
before do
@controller = ActionView::TestCase::TestController.new
@controller.instance_variable_set(:@_routes, router)
@controller.class_eval { include router.url_helpers }
@controller.view_context_class.class_eval { include router.url_helpers }
@s = Person.ransack
@controller.view_context.search_form_for(@s) { |f| @f = f }
end
it 'selects previously-entered time values with datetime_select' do
date_values = %w(2011 1 2 03 04 05)
# @s.created_at_eq = date_values # This works in Rails 4.x but not 3.x
@s.created_at_eq = [2011, 1, 2, 3, 4, 5] # so we have to do this
html = @f.datetime_select(
:created_at_eq, use_month_numbers: true, include_seconds: true
)
date_values.each { |val| expect(html).to include date_select_html(val) }
end
describe '#label' do
context 'with direct model attributes' do
it 'localizes attribute names' do
test_label(@f, :name_cont, /Full Name contains/)
test_label(@f, :only_admin_start, /admin uSer Only starts with/)
test_label(@f, :salary_gt, /wages greater than/)
test_label(@f, :awesome_true, /ransack is really awesome is true/)
end
it 'falls back to `attribute_name.capitalize` when no translation' do
test_label(@f, :email_cont, /Email contains/)
test_label(@f, :only_sort_start, /Only sort starts with/)
test_label(@f, :only_search_eq, /Only search equals/)
end
end
context 'with `has_many` association attributes' do
it 'localizes :"#{pluralized model}_#{attribute name}_#{predicate}"' do
test_label(@f, :articles_body_start, /Article maiN BoDy starts with/)
end
it 'falls back to `model_name.capitalize + attribute_name.capitalize` when no translation' do
test_label(@f, :articles_title_cont, /Article Title contains/)
test_label(@f, :articles_subject_header_start, /Article Subject header starts with/)
end
end
context 'with `belongs_to` association attributes' do
before do
@controller.view_context.search_form_for(Comment.ransack) { |f| @f = f }
end
it 'localizes :"#{singularized model}_#{attribute name}_#{predicate}"' do
test_label(@f, :article_body_start, /Article maiN BoDy starts with/)
end
it 'falls back to `model_name.capitalize + attribute_name.capitalize` when no translation' do
test_label(@f, :article_title_eq, /Article Title equals/)
test_label(@f, :article_subject_header_end, /Article Subject header ends with/)
end
end
end
describe '#sort_link' do
it 'sort_link for ransack attribute' do
sort_link = @f.sort_link :name, controller: 'people'
expect(sort_link).to match /people\?q(%5B|\[)s(%5D|\])=name\+asc/
expect(sort_link).to match /sort_link/
expect(sort_link).to match /Full Name<\/a>/
end
it 'sort_link for common attribute' do
sort_link = @f.sort_link :id, controller: 'people'
expect(sort_link).to match /id<\/a>/
end
end
describe '#submit' do
it 'localizes :search when no default value given' do
html = @f.submit
expect(html).to match /"Search"/
end
end
describe '#attribute_select' do
it 'returns ransackable attributes' do
html = @f.attribute_select
expect(html.split(/\n/).size).to eq(Person.ransackable_attributes.size + 1)
Person.ransackable_attributes.each do |attribute|
expect(html).to match /<option value="#{attribute}">/
end
end
it 'returns ransackable attributes for associations with :associations' do
attributes = Person.ransackable_attributes +
Article.ransackable_attributes.map { |a| "articles_#{a}" }
html = @f.attribute_select(associations: ['articles'])
expect(html.split(/\n/).size).to eq(attributes.size)
attributes.each do |attribute|
expect(html).to match /<option value="#{attribute}">/
end
end
it 'returns option groups for base and associations with :associations' do
html = @f.attribute_select(associations: ['articles'])
[Person, Article].each do |model|
expect(html).to match /<optgroup label="#{model}">/
end
end
end
describe '#predicate_select' do
it 'returns predicates with predicate_select' do
html = @f.predicate_select
Predicate.names.each do |key|
expect(html).to match /<option value="#{key}">/
end
end
it 'filters predicates with single-value :only' do
html = @f.predicate_select only: 'eq'
Predicate.names.reject { |k| k =~ /^eq/ }.each do |key|
expect(html).not_to match /<option value="#{key}">/
end
end
it 'filters predicates with multi-value :only' do
html = @f.predicate_select only: [:eq, :lt]
Predicate.names.reject { |k| k =~ /^(eq|lt)/ }.each do |key|
expect(html).not_to match /<option value="#{key}">/
end
end
it 'excludes compounds when compounds: false' do
html = @f.predicate_select compounds: false
Predicate.names.select { |k| k =~ /_(any|all)$/ }.each do |key|
expect(html).not_to match /<option value="#{key}">/
end
end
end
context 'fields used in polymorphic relations as search attributes in form' do
before do
@controller.view_context.search_form_for(Note.ransack) { |f| @f = f }
end
it 'accepts poly_id field' do
html = @f.text_field(:notable_id_eq)
expect(html).to match /id=\"q_notable_id_eq\"/
end
it 'accepts poly_type field' do
html = @f.text_field(:notable_type_eq)
expect(html).to match /id=\"q_notable_type_eq\"/
end
end
private
def test_label(f, query, expected)
expect(f.label query).to match expected
end
# Starting from Rails 4.2, the date_select html attributes are no longer
# `sort`ed (for a speed gain), so the tests have to be different:
def date_select_html(val)
%(<option value="#{val}" selected="selected">#{val}</option>)
end
end
end
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/spec/ransack/helpers/form_helper_spec.rb | spec/ransack/helpers/form_helper_spec.rb | require 'spec_helper'
module Ransack
module Helpers
describe FormHelper do
router = ActionDispatch::Routing::RouteSet.new
router.draw do
resources :people, :notes
namespace :admin do
resources :comments
end
end
include router.url_helpers
# FIXME: figure out a cleaner way to get this behavior
before do
@controller = ActionView::TestCase::TestController.new
@controller.instance_variable_set(:@_routes, router)
@controller.class_eval { include router.url_helpers }
@controller.view_context_class.class_eval { include router.url_helpers }
end
describe '#sort_link with default search_key' do
subject { @controller.view_context
.sort_link(
[:main_app, Person.ransack(sorts: ['name desc'])],
:name,
controller: 'people'
)
}
it { should match /people\?q(%5B|\[)s(%5D|\])=name\+asc/ }
it { should match /sort_link desc/ }
it { should match /Full Name ▼/ }
end
describe '#sort_url with default search_key' do
subject { @controller.view_context
.sort_url(
[:main_app, Person.ransack(sorts: ['name desc'])],
:name,
controller: 'people'
)
}
it { should match /people\?q(%5B|\[)s(%5D|\])=name\+asc/ }
end
describe '#sort_link with default search_key defined as symbol' do
subject { @controller.view_context
.sort_link(
Person.ransack({ sorts: ['name desc'] }, search_key: :people_search),
:name, controller: 'people'
)
}
it { should match /people\?people_search(%5B|\[)s(%5D|\])=name\+asc/ }
end
describe '#sort_url with default search_key defined as symbol' do
subject { @controller.view_context
.sort_url(
Person.ransack({ sorts: ['name desc'] }, search_key: :people_search),
:name, controller: 'people'
)
}
it { should match /people\?people_search(%5B|\[)s(%5D|\])=name\+asc/ }
end
describe '#sort_link desc through association table defined as symbol' do
subject { @controller.view_context
.sort_link(
Person.ransack({ sorts: 'comments_body asc' }),
:comments_body,
controller: 'people'
)
}
it { should match /people\?q(%5B|\[)s(%5D|\])=comments.body\+desc/ }
it { should match /sort_link asc/ }
it { should match /Body ▲/ }
end
describe '#sort_url desc through association table defined as symbol' do
subject { @controller.view_context
.sort_url(
Person.ransack({ sorts: 'comments_body asc' }),
:comments_body,
controller: 'people'
)
}
it { should match /people\?q(%5B|\[)s(%5D|\])=comments.body\+desc/ }
end
describe '#sort_link through association table defined as a string' do
subject { @controller.view_context
.sort_link(
Person.ransack({ sorts: 'comments.body desc' }),
'comments.body',
controller: 'people'
)
}
it { should match /people\?q(%5B|\[)s(%5D|\])=comments.body\+asc/ }
it { should match /sort_link desc/ }
it { should match /Comments.body ▼/ }
end
describe '#sort_url through association table defined as a string' do
subject { @controller.view_context
.sort_url(
Person.ransack({ sorts: 'comments.body desc' }),
'comments.body',
controller: 'people'
)
}
it { should match /people\?q(%5B|\[)s(%5D|\])=comments.body\+asc/ }
end
describe '#sort_link works even if search params are a blank string' do
before { @controller.view_context.params[:q] = '' }
specify {
expect { @controller.view_context
.sort_link(
Person.ransack(@controller.view_context.params[:q]),
:name,
controller: 'people'
)
}.not_to raise_error
}
end
describe '#sort_url works even if search params are a blank string' do
before { @controller.view_context.params[:q] = '' }
specify {
expect { @controller.view_context
.sort_url(
Person.ransack(@controller.view_context.params[:q]),
:name,
controller: 'people'
)
}.not_to raise_error
}
end
describe '#sort_link works even if search params are a string' do
before { @controller.view_context.params[:q] = 'input error' }
specify {
expect { @controller.view_context
.sort_link(
Person.ransack({}),
:name,
controller: 'people'
)
}.not_to raise_error
}
end
describe '#sort_url works even if search params are a string' do
before { @controller.view_context.params[:q] = 'input error' }
specify {
expect { @controller.view_context
.sort_url(
Person.ransack({}),
:name,
controller: 'people'
)
}.not_to raise_error
}
end
describe '#sort_link with search_key defined as a string' do
subject { @controller.view_context
.sort_link(
Person.ransack(
{ sorts: ['name desc'] }, search_key: 'people_search'
),
:name,
controller: 'people'
)
}
it { should match /people\?people_search(%5B|\[)s(%5D|\])=name\+asc/ }
end
describe '#sort_link with default_order defined with a string key' do
subject { @controller.view_context
.sort_link(
[:main_app, Person.ransack()],
:name,
controller: 'people',
default_order: 'desc'
)
}
it { should_not match /default_order/ }
end
describe '#sort_url with default_order defined with a string key' do
subject { @controller.view_context
.sort_url(
[:main_app, Person.ransack()],
:name,
controller: 'people',
default_order: 'desc'
)
}
it { should_not match /default_order/ }
end
describe '#sort_link with multiple search_keys defined as an array' do
subject { @controller.view_context
.sort_link(
[:main_app, Person.ransack(sorts: ['name desc', 'email asc'])],
:name, [:name, 'email DESC'],
controller: 'people'
)
}
it {
should match(/people\?q(%5B|\[)s(%5D|\])(%5B|\[)(%5D|\])=name\+asc&q(%5B|\[)s(%5D|\])(%5B|\[)(%5D|\])=email\+desc/
)
}
it { should match /sort_link desc/ }
it { should match /Full Name ▼/ }
end
describe '#sort_url with multiple search_keys defined as an array' do
subject { @controller.view_context
.sort_url(
[:main_app, Person.ransack(sorts: ['name desc', 'email asc'])],
:name, [:name, 'email DESC'],
controller: 'people'
)
}
it {
should match(/people\?q(%5B|\[)s(%5D|\])(%5B|\[)(%5D|\])=name\+asc&q(%5B|\[)s(%5D|\])(%5B|\[)(%5D|\])=email\+desc/
)
}
end
describe '#sort_link with multiple search_keys does not break on nil values & ignores them' do
subject { @controller.view_context
.sort_link(
[:main_app, Person.ransack(sorts: ['name desc', nil, 'email', nil])],
:name, [nil, :name, nil, 'email DESC', nil],
controller: 'people'
)
}
it {
should match(/people\?q(%5B|\[)s(%5D|\])(%5B|\[)(%5D|\])=name\+asc&q(%5B|\[)s(%5D|\])(%5B|\[)(%5D|\])=email\+desc/
)
}
it { should match /sort_link desc/ }
it { should match /Full Name ▼/ }
end
describe '#sort_url with multiple search_keys does not break on nil values & ignores them' do
subject { @controller.view_context
.sort_url(
[:main_app, Person.ransack(sorts: ['name desc', nil, 'email', nil])],
:name, [nil, :name, nil, 'email DESC', nil],
controller: 'people'
)
}
it {
should match(/people\?q(%5B|\[)s(%5D|\])(%5B|\[)(%5D|\])=name\+asc&q(%5B|\[)s(%5D|\])(%5B|\[)(%5D|\])=email\+desc/
)
}
end
describe '#sort_link with multiple search_keys should allow a label to be specified' do
subject { @controller.view_context
.sort_link(
[:main_app, Person.ransack(sorts: ['name desc', 'email asc'])],
:name, [:name, 'email DESC'],
'Property Name',
controller: 'people'
)
}
it { should match /Property Name ▼/ }
end
describe '#sort_link with multiple search_keys should flip multiple fields specified without a direction' do
subject { @controller.view_context
.sort_link(
[:main_app, Person.ransack(sorts: ['name desc', 'email asc'])],
:name, [:name, :email],
controller: 'people'
)
}
it {
should match(/people\?q(%5B|\[)s(%5D|\])(%5B|\[)(%5D|\])=name\+asc&q(%5B|\[)s(%5D|\])(%5B|\[)(%5D|\])=email\+desc/
)
}
it { should match /sort_link desc/ }
it { should match /Full Name ▼/ }
end
describe '#sort_url with multiple search_keys should flip multiple fields specified without a direction' do
subject { @controller.view_context
.sort_url(
[:main_app, Person.ransack(sorts: ['name desc', 'email asc'])],
:name, [:name, :email],
controller: 'people'
)
}
it {
should match(/people\?q(%5B|\[)s(%5D|\])(%5B|\[)(%5D|\])=name\+asc&q(%5B|\[)s(%5D|\])(%5B|\[)(%5D|\])=email\+desc/
)
}
end
describe '#sort_link with multiple search_keys and default_order specified as a string' do
subject { @controller.view_context
.sort_link(
[:main_app, Person.ransack()],
:name, [:name, :email],
controller: 'people',
default_order: 'desc'
)
}
it {
should match(/people\?q(%5B|\[)s(%5D|\])(%5B|\[)(%5D|\])=name\+desc&q(%5B|\[)s(%5D|\])(%5B|\[)(%5D|\])=email\+desc/
)
}
it { should match /sort_link/ }
it { should match /Full Name/ }
end
describe '#sort_url with multiple search_keys and default_order specified as a string' do
subject { @controller.view_context
.sort_url(
[:main_app, Person.ransack()],
:name, [:name, :email],
controller: 'people',
default_order: 'desc'
)
}
it {
should match(/people\?q(%5B|\[)s(%5D|\])(%5B|\[)(%5D|\])=name\+desc&q(%5B|\[)s(%5D|\])(%5B|\[)(%5D|\])=email\+desc/
)
}
end
describe '#sort_link with multiple search_keys and default_order specified as a symbol' do
subject { @controller.view_context
.sort_link(
[:main_app, Person.ransack()],
:name, [:name, :email],
controller: 'people',
default_order: :desc
)
}
it {
should match(/people\?q(%5B|\[)s(%5D|\])(%5B|\[)(%5D|\])=name\+desc&q(%5B|\[)s(%5D|\])(%5B|\[)(%5D|\])=email\+desc/
)
}
it { should match /sort_link/ }
it { should match /Full Name/ }
end
describe '#sort_url with multiple search_keys and default_order specified as a symbol' do
subject { @controller.view_context
.sort_url(
[:main_app, Person.ransack],
:name, [:name, :email],
controller: 'people',
default_order: :desc
)
}
it {
should match(/people\?q(%5B|\[)s(%5D|\])(%5B|\[)(%5D|\])=name\+desc&q(%5B|\[)s(%5D|\])(%5B|\[)(%5D|\])=email\+desc/
)
}
end
describe '#sort_link with multiple search_keys should allow multiple default_orders to be specified' do
subject { @controller.view_context
.sort_link(
[:main_app, Person.ransack],
:name, [:name, :email],
controller: 'people',
default_order: { name: 'desc', email: 'asc' }
)
}
it {
should match(/people\?q(%5B|\[)s(%5D|\])(%5B|\[)(%5D|\])=name\+desc&q(%5B|\[)s(%5D|\])(%5B|\[)(%5D|\])=email\+asc/
)
}
it { should match /sort_link/ }
it { should match /Full Name/ }
end
describe '#sort_url with multiple search_keys should allow multiple default_orders to be specified' do
subject { @controller.view_context
.sort_url(
[:main_app, Person.ransack],
:name, [:name, :email],
controller: 'people',
default_order: { name: 'desc', email: 'asc' }
)
}
it {
should match(/people\?q(%5B|\[)s(%5D|\])(%5B|\[)(%5D|\])=name\+desc&q(%5B|\[)s(%5D|\])(%5B|\[)(%5D|\])=email\+asc/
)
}
end
describe '#sort_link with multiple search_keys with multiple default_orders should not override a specified order' do
subject { @controller.view_context
.sort_link(
[:main_app, Person.ransack],
:name, [:name, 'email desc'],
controller: 'people',
default_order: { name: 'desc', email: 'asc' }
)
}
it {
should match(/people\?q(%5B|\[)s(%5D|\])(%5B|\[)(%5D|\])=name\+desc&q(%5B|\[)s(%5D|\])(%5B|\[)(%5D|\])=email\+desc/
)
}
it { should match /sort_link/ }
it { should match /Full Name/ }
end
describe '#sort_url with multiple search_keys with multiple default_orders should not override a specified order' do
subject { @controller.view_context
.sort_url(
[:main_app, Person.ransack],
:name, [:name, 'email desc'],
controller: 'people',
default_order: { name: 'desc', email: 'asc' }
)
}
it {
should match(/people\?q(%5B|\[)s(%5D|\])(%5B|\[)(%5D|\])=name\+desc&q(%5B|\[)s(%5D|\])(%5B|\[)(%5D|\])=email\+desc/
)
}
end
describe "#sort_link on polymorphic association should preserve association model name case" do
subject { @controller.view_context
.sort_link(
[:main_app, Note.ransack],
:notable_of_Person_type_name, "Notable",
controller: 'notes'
)
}
it { should match /notes\?q(%5B|\[)s(%5D|\])=notable_of_Person_type_name\+asc/ }
it { should match /sort_link/ }
it { should match /Notable/ }
end
describe "#sort_url on polymorphic association should preserve association model name case" do
subject { @controller.view_context
.sort_link(
[:main_app, Note.ransack],
:notable_of_Person_type_name, "Notable",
controller: 'notes'
)
}
it { should match /notes\?q(%5B|\[)s(%5D|\])=notable_of_Person_type_name\+asc/ }
end
context 'view has existing parameters' do
describe '#sort_link should not remove existing params' do
before { @controller.view_context.params[:exist] = 'existing' }
subject {
@controller.view_context.sort_link(
Person.ransack(
{ sorts: ['name desc'] },
search_key: 'people_search'
),
:name,
controller: 'people'
)
}
it { should match /exist\=existing/ }
end
describe '#sort_url should not remove existing params' do
before { @controller.view_context.params[:exist] = 'existing' }
subject {
@controller.view_context.sort_url(
Person.ransack(
{ sorts: ['name desc'] },
search_key: 'people_search'
),
:name,
controller: 'people'
)
}
it { should match /exist\=existing/ }
end
context 'using a real ActionController::Parameter object' do
describe 'with symbol q:, #sort_link should include search params' do
subject { @controller.view_context.sort_link(Person.ransack, :name) }
let(:params) { ActionController::Parameters.new(
{ q: { name_eq: 'TEST' }, controller: 'people' }
) }
before { @controller.instance_variable_set(:@params, params) }
it {
should match(
/people\?q(%5B|\[)name_eq(%5D|\])=TEST&q(%5B|\[)s(%5D|\])
=name\+asc/x,
)
}
end
describe 'with symbol q:, #sort_url should include search params' do
subject { @controller.view_context.sort_url(Person.ransack, :name) }
let(:params) { ActionController::Parameters.new(
{ q: { name_eq: 'TEST' }, controller: 'people' }
) }
before { @controller.instance_variable_set(:@params, params) }
it {
should match(
/people\?q(%5B|\[)name_eq(%5D|\])=TEST&q(%5B|\[)s(%5D|\])
=name\+asc/x,
)
}
end
describe "with string 'q', #sort_link should include search params" do
subject { @controller.view_context.sort_link(Person.ransack, :name) }
let(:params) {
ActionController::Parameters.new(
{ 'q' => { name_eq: 'Test2' }, controller: 'people' }
) }
before { @controller.instance_variable_set(:@params, params) }
it {
should match(
/people\?q(%5B|\[)name_eq(%5D|\])=Test2&q(%5B|\[)s(%5D|\])
=name\+asc/x,
)
}
end
describe "with string 'q', #sort_url should include search params" do
subject { @controller.view_context.sort_url(Person.ransack, :name) }
let(:params) {
ActionController::Parameters.new(
{ 'q' => { name_eq: 'Test2' }, controller: 'people' }
) }
before { @controller.instance_variable_set(:@params, params) }
it {
should match(
/people\?q(%5B|\[)name_eq(%5D|\])=Test2&q(%5B|\[)s(%5D|\])
=name\+asc/x,
)
}
end
end
end
describe '#sort_link with hide order indicator set to true' do
subject { @controller.view_context
.sort_link(
[:main_app, Person.ransack(sorts: ['name desc'])],
:name,
controller: 'people',
hide_indicator: true
)
}
it { should match /Full Name/ }
it { should_not match /▼|▲/ }
end
describe '#sort_link with hide order indicator set to false' do
subject { @controller.view_context
.sort_link(
[:main_app, Person.ransack(sorts: ['name desc'])],
:name,
controller: 'people',
hide_indicator: false
)
}
it { should match /Full Name ▼/ }
end
describe '#sort_link with config set with custom up_arrow' do
before do
Ransack.configure { |c| c.custom_arrows = { up_arrow: "\u{1F446}" } }
end
after do
Ransack.configure { |c| c.custom_arrows = { up_arrow: "▼" } }
end
subject { @controller.view_context
.sort_link(
[:main_app, Person.ransack(sorts: ['name desc'])],
:name,
controller: 'people',
hide_indicator: false
)
}
it { should match /Full Name \u{1F446}/ }
end
describe '#sort_link with config set with custom down_arrow' do
before do
Ransack.configure { |c| c.custom_arrows = { down_arrow: "\u{1F447}" } }
end
after do
Ransack.configure { |c| c.custom_arrows = { down_arrow: "▲" } }
end
subject { @controller.view_context
.sort_link(
[:main_app, Person.ransack(sorts: ['name asc'])],
:name,
controller: 'people',
hide_indicator: false
)
}
it { should match /Full Name \u{1F447}/ }
end
describe '#sort_link with config set to hide arrows' do
before do
Ransack.configure { |c| c.hide_sort_order_indicators = true }
end
after do
Ransack.configure { |c| c.hide_sort_order_indicators = false }
end
subject { @controller.view_context
.sort_link(
[:main_app, Person.ransack(sorts: ['name desc'])],
:name,
controller: 'people'
)
}
it { should_not match /▼|▲/ }
end
describe '#sort_link with config set to show arrows (default setting)' do
before do
Ransack.configure { |c| c.hide_sort_order_indicators = false }
end
subject { @controller.view_context
.sort_link(
[:main_app, Person.ransack(sorts: ['name desc'])],
:name,
controller: 'people'
)
}
it { should match /Full Name ▼/ }
end
describe '#sort_link with config set to show arrows and a default arrow set' do
before do
Ransack.configure do |c|
c.hide_sort_order_indicators = false
c.custom_arrows = { default_arrow: "defaultarrow" }
end
end
after do
Ransack.configure do |c|
c.custom_arrows = { default_arrow: nil }
end
end
subject { @controller.view_context
.sort_link(
[:main_app, Person.ransack],
:name,
controller: 'people'
)
}
it { should match /Full Name defaultarrow/ }
end
describe '#sort_link w/config to hide arrows + custom arrow, hides all' do
before do
Ransack.configure do |c|
c.hide_sort_order_indicators = true
c.custom_arrows = { down_arrow: 'down', default_arrow: "defaultarrow" }
end
end
after do
Ransack.configure do |c|
c.hide_sort_order_indicators = false
c.custom_arrows = { down_arrow: '▲' }
end
end
subject { @controller.view_context
.sort_link(
[:main_app, Person.ransack(sorts: ['name desc'])],
:name,
controller: 'people'
)
}
it { should_not match /▼|down|defaultarrow/ }
end
describe '#sort_link with config set to show arrows + custom arrow' do
before do
Ransack.configure do |c|
c.hide_sort_order_indicators = false
c.custom_arrows = { up_arrow: 'up-value' }
end
end
after do
Ransack.configure do |c|
c.hide_sort_order_indicators = false
c.custom_arrows = { up_arrow: '▼' }
end
end
subject { @controller.view_context
.sort_link(
[:main_app, Person.ransack(sorts: ['name desc'])],
:name,
controller: 'people'
)
}
it { should match /▲|up-value/ }
end
describe '#sort_link with a block' do
subject { @controller.view_context
.sort_link(
[:main_app, Person.ransack(sorts: ['name desc'])],
:name,
controller: 'people'
) { 'Block label' }
}
it { should match /Block label ▼/ }
end
describe '#sort_link with class option' do
subject { @controller.view_context
.sort_link(
[:main_app, Person.ransack(sorts: ['name desc'])],
:name,
class: 'people', controller: 'people'
)
}
it { should match /class="sort_link desc people"/ }
it { should_not match /people\?class=people/ }
end
describe '#sort_link with class option workaround' do
it "generates a correct link and prints a deprecation" do
expect do
link = @controller.view_context
.sort_link(
[:main_app, Person.ransack(sorts: ['name desc'])],
:name,
'name',
{ controller: 'people' },
class: 'people'
)
expect(link).to match(/class="sort_link desc people"/)
expect(link).not_to match(/people\?class=people/)
end.to output(
/Passing two trailing hashes to `sort_link` is deprecated, merge the trailing hashes into a single one\. \(called at #{Regexp.escape(__FILE__)}:/
).to_stderr
end
end
describe '#sort_link with data option' do
subject { @controller.view_context
.sort_link(
[:main_app, Person.ransack(sorts: ['name desc'])],
:name,
data: { turbo_action: :advance }, controller: 'people'
)
}
it { should match /data-turbo-action="advance"/ }
it { should_not match /people\?data%5Bturbo_action%5D=advance/ }
end
describe "#sort_link with host option" do
subject { @controller.view_context
.sort_link(
[:main_app, Person.ransack(sorts: ['name desc'])],
:name,
host: 'foo', controller: 'people'
)
}
it { should match /href="\/people\?q/ }
it { should_not match /href=".*foo/ }
end
describe "#sort_link ignores host in params" do
before { @controller.view_context.params[:host] = 'other_domain' }
subject { @controller.view_context.sort_link(Person.ransack, :name, controller: 'people') }
it { should match /href="\/people\?q/ }
it { should_not match /href=".*other_domain/ }
end
describe '#search_form_for with default format' do
subject { @controller.view_context
.search_form_for(Person.ransack) {} }
it { should match /action="\/people"/ }
end
describe '#search_form_for with pdf format' do
subject {
@controller.view_context
.search_form_for(Person.ransack, format: :pdf) {}
}
it { should match /action="\/people.pdf"/ }
end
describe '#search_form_for with json format' do
subject {
@controller.view_context
.search_form_for(Person.ransack, format: :json) {}
}
it { should match /action="\/people.json"/ }
end
describe '#search_form_for with an array of routes' do
subject {
@controller.view_context
.search_form_for([:admin, Comment.ransack]) {}
}
it { should match /action="\/admin\/comments"/ }
end
describe '#search_form_for with custom default search key' do
before do
Ransack.configure { |c| c.search_key = :example }
end
after do
Ransack.configure { |c| c.search_key = :q }
end
subject {
@controller.view_context
.search_form_for(Person.ransack) { |f| f.text_field :name_eq }
}
it { should match /example_name_eq/ }
end
describe '#search_form_with with default format' do
subject { @controller.view_context
.search_form_with(model: Person.ransack) {} }
it { should match /action="\/people"/ }
end
describe '#search_form_with with pdf format' do
subject {
@controller.view_context
.search_form_with(model: Person.ransack, format: :pdf) {}
}
it { should match /action="\/people.pdf"/ }
end
describe '#search_form_with with json format' do
subject {
@controller.view_context
.search_form_with(model: Person.ransack, format: :json) {}
}
it { should match /action="\/people.json"/ }
end
describe '#search_form_with with an array of routes' do
subject {
@controller.view_context
.search_form_with(model: [:admin, Comment.ransack]) {}
}
it { should match /action="\/admin\/comments"/ }
end
describe '#search_form_with with custom default search key' do
before do
Ransack.configure { |c| c.search_key = :example }
end
after do
Ransack.configure { |c| c.search_key = :q }
end
subject {
@controller.view_context
.search_form_with(model: Person.ransack) { |f| f.text_field :name_eq }
}
it { should match /example\[name_eq\]/ }
end
describe '#search_form_with without Ransack::Search object' do
it 'raises ArgumentError' do
expect {
@controller.view_context.search_form_with(model: "not a search object") {}
}.to raise_error(ArgumentError, 'No Ransack::Search object was provided to search_form_with!')
end
end
describe '#turbo_search_form_for with default options' do
subject {
@controller.view_context
.turbo_search_form_for(Person.ransack) {}
}
it { should match /action="\/people"/ }
it { should match /method="post"/ }
it { should match /data-turbo-action="advance"/ }
end
describe '#turbo_search_form_for with custom method' do
subject {
@controller.view_context
.turbo_search_form_for(Person.ransack, method: :patch) {}
}
it { should match /method="post"/ }
it { should match /name="_method" value="patch"/ }
it { should match /data-turbo-action="advance"/ }
end
describe '#turbo_search_form_for with turbo_frame' do
subject {
@controller.view_context
.turbo_search_form_for(Person.ransack, turbo_frame: 'search_results') {}
}
it { should match /data-turbo-frame="search_results"/ }
end
describe '#turbo_search_form_for with custom turbo_action' do
subject {
@controller.view_context
.turbo_search_form_for(Person.ransack, turbo_action: 'replace') {}
}
it { should match /data-turbo-action="replace"/ }
end
describe '#turbo_search_form_for with format' do
subject {
@controller.view_context
.turbo_search_form_for(Person.ransack, format: :json) {}
}
it { should match /action="\/people.json"/ }
end
describe '#turbo_search_form_for with array of routes' do
subject {
@controller.view_context
.turbo_search_form_for([:admin, Comment.ransack]) {}
}
it { should match /action="\/admin\/comments"/ }
end
describe '#turbo_search_form_for with custom search key' do
before do
Ransack.configure { |c| c.search_key = :example }
end
after do
Ransack.configure { |c| c.search_key = :q }
end
subject {
@controller.view_context
.turbo_search_form_for(Person.ransack) { |f| f.text_field :name_eq }
}
it { should match /example_name_eq/ }
end
describe '#turbo_search_form_for without Ransack::Search object' do
it 'raises ArgumentError' do
expect {
@controller.view_context.turbo_search_form_for("not a search object") {}
}.to raise_error(ArgumentError, 'No Ransack::Search object was provided to turbo_search_form_for!')
end
end
describe 'private helper methods' do
let(:helper) { @controller.view_context }
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | true |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/spec/ransack/nodes/value_spec.rb | spec/ransack/nodes/value_spec.rb | require 'spec_helper'
module Ransack
module Nodes
describe Value do
let(:context) { Context.for(Person) }
subject do
Value.new(context, raw_value)
end
context "with a date value" do
let(:raw_value) { "2022-05-23" }
[:date].each do |type|
it "should cast #{type} correctly" do
result = subject.cast(type)
expect(result).to be_a_kind_of(Date)
expect(result).to eq(Date.parse(raw_value))
end
end
end
context "with a timestamp value" do
let(:raw_value) { "2022-05-23 10:40:02 -0400" }
[:datetime, :timestamp, :time, :timestamptz].each do |type|
it "should cast #{type} correctly" do
result = subject.cast(type)
expect(result).to be_a_kind_of(Time)
expect(result).to eq(Time.zone.parse(raw_value))
end
end
end
Constants::TRUE_VALUES.each do |value|
context "with a true boolean value (#{value})" do
let(:raw_value) { value.to_s }
it "should cast boolean correctly" do
result = subject.cast(:boolean)
expect(result).to eq(true)
end
end
end
Constants::FALSE_VALUES.each do |value|
context "with a false boolean value (#{value})" do
let(:raw_value) { value.to_s }
it "should cast boolean correctly" do
result = subject.cast(:boolean)
expect(result).to eq(false)
end
end
end
["12", "101.5"].each do |value|
context "with an integer value (#{value})" do
let(:raw_value) { value }
it "should cast #{value} to integer correctly" do
result = subject.cast(:integer)
expect(result).to be_an(Integer)
expect(result).to eq(value.to_i)
end
end
end
[[], ["12"], ["101.5"]].each do |value|
context "with an array value (#{value.inspect})" do
let(:raw_value) { value }
it "should cast to integer as nil" do
result = subject.cast(:integer)
expect(result).to be nil
end
end
end
["12", "101.5"].each do |value|
context "with a float value (#{value})" do
let(:raw_value) { value }
it "should cast #{value} to float correctly" do
result = subject.cast(:float)
expect(result).to be_an(Float)
expect(result).to eq(value.to_f)
end
end
end
["12", "101.5"].each do |value|
context "with a decimal value (#{value})" do
let(:raw_value) { value }
it "should cast #{value} to decimal correctly" do
result = subject.cast(:decimal)
expect(result).to be_a(BigDecimal)
expect(result).to eq(value.to_d)
end
end
end
["12", "101.513"].each do |value|
context "with a money value (#{value})" do
let(:raw_value) { value }
it "should cast #{value} to money correctly" do
result = subject.cast(:money)
expect(result).to be_a(String)
expect(result).to eq(value.to_f.to_s)
end
end
end
end
end
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/spec/ransack/nodes/condition_spec.rb | spec/ransack/nodes/condition_spec.rb | require 'spec_helper'
module Ransack
module Nodes
describe Condition do
context 'bug report #1245' do
it 'preserves tuple behavior' do
ransack_hash = {
m: 'and',
g: [
{ title_type_in: ['["title 1", ""]'] }
]
}
sql = Article.ransack(ransack_hash).result.to_sql
expect(sql).to include("IN (('title 1', ''))")
end
end
context 'with an alias' do
subject {
Condition.extract(
Context.for(Person), 'term_start', Person.first(2).map(&:name)
)
}
specify { expect(subject.combinator).to eq 'or' }
specify { expect(subject.predicate.name).to eq 'start' }
it 'converts the alias to the correct attributes' do
expect(subject.attributes.map(&:name)).to eq(['name', 'email'])
end
end
context 'with multiple values and an _any predicate' do
subject {
Condition.extract(
Context.for(Person), 'name_eq_any', Person.first(2).map(&:name)
)
}
specify { expect(subject.values.size).to eq(2) }
end
describe '#negative?' do
let(:context) { Context.for(Person) }
let(:eq) { Condition.extract(context, 'name_eq', 'A') }
let(:not_eq) { Condition.extract(context, 'name_not_eq', 'A') }
specify { expect(not_eq.negative?).to be true }
specify { expect(eq.negative?).to be false }
end
context 'with an invalid predicate' do
subject {
Condition.extract(
Context.for(Person), 'name_invalid', Person.first.name
)
}
context "when ignore_unknown_conditions is false" do
before do
Ransack.configure { |c| c.ignore_unknown_conditions = false }
end
specify { expect { subject }.to raise_error ArgumentError }
specify { expect { subject }.to raise_error InvalidSearchError }
end
context "when ignore_unknown_conditions is true" do
before do
Ransack.configure { |c| c.ignore_unknown_conditions = true }
end
specify { expect(subject).to be_nil }
end
end
context 'with an empty predicate' do
subject {
Condition.extract(
Context.for(Person), 'full_name', Person.first.name
)
}
context "when default_predicate = nil" do
before do
Ransack.configure { |c| c.default_predicate = nil }
end
specify { expect(subject).to be_nil }
end
context "when default_predicate = 'eq'" do
before do
Ransack.configure { |c| c.default_predicate = 'eq' }
end
specify { expect(subject).to eq Condition.extract(Context.for(Person), 'full_name_eq', Person.first.name) }
end
end
context 'with wildcard string values' do
it 'properly quotes values with wildcards for LIKE predicates' do
ransack_hash = { name_cont: 'test%' }
sql = Person.ransack(ransack_hash).result.to_sql
# The % should be properly quoted in the SQL
case ActiveRecord::Base.connection.adapter_name
when "Mysql2"
expect(sql).to include("LIKE '%test\\\\%%'")
expect(sql).not_to include("NOT LIKE '%test\\\\%%'")
when "PostGIS", "PostgreSQL"
expect(sql).to include("ILIKE '%test\\%%'")
expect(sql).not_to include("NOT ILIKE '%test\\%%'")
else
expect(sql).to include("LIKE '%test%%'")
expect(sql).not_to include("NOT LIKE '%test%%'")
end
end
it 'properly quotes values with wildcards for NOT LIKE predicates' do
ransack_hash = { name_not_cont: 'test%' }
sql = Person.ransack(ransack_hash).result.to_sql
# The % should be properly quoted in the SQL
case ActiveRecord::Base.connection.adapter_name
when "Mysql2"
expect(sql).to include("NOT LIKE '%test\\\\%%'")
when "PostGIS", "PostgreSQL"
expect(sql).to include("NOT ILIKE '%test\\%%'")
else
expect(sql).to include("NOT LIKE '%test%%'")
end
end
end
context 'with negative conditions on associations' do
it 'handles not_null predicate with true value correctly' do
ransack_hash = { comments_id_not_null: true }
sql = Person.ransack(ransack_hash).result.to_sql
# Should generate an IN query with IS NOT NULL condition
expect(sql).to include('IN (')
expect(sql).to include('IS NOT NULL')
expect(sql).not_to include('IS NULL')
end
it 'handles not_null predicate with false value correctly' do
ransack_hash = { comments_id_not_null: false }
sql = Person.ransack(ransack_hash).result.to_sql
# Should generate a NOT IN query with IS NULL condition
expect(sql).to include('NOT IN (')
expect(sql).to include('IS NULL')
expect(sql).not_to include('IS NOT NULL')
end
it 'handles not_cont predicate correctly' do
ransack_hash = { comments_body_not_cont: 'test' }
sql = Person.ransack(ransack_hash).result.to_sql
# Should generate a NOT IN query with LIKE condition (not NOT LIKE)
expect(sql).to include('NOT IN (')
expect(sql).to include("LIKE '%test%'")
expect(sql).not_to include("NOT LIKE '%test%'")
end
end
context 'with nested conditions' do
it 'correctly identifies non-nested conditions' do
condition = Condition.extract(
Context.for(Person), 'name_eq', 'Test'
)
# Create a mock parent table
parent_table = Person.arel_table
# Get the attribute name and make sure it starts with the table name
attribute = condition.attributes.first
expect(attribute.name).to eq('name')
expect(parent_table.name).to eq('people')
# The method should return false because 'name' doesn't start with 'people'
result = condition.send(:not_nested_condition, attribute, parent_table)
expect(result).to be false
end
it 'correctly identifies truly non-nested conditions when attribute name starts with table name' do
# Create a condition with an attribute that starts with the table name
condition = Condition.extract(
Context.for(Person), 'name_eq', 'Test'
)
# Modify the attribute name to start with the table name for testing purposes
attribute = condition.attributes.first
allow(attribute).to receive(:name).and_return('people_name')
# Create a parent table
parent_table = Person.arel_table
# Now the method should return true because 'people_name' starts with 'people'
result = condition.send(:not_nested_condition, attribute, parent_table)
expect(result).to be true
end
it 'correctly identifies nested conditions' do
condition = Condition.extract(
Context.for(Person), 'articles_title_eq', 'Test'
)
# Create a mock table alias
parent_table = Arel::Nodes::TableAlias.new(
Article.arel_table,
Article.arel_table
)
# Access the private method using send
result = condition.send(:not_nested_condition, condition.attributes.first, parent_table)
# Should return false for nested condition
expect(result).to be false
end
end
context 'with polymorphic associations and not_in predicate' do
before do
# Define test models for polymorphic associations
class ::TestTask < ActiveRecord::Base
self.table_name = 'tasks'
has_many :follows, primary_key: :uid, inverse_of: :followed, foreign_key: :followed_uid, class_name: 'TestFollow'
has_many :users, through: :follows, source: :follower, source_type: 'TestUser'
# Add ransackable_attributes method
def self.ransackable_attributes(auth_object = nil)
["created_at", "id", "name", "uid", "updated_at"]
end
# Add ransackable_associations method
def self.ransackable_associations(auth_object = nil)
["follows", "users"]
end
end
class ::TestFollow < ActiveRecord::Base
self.table_name = 'follows'
belongs_to :follower, polymorphic: true, foreign_key: :follower_uid, primary_key: :uid
belongs_to :followed, polymorphic: true, foreign_key: :followed_uid, primary_key: :uid
# Add ransackable_attributes method
def self.ransackable_attributes(auth_object = nil)
["created_at", "followed_type", "followed_uid", "follower_type", "follower_uid", "id", "updated_at"]
end
# Add ransackable_associations method
def self.ransackable_associations(auth_object = nil)
["followed", "follower"]
end
end
class ::TestUser < ActiveRecord::Base
self.table_name = 'users'
has_many :follows, primary_key: :uid, inverse_of: :follower, foreign_key: :follower_uid, class_name: 'TestFollow'
has_many :tasks, through: :follows, source: :followed, source_type: 'TestTask'
# Add ransackable_attributes method
def self.ransackable_attributes(auth_object = nil)
["created_at", "id", "name", "uid", "updated_at"]
end
# Add ransackable_associations method
def self.ransackable_associations(auth_object = nil)
["follows", "tasks"]
end
end
# Create tables if they don't exist
ActiveRecord::Base.connection.create_table(:tasks, force: true) do |t|
t.string :uid
t.string :name
t.timestamps null: false
end
ActiveRecord::Base.connection.create_table(:follows, force: true) do |t|
t.string :followed_uid, null: false
t.string :followed_type, null: false
t.string :follower_uid, null: false
t.string :follower_type, null: false
t.timestamps null: false
t.index [:followed_uid, :followed_type]
t.index [:follower_uid, :follower_type]
end
ActiveRecord::Base.connection.create_table(:users, force: true) do |t|
t.string :uid
t.string :name
t.timestamps null: false
end
end
after do
# Clean up test models and tables
Object.send(:remove_const, :TestTask)
Object.send(:remove_const, :TestFollow)
Object.send(:remove_const, :TestUser)
ActiveRecord::Base.connection.drop_table(:tasks, if_exists: true)
ActiveRecord::Base.connection.drop_table(:follows, if_exists: true)
ActiveRecord::Base.connection.drop_table(:users, if_exists: true)
end
it 'correctly handles not_in predicate with polymorphic associations' do
# Create the search
search = TestTask.ransack(users_uid_not_in: ['uid_example'])
sql = search.result.to_sql
# Verify the SQL contains the expected NOT IN clause
expect(sql).to include('NOT IN')
expect(sql).to include("follower_uid")
expect(sql).to include("followed_uid")
expect(sql).to include("'uid_example'")
# The SQL should include a reference to tasks.uid
expect(sql).to include("tasks")
expect(sql).to include("uid")
# The SQL should include a reference to follows table
expect(sql).to include("follows")
end
end
end
end
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/spec/ransack/nodes/grouping_spec.rb | spec/ransack/nodes/grouping_spec.rb | require 'spec_helper'
module Ransack
module Nodes
describe Grouping do
before do
@g = 1
end
let(:context) { Context.for(Person) }
subject { described_class.new(context) }
describe '#attribute_method?' do
context 'for attributes of the context' do
it 'is true' do
expect(subject.attribute_method?('name')).to be true
end
context "when the attribute contains '_and_'" do
it 'is true' do
expect(subject.attribute_method?('terms_and_conditions')).to be true
end
end
context "when the attribute contains '_or_'" do
it 'is true' do
expect(subject.attribute_method?('true_or_false')).to be true
end
end
context "when the attribute ends with '_start'" do
it 'is true' do
expect(subject.attribute_method?('life_start')).to be true
end
end
context "when the attribute ends with '_end'" do
it 'is true' do
expect(subject.attribute_method?('stop_end')).to be true
end
end
end
context 'for unknown attributes' do
it 'is false' do
expect(subject.attribute_method?('not_an_attribute')).to be false
end
end
end
describe '#conditions=' do
context 'when conditions are identical' do
let(:conditions) do
{
'0' => {
'a' => { '0'=> { 'name' => 'name', 'ransacker_args' => '' } },
'p' => 'cont',
'v' => { '0' => { 'value' => 'John' } }
},
'1' => {
'a' => { '0' => { 'name' => 'name', 'ransacker_args' => '' } },
'p' => 'cont',
'v' => { '0' => { 'value' => 'John' } }
}
}
end
before { subject.conditions = conditions }
it 'expect duplicates to be removed' do
expect(subject.conditions.count).to eq 1
end
end
context 'when conditions differ only by ransacker_args' do
let(:conditions) do
{
'0' => {
'a' => {
'0' => {
'name' => 'with_arguments',
'ransacker_args' => [1, 2]
}
},
'p' => 'eq',
'v' => { '0' => { 'value' => '10' } }
},
'1' => {
'a' => {
'0' => {
'name' => 'with_arguments',
'ransacker_args' => [3, 4]
}
},
'p' => 'eq',
'v' => { '0' => { 'value' => '10' } }
}
}
end
before { subject.conditions = conditions }
it 'expect them to be parsed as different and not as duplicates' do
expect(subject.conditions.count).to eq 2
end
end
end
end
end
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/spec/ransack/adapters/active_record/context_spec.rb | spec/ransack/adapters/active_record/context_spec.rb | require 'spec_helper'
module Ransack
module Adapters
module ActiveRecord
version = ::ActiveRecord::VERSION
AR_version = "#{version::MAJOR}.#{version::MINOR}"
describe Context do
subject { Context.new(Person) }
it 'has an Active Record alias tracker method' do
expect(subject.alias_tracker)
.to be_an ::ActiveRecord::Associations::AliasTracker
end
describe '#relation_for' do
it 'returns relation for given object' do
expect(subject.object).to be_an ::ActiveRecord::Relation
end
end
describe '#evaluate' do
it 'evaluates search objects' do
s = Search.new(Person, name_eq: 'Joe Blow')
result = subject.evaluate(s)
expect(result).to be_an ::ActiveRecord::Relation
expect(result.to_sql)
.to match /#{quote_column_name("name")} = 'Joe Blow'/
end
it 'SELECTs DISTINCT when distinct: true' do
s = Search.new(Person, name_eq: 'Joe Blow')
result = subject.evaluate(s, distinct: true)
expect(result).to be_an ::ActiveRecord::Relation
expect(result.to_sql).to match /SELECT DISTINCT/
end
end
describe '#build_correlated_subquery' do
it 'build correlated subquery for Root STI model' do
search = Search.new(Person, { articles_title_not_eq: 'some_title' }, context: subject)
attribute = search.conditions.first.attributes.first
constraints = subject.build_correlated_subquery(attribute.parent).constraints
constraint = constraints.first
expect(constraints.length).to eql 1
expect(constraint.left.name).to eql 'person_id'
expect(constraint.left.relation.name).to eql 'articles'
expect(constraint.right.name).to eql 'id'
expect(constraint.right.relation.name).to eql 'people'
end
it 'build correlated subquery for Child STI model when predicate is not_eq' do
search = Search.new(Person, { story_articles_title_not_eq: 'some_title' }, context: subject)
attribute = search.conditions.first.attributes.first
constraints = subject.build_correlated_subquery(attribute.parent).constraints
constraint = constraints.first
expect(constraints.length).to eql 1
expect(constraint.left.relation.name).to eql 'articles'
expect(constraint.left.name).to eql 'person_id'
expect(constraint.right.relation.name).to eql 'people'
expect(constraint.right.name).to eql 'id'
end
it 'build correlated subquery for Child STI model when predicate is eq' do
search = Search.new(Person, { story_articles_title_not_eq: 'some_title' }, context: subject)
attribute = search.conditions.first.attributes.first
constraints = subject.build_correlated_subquery(attribute.parent).constraints
constraint = constraints.first
expect(constraints.length).to eql 1
expect(constraint.left.relation.name).to eql 'articles'
expect(constraint.left.name).to eql 'person_id'
expect(constraint.right.relation.name).to eql 'people'
expect(constraint.right.name).to eql 'id'
end
it 'build correlated subquery for multiple conditions (default scope)' do
search = Search.new(Person, { comments_body_not_eq: 'some_title' })
# Was
# SELECT "people".* FROM "people" WHERE "people"."id" NOT IN (
# SELECT "comments"."disabled" FROM "comments"
# WHERE "comments"."disabled" = "people"."id"
# AND NOT ("comments"."body" != 'some_title')
# ) ORDER BY "people"."id" DESC
# Should Be
# SELECT "people".* FROM "people" WHERE "people"."id" NOT IN (
# SELECT "comments"."person_id" FROM "comments"
# WHERE "comments"."person_id" = "people"."id"
# AND NOT ("comments"."body" != 'some_title')
# ) ORDER BY "people"."id" DESC
expect(search.result.to_sql).to match /.comments.\..person_id. = .people.\..id./
end
it 'handles Arel::Nodes::And with children' do
# Create a mock Arel::Nodes::And with children for testing
search = Search.new(Person, { articles_title_not_eq: 'some_title', articles_body_not_eq: 'some_body' }, context: subject)
attribute = search.conditions.first.attributes.first
constraints = subject.build_correlated_subquery(attribute.parent).constraints
constraint = constraints.first
expect(constraints.length).to eql 1
expect(constraint.left.name).to eql 'person_id'
expect(constraint.left.relation.name).to eql 'articles'
expect(constraint.right.name).to eql 'id'
expect(constraint.right.relation.name).to eql 'people'
end
it 'correctly extracts correlated key from complex AND conditions' do
# Test with multiple nested conditions to ensure the children traversal works
search = Search.new(
Person,
{
articles_title_not_eq: 'title',
articles_body_not_eq: 'body',
articles_published_eq: true
},
context: subject
)
attribute = search.conditions.first.attributes.first
constraints = subject.build_correlated_subquery(attribute.parent).constraints
constraint = constraints.first
expect(constraints.length).to eql 1
expect(constraint.left.relation.name).to eql 'articles'
expect(constraint.left.name).to eql 'person_id'
expect(constraint.right.relation.name).to eql 'people'
expect(constraint.right.name).to eql 'id'
end
it 'build correlated subquery for polymorphic & default_scope when predicate is not_cont_all' do
search = Search.new(Article,
g: [
{
m: "and",
c: [
{
a: ["recent_notes_note"],
p: "not_eq",
v: ["some_note"],
}
]
}
],
)
expect(search.result.to_sql).to match /(.notes.\..note. != \'some_note\')/
end
end
describe 'sharing context across searches' do
let(:shared_context) { Context.for(Person) }
before do
Search.new(Person, { parent_name_eq: 'A' },
context: shared_context)
Search.new(Person, { children_name_eq: 'B' },
context: shared_context)
end
describe '#join_sources' do
it 'returns dependent arel join nodes for all searches run against
the context' do
parents, children = shared_context.join_sources
expect(children.left.name).to eq "children_people"
expect(parents.left.name).to eq "parents_people"
end
it 'can be rejoined to execute a valid query' do
parents, children = shared_context.join_sources
expect { Person.joins(parents).joins(children).to_a }
.to_not raise_error
end
end
end
it 'contextualizes strings to attributes' do
attribute = subject.contextualize 'children_children_parent_name'
expect(attribute).to be_a Arel::Attributes::Attribute
expect(attribute.name.to_s).to eq 'name'
expect(attribute.relation.table_alias).to eq 'parents_people'
end
it 'builds new associations if not yet built' do
attribute = subject.contextualize 'children_articles_title'
expect(attribute).to be_a Arel::Attributes::Attribute
expect(attribute.name.to_s).to eq 'title'
expect(attribute.relation.name).to eq 'articles'
expect(attribute.relation.table_alias).to be_nil
end
describe '#type_for' do
it 'returns nil when column does not exist instead of raising NoMethodError' do
# Create a mock attribute that references a non-existent column
mock_attr = double('attribute')
allow(mock_attr).to receive(:valid?).and_return(true)
mock_arel_attr = double('arel_attribute')
allow(mock_arel_attr).to receive(:relation).and_return(Person.arel_table)
allow(mock_arel_attr).to receive(:name).and_return('nonexistent_column')
allow(mock_attr).to receive(:arel_attribute).and_return(mock_arel_attr)
allow(mock_attr).to receive(:klass).and_return(Person)
# This should return nil instead of raising an error
expect(subject.type_for(mock_attr)).to be_nil
end
end
end
end
end
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/spec/ransack/adapters/active_record/base_spec.rb | spec/ransack/adapters/active_record/base_spec.rb | require 'spec_helper'
module Ransack
module Adapters
module ActiveRecord
describe Base do
subject { ::ActiveRecord::Base }
it { should respond_to :ransack }
describe '#search' do
subject { Person.ransack }
it { should be_a Search }
it 'has a Relation as its object' do
expect(subject.object).to be_an ::ActiveRecord::Relation
end
context "multiple database connection" do
it "does not raise error" do
expect { Person.ransack(name_cont: "test") }.not_to raise_error
expect { SubDB::OperationHistory.ransack(people_id_eq: 1) }.not_to raise_error
end
end
context 'with scopes' do
before do
allow(Person)
.to receive(:ransackable_scopes)
.and_return([:active, :over_age, :of_age])
end
it 'applies true scopes' do
s = Person.ransack('active' => true)
expect(s.result.to_sql).to (include 'active = 1')
end
it 'applies stringy true scopes' do
s = Person.ransack('active' => 'true')
expect(s.result.to_sql).to (include 'active = 1')
end
it 'applies stringy boolean scopes with true value in an array' do
s = Person.ransack('of_age' => ['true'])
expect(s.result.to_sql).to (include rails7_and_mysql ? %q{(age >= '18')} : 'age >= 18')
end
it 'applies stringy boolean scopes with false value in an array' do
s = Person.ransack('of_age' => ['false'])
expect(s.result.to_sql).to (include rails7_and_mysql ? %q{age < '18'} : 'age < 18')
end
it 'ignores unlisted scopes' do
s = Person.ransack('restricted' => true)
expect(s.result.to_sql).to_not (include 'restricted')
end
it 'ignores false scopes' do
s = Person.ransack('active' => false)
expect(s.result.to_sql).not_to (include 'active')
end
it 'ignores stringy false scopes' do
s = Person.ransack('active' => 'false')
expect(s.result.to_sql).to_not (include 'active')
end
it 'passes values to scopes' do
s = Person.ransack('over_age' => 18)
expect(s.result.to_sql).to (include rails7_and_mysql ? %q{age > '18'} : 'age > 18')
end
it 'chains scopes' do
s = Person.ransack('over_age' => 18, 'active' => true)
expect(s.result.to_sql).to (include rails7_and_mysql ? %q{age > '18'} : 'age > 18')
expect(s.result.to_sql).to (include 'active = 1')
end
it 'applies scopes that define string SQL joins' do
allow(Article)
.to receive(:ransackable_scopes)
.and_return([:latest_comment_cont])
# Including a negative condition to test removing the scope
s = Search.new(Article, notes_note_not_eq: 'Test', latest_comment_cont: 'Test')
expect(s.result.to_sql).to include 'latest_comment'
end
context "with sanitize_custom_scope_booleans set to false" do
before(:all) do
Ransack.configure { |c| c.sanitize_custom_scope_booleans = false }
end
after(:all) do
Ransack.configure { |c| c.sanitize_custom_scope_booleans = true }
end
it 'passes true values to scopes' do
s = Person.ransack('over_age' => 1)
expect(s.result.to_sql).to (include rails7_and_mysql ? %q{age > '1'} : 'age > 1')
end
it 'passes false values to scopes' do
s = Person.ransack('over_age' => 0)
expect(s.result.to_sql).to (include rails7_and_mysql ? %q{age > '0'} : 'age > 0')
end
end
context "with ransackable_scopes_skip_sanitize_args enabled for scope" do
before do
allow(Person)
.to receive(:ransackable_scopes_skip_sanitize_args)
.and_return([:over_age])
end
it 'passes true values to scopes' do
s = Person.ransack('over_age' => 1)
expect(s.result.to_sql).to (include rails7_and_mysql ? %q{age > '1'} : 'age > 1')
end
it 'passes false values to scopes' do
s = Person.ransack('over_age' => 0)
expect(s.result.to_sql).to (include rails7_and_mysql ? %q{age > '0'} : 'age > 0')
end
end
end
it 'does not raise exception for string :params argument' do
expect { Person.ransack('') }.to_not raise_error
end
it 'raises ArgumentError exception if ransack! called with unknown condition' do
expect { Person.ransack!(unknown_attr_eq: 'Ernie') }.to raise_error(ArgumentError)
end
it 'raises InvalidSearchError exception if ransack! called with unknown condition' do
expect { Person.ransack!(unknown_attr_eq: 'Ernie') }.to raise_error(InvalidSearchError)
end
it 'does not modify the parameters' do
params = { name_eq: '' }
expect { Person.ransack(params) }.not_to change { params }
end
end
context 'has_one through associations' do
let(:address) { Address.create!(city: 'Boston') }
let(:org) { Organization.create!(name: 'Testorg', address: address) }
let!(:employee) { Employee.create!(name: 'Ernie', organization: org) }
it 'works when has_one through association is first' do
s = Employee.ransack(address_city_eq: 'Boston', organization_name_eq: 'Testorg')
expect(s.result.to_a).to include(employee)
end
it 'works when has_one through association is last' do
s = Employee.ransack(organization_name_eq: 'Testorg', address_city_eq: 'Boston')
expect(s.result.to_a).to include(employee)
end
end
context 'negative conditions on HABTM associations' do
let(:medieval) { Tag.create!(name: 'Medieval') }
let(:fantasy) { Tag.create!(name: 'Fantasy') }
let(:arthur) { Article.create!(title: 'King Arthur') }
let(:marco) { Article.create!(title: 'Marco Polo') }
before do
marco.tags << medieval
arthur.tags << medieval
arthur.tags << fantasy
end
it 'removes redundant joins from top query' do
s = Article.ransack(tags_name_not_eq: "Fantasy")
sql = s.result.to_sql
expect(sql).to_not include('LEFT OUTER JOIN')
end
it 'handles != for single values' do
s = Article.ransack(tags_name_not_eq: "Fantasy")
articles = s.result.to_a
expect(articles).to include marco
expect(articles).to_not include arthur
end
it 'handles NOT IN for multiple attributes' do
s = Article.ransack(tags_name_not_in: ["Fantasy", "Scifi"])
articles = s.result.to_a
expect(articles).to include marco
expect(articles).to_not include arthur
end
end
context 'negative conditions on related object with HABTM associations' do
let(:medieval) { Tag.create!(name: 'Medieval') }
let(:fantasy) { Tag.create!(name: 'Fantasy') }
let(:arthur) { Article.create!(title: 'King Arthur') }
let(:marco) { Article.create!(title: 'Marco Polo') }
let(:comment_arthur) { marco.comments.create!(body: 'King Arthur comment') }
let(:comment_marco) { arthur.comments.create!(body: 'Marco Polo comment') }
before do
comment_arthur.tags << medieval
comment_marco.tags << fantasy
end
it 'removes redundant joins from top query' do
s = Article.ransack(comments_tags_name_not_eq: "Fantasy")
sql = s.result.to_sql
expect(sql).to include('LEFT OUTER JOIN')
end
it 'handles != for single values' do
s = Article.ransack(comments_tags_name_not_eq: "Fantasy")
articles = s.result.to_a
expect(articles).to include marco
expect(articles).to_not include arthur
end
it 'handles NOT IN for multiple attributes' do
s = Article.ransack(comments_tags_name_not_in: ["Fantasy", "Scifi"])
articles = s.result.to_a
expect(articles).to include marco
expect(articles).to_not include arthur
end
end
context 'negative conditions on self-referenced associations' do
let(:pop) { Person.create!(name: 'Grandpa') }
let(:dad) { Person.create!(name: 'Father') }
let(:mom) { Person.create!(name: 'Mother') }
let(:son) { Person.create!(name: 'Grandchild') }
before do
son.parent = dad
dad.parent = pop
dad.children << son
mom.children << son
pop.children << dad
son.save! && dad.save! && mom.save! && pop.save!
end
it 'handles multiple associations and aliases' do
s = Person.ransack(
c: {
'0' => { a: ['name'], p: 'not_eq', v: ['Father'] },
'1' => {
a: ['children_name', 'parent_name'],
p: 'not_eq', v: ['Father'], m: 'or'
},
'2' => { a: ['children_salary'], p: 'eq', v: [nil] }
})
people = s.result
expect(people.to_a).to include son
expect(people.to_a).to include mom
expect(people.to_a).to_not include dad # rule '0': 'name'
expect(people.to_a).to_not include pop # rule '1': 'children_name'
end
end
describe '#ransack_alias' do
it 'translates an alias to the correct attributes' do
p = Person.create!(name: 'Meatloaf', email: 'babies@example.com')
s = Person.ransack(term_cont: 'atlo')
expect(s.result.to_a).to eq [p]
s = Person.ransack(term_cont: 'babi')
expect(s.result.to_a).to eq [p]
s = Person.ransack(term_cont: 'nomatch')
expect(s.result.to_a).to eq []
end
it 'also works with associations' do
dad = Person.create!(name: 'Birdman')
son = Person.create!(name: 'Weezy', parent: dad)
s = Person.ransack(daddy_eq: 'Birdman')
expect(s.result.to_a).to eq [son]
s = Person.ransack(daddy_eq: 'Drake')
expect(s.result.to_a).to eq []
end
it 'makes aliases available to subclasses' do
yngwie = Musician.create!(name: 'Yngwie Malmsteen')
musicians = Musician.ransack(term_cont: 'ngw').result
expect(musicians).to eq([yngwie])
end
it 'handles naming collisions gracefully' do
frank = Person.create!(name: 'Frank Stallone')
people = Person.ransack(term_cont: 'allon').result
expect(people).to eq([frank])
Class.new(Article) do
ransack_alias :term, :title
end
people = Person.ransack(term_cont: 'allon').result
expect(people).to eq([frank])
end
end
describe '#ransacker' do
# For infix tests
def self.sane_adapter?
case ::ActiveRecord::Base.connection.adapter_name
when 'SQLite3', 'PostgreSQL'
true
else
false
end
end
# in schema.rb, class Person:
# ransacker :reversed_name, formatter: proc { |v| v.reverse } do |parent|
# parent.table[:name]
# end
#
# ransacker :doubled_name do |parent|
# Arel::Nodes::InfixOperation.new(
# '||', parent.table[:name], parent.table[:name]
# )
# end
it 'creates ransack attributes' do
person = Person.create!(name: 'Aric Smith')
s = Person.ransack(reversed_name_eq: 'htimS cirA')
expect(s.result.size).to eq(1)
expect(s.result.first).to eq person
end
it 'can be accessed through associations' do
s = Person.ransack(children_reversed_name_eq: 'htimS cirA')
expect(s.result.to_sql).to match(
/#{quote_table_name("children_people")}.#{
quote_column_name("name")} = 'Aric Smith'/
)
end
it 'allows an attribute to be an InfixOperation' do
s = Person.ransack(doubled_name_eq: 'Aric SmithAric Smith')
expect(s.result.first).to eq Person.where(name: 'Aric Smith').first
end if defined?(Arel::Nodes::InfixOperation) && sane_adapter?
it 'does not break #count if using InfixOperations' do
s = Person.ransack(doubled_name_eq: 'Aric SmithAric Smith')
expect(s.result.count).to eq 1
end if defined?(Arel::Nodes::InfixOperation) && sane_adapter?
it 'should remove empty key value pairs from the params hash' do
s = Person.ransack(children_reversed_name_eq: '')
expect(s.result.to_sql).not_to match /LEFT OUTER JOIN/
end
it 'should keep proper key value pairs in the params hash' do
s = Person.ransack(children_reversed_name_eq: 'Testing')
expect(s.result.to_sql).to match /LEFT OUTER JOIN/
end
it 'should function correctly when nil is passed in' do
s = Person.ransack(nil)
end
it 'should function correctly when a blank string is passed in' do
s = Person.ransack('')
end
it 'should function correctly with a multi-parameter attribute' do
if ::ActiveRecord::VERSION::MAJOR >= 7
::ActiveRecord.default_timezone = :utc
else
::ActiveRecord::Base.default_timezone = :utc
end
Time.zone = 'UTC'
date = Date.current
s = Person.ransack(
{ 'created_at_gteq(1i)' => date.year,
'created_at_gteq(2i)' => date.month,
'created_at_gteq(3i)' => date.day
}
)
expect(s.result.to_sql).to match />=/
expect(s.result.to_sql).to match date.to_s
end
it 'should function correctly when using fields with dots in them' do
s = Person.ransack(email_cont: 'example.com')
expect(s.result.exists?).to be true
end
it 'should function correctly when using fields with % in them' do
p = Person.create!(name: '110%-er')
s = Person.ransack(name_cont: '10%')
expect(s.result.to_a).to eq [p]
end
it 'should function correctly when using fields with backslashes in them' do
p = Person.create!(name: "\\WINNER\\")
s = Person.ransack(name_cont: "\\WINNER\\")
expect(s.result.to_a).to eq [p]
end
if ::ActiveRecord::VERSION::MAJOR >= 7 && ActiveRecord::Base.respond_to?(:normalizes)
context 'with ActiveRecord::normalizes' do
around(:each) do |example|
# Create a temporary model class with normalization for testing
test_class = Class.new(ActiveRecord::Base) do
self.table_name = 'people'
normalizes :name, with: ->(name) { name.gsub(/[^a-z0-9]/, '_') }
def self.ransackable_attributes(auth_object = nil)
Person.ransackable_attributes(auth_object)
end
def self.name
'TestPersonWithNormalization'
end
end
stub_const('TestPersonWithNormalization', test_class)
example.run
end
it 'should not apply normalization to LIKE wildcards for cont predicate' do
# Create a person with characters that would be normalized
p = TestPersonWithNormalization.create!(name: 'foo%bar')
expect(p.reload.name).to eq('foo_bar') # Verify normalization happened on storage
# Search should find the person using the original search term
s = TestPersonWithNormalization.ransack(name_cont: 'foo')
expect(s.result.to_a).to eq [p]
# Verify the SQL contains proper LIKE wildcards, not normalized ones
sql = s.result.to_sql
expect(sql).to include("LIKE '%foo%'")
expect(sql).not_to include("LIKE '_foo_'")
end
it 'should not apply normalization to LIKE wildcards for other LIKE predicates' do
p = TestPersonWithNormalization.create!(name: 'foo%bar')
# Test start predicate
s = TestPersonWithNormalization.ransack(name_start: 'foo')
expect(s.result.to_a).to eq [p]
expect(s.result.to_sql).to include("LIKE 'foo%'")
# Test end predicate
s = TestPersonWithNormalization.ransack(name_end: 'bar')
expect(s.result.to_a).to eq [p]
expect(s.result.to_sql).to include("LIKE '%bar'")
# Test i_cont predicate
s = TestPersonWithNormalization.ransack(name_i_cont: 'FOO')
expect(s.result.to_a).to eq [p]
expect(s.result.to_sql).to include("LIKE '%foo%'")
end
end
end
context 'searching by underscores' do
# when escaping is supported right in LIKE expression without adding extra expressions
def self.simple_escaping?
case ::ActiveRecord::Base.connection.adapter_name
when 'Mysql2', 'PostgreSQL'
true
else
false
end
end
it 'should search correctly if matches exist' do
p = Person.create!(name: 'name_with_underscore')
s = Person.ransack(name_cont: 'name_')
expect(s.result.to_a).to eq [p]
end if simple_escaping?
it 'should return empty result if no matches' do
Person.create!(name: 'name_with_underscore')
s = Person.ransack(name_cont: 'n_')
expect(s.result.to_a).to eq []
end if simple_escaping?
end
context 'searching on an `in` predicate with a ransacker' do
it 'should function correctly when passing an array of ids' do
s = Person.ransack(array_people_ids_in: true)
expect(s.result.count).to be > 0
s = Person.ransack(array_where_people_ids_in: [1, '2', 3])
expect(s.result.count).to be 3
expect(s.result.map(&:id)).to eq [3, 2, 1]
end
it 'should function correctly with HABTM associations' do
article = Article.first
tag = article.tags.first
s = Person.ransack(article_tags_in: [tag.id])
expect(s.result.count).to be 1
expect(s.result.map(&:id)).to eq [article.person.id]
end
it 'should function correctly when passing an array of strings' do
a, b = Person.select(:id).order(:id).limit(2).map { |a| a.id.to_s }
Person.create!(name: a)
s = Person.ransack(array_people_names_in: true)
expect(s.result.count).to be > 0
s = Person.ransack(array_where_people_names_in: a)
expect(s.result.count).to be 1
Person.create!(name: b)
s = Person.ransack(array_where_people_names_in: [a, b])
expect(s.result.count).to be 2
end
it 'should function correctly with an Arel SqlLiteral' do
s = Person.ransack(sql_literal_id_in: 1)
expect(s.result.count).to be 1
s = Person.ransack(sql_literal_id_in: ['2', 4, '5', 8])
expect(s.result.count).to be 4
end
end
context 'search on an `in` predicate with an array' do
it 'should function correctly when passing an array of ids' do
array = Person.all.map(&:id)
s = Person.ransack(id_in: array)
expect(s.result.count).to eq array.size
end
end
it 'should work correctly when an attribute name ends with _start' do
p = Person.create!(new_start: 'Bar and foo', name: 'Xiang')
s = Person.ransack(new_start_end: ' and foo')
expect(s.result.to_a).to eq [p]
s = Person.ransack(name_or_new_start_start: 'Xia')
expect(s.result.to_a).to eq [p]
s = Person.ransack(new_start_or_name_end: 'iang')
expect(s.result.to_a).to eq [p]
end
it 'should work correctly when an attribute name ends with _end' do
p = Person.create!(stop_end: 'Foo and bar', name: 'Marianne')
s = Person.ransack(stop_end_start: 'Foo and')
expect(s.result.to_a).to eq [p]
s = Person.ransack(stop_end_or_name_end: 'anne')
expect(s.result.to_a).to eq [p]
s = Person.ransack(name_or_stop_end_end: ' bar')
expect(s.result.to_a).to eq [p]
end
it 'should work correctly when an attribute name has `and` in it' do
p = Person.create!(terms_and_conditions: true)
s = Person.ransack(terms_and_conditions_eq: true)
expect(s.result.to_a).to eq [p]
end
context 'attribute aliased column names',
if: Ransack::SUPPORTS_ATTRIBUTE_ALIAS do
it 'should be translated to original column name' do
s = Person.ransack(full_name_eq: 'Nicolas Cage')
expect(s.result.to_sql).to match(
/WHERE #{quote_table_name("people")}.#{quote_column_name("name")}/
)
end
it 'should translate on associations' do
s = Person.ransack(articles_content_cont: 'Nicolas Cage')
expect(s.result.to_sql).to match(
/#{quote_table_name("articles")}.#{
quote_column_name("body")} I?LIKE '%Nicolas Cage%'/
)
end
end
it 'sorts with different join variants' do
comments = [
Comment.create(article: Article.create(title: 'Avenger'), person: Person.create(salary: 100_000)),
Comment.create(article: Article.create(title: 'Avenge'), person: Person.create(salary: 50_000)),
]
expect(Comment.ransack(article_title_cont: 'aven', s: 'person_salary desc').result).to eq(comments)
expect(Comment.joins(:person).ransack(s: 'persons_salarydesc', article_title_cont: 'aven').result).to eq(comments)
expect(Comment.joins(:person).ransack(article_title_cont: 'aven', s: 'persons_salary desc').result).to eq(comments)
end
it 'allows sort by `only_sort` field' do
s = Person.ransack(
's' => { '0' => { 'dir' => 'asc', 'name' => 'only_sort' } }
)
expect(s.result.to_sql).to match(
/ORDER BY #{quote_table_name("people")}.#{
quote_column_name("only_sort")} ASC/
)
end
it 'does not sort by `only_search` field' do
s = Person.ransack(
's' => { '0' => { 'dir' => 'asc', 'name' => 'only_search' } }
)
expect(s.result.to_sql).not_to match(
/ORDER BY #{quote_table_name("people")}.#{
quote_column_name("only_search")} ASC/
)
end
it 'allows search by `only_search` field' do
s = Person.ransack(only_search_eq: 'htimS cirA')
expect(s.result.to_sql).to match(
/WHERE #{quote_table_name("people")}.#{
quote_column_name("only_search")} = 'htimS cirA'/
)
end
it 'cannot be searched by `only_sort`' do
s = Person.ransack(only_sort_eq: 'htimS cirA')
expect(s.result.to_sql).not_to match(
/WHERE #{quote_table_name("people")}.#{
quote_column_name("only_sort")} = 'htimS cirA'/
)
end
it 'allows sort by `only_admin` field, if auth_object: :admin' do
s = Person.ransack(
{ 's' => { '0' => { 'dir' => 'asc', 'name' => 'only_admin' } } },
{ auth_object: :admin }
)
expect(s.result.to_sql).to match(
/ORDER BY #{quote_table_name("people")}.#{
quote_column_name("only_admin")} ASC/
)
end
it 'does not sort by `only_admin` field, if auth_object: nil' do
s = Person.ransack(
's' => { '0' => { 'dir' => 'asc', 'name' => 'only_admin' } }
)
expect(s.result.to_sql).not_to match(
/ORDER BY #{quote_table_name("people")}.#{
quote_column_name("only_admin")} ASC/
)
end
it 'allows search by `only_admin` field, if auth_object: :admin' do
s = Person.ransack(
{ only_admin_eq: 'htimS cirA' },
{ auth_object: :admin }
)
expect(s.result.to_sql).to match(
/WHERE #{quote_table_name("people")}.#{
quote_column_name("only_admin")} = 'htimS cirA'/
)
end
it 'cannot be searched by `only_admin`, if auth_object: nil' do
s = Person.ransack(only_admin_eq: 'htimS cirA')
expect(s.result.to_sql).not_to match(
/WHERE #{quote_table_name("people")}.#{
quote_column_name("only_admin")} = 'htimS cirA'/
)
end
it 'should allow passing ransacker arguments to a ransacker' do
s = Person.ransack(
c: [{
a: {
'0' => {
name: 'with_arguments', ransacker_args: [10, 100]
}
},
p: 'cont',
v: ['Passing arguments to ransackers!']
}]
)
expect(s.result.to_sql).to match(
/LENGTH\(articles.body\) BETWEEN 10 AND 100/
)
expect(s.result.to_sql).to match(
/LIKE \'\%Passing arguments to ransackers!\%\'/
)
expect { s.result.first }.to_not raise_error
end
it 'should allow sort passing arguments to a ransacker' do
s = Person.ransack(
s: {
'0' => {
name: 'with_arguments', dir: 'desc', ransacker_args: [2, 6]
}
}
)
expect(s.result.to_sql).to match(
/ORDER BY \(SELECT MAX\(articles.title\) FROM articles/
)
expect(s.result.to_sql).to match(
/WHERE articles.person_id = people.id AND LENGTH\(articles.body\)/
)
expect(s.result.to_sql).to match(
/BETWEEN 2 AND 6 GROUP BY articles.person_id \) DESC/
)
end
context 'case insensitive sorting' do
it 'allows sort by desc' do
search = Person.ransack(sorts: ['name_case_insensitive desc'])
expect(search.result.to_sql).to match /ORDER BY LOWER(.*) DESC/
end
it 'allows sort by asc' do
search = Person.ransack(sorts: ['name_case_insensitive asc'])
expect(search.result.to_sql).to match /ORDER BY LOWER(.*) ASC/
end
end
context 'ransacker with different types' do
it 'handles string type ransacker correctly' do
s = Person.ransack(name_case_insensitive_eq: 'test')
expect(s.result.to_sql).to match(/LOWER\(.*\) = 'test'/)
end
it 'handles integer type ransacker correctly' do
s = Person.ransack(sql_literal_id_eq: 1)
expect(s.result.to_sql).to match(/people\.id = 1/)
end
end
context 'ransacker with formatter returning nil' do
it 'handles formatter returning nil gracefully' do
# This tests the edge case where a formatter might return nil
s = Person.ransack(article_tags_eq: 999999) # Non-existent tag ID
expect { s.result.to_sql }.not_to raise_error
end
end
context 'ransacker with array formatters' do
it 'handles array_people_ids formatter correctly' do
person1 = Person.create!(name: 'Test1')
person2 = Person.create!(name: 'Test2')
s = Person.ransack(array_people_ids_eq: 'test')
expect { s.result }.not_to raise_error
end
it 'handles array_where_people_ids formatter correctly' do
person1 = Person.create!(name: 'Test1')
person2 = Person.create!(name: 'Test2')
s = Person.ransack(array_where_people_ids_eq: [person1.id, person2.id])
expect { s.result }.not_to raise_error
end
end
context 'regular sorting' do
it 'allows sort by desc' do
search = Person.ransack(sorts: ['name desc'])
expect(search.result.to_sql).to match /ORDER BY .* DESC/
end
it 'allows sort by asc' do
search = Person.ransack(sorts: ['name asc'])
expect(search.result.to_sql).to match /ORDER BY .* ASC/
end
end
context 'sorting by a scope' do
it 'applies the correct scope' do
search = Person.ransack(sorts: ['reverse_name asc'])
expect(search.result.to_sql).to include("ORDER BY REVERSE(name) ASC")
end
end
end
describe '#ransackable_attributes' do
context 'when auth_object is nil' do
subject { Person.ransackable_attributes }
it { should include 'name' }
it { should include 'reversed_name' }
it { should include 'doubled_name' }
it { should include 'term' }
it { should include 'only_search' }
it { should_not include 'only_sort' }
it { should_not include 'only_admin' }
if Ransack::SUPPORTS_ATTRIBUTE_ALIAS
it { should include 'full_name' }
end
end
context 'with auth_object :admin' do
subject { Person.ransackable_attributes(:admin) }
it { should include 'name' }
it { should include 'reversed_name' }
it { should include 'doubled_name' }
it { should include 'only_search' }
it { should_not include 'only_sort' }
it { should include 'only_admin' }
end
context 'when not defined in model, nor in ApplicationRecord' do
subject { Article.ransackable_attributes }
it "raises a helpful error" do
without_application_record_method(:ransackable_attributes) do
expect { subject }.to raise_error(RuntimeError, /Ransack needs Article attributes explicitly allowlisted/)
end
end
end
context 'when defined only in model by delegating to super' do
subject { Article.ransackable_attributes }
around do |example|
Article.singleton_class.define_method(:ransackable_attributes) do
super(nil) - super(nil)
end
example.run
ensure
Article.singleton_class.remove_method(:ransackable_attributes)
end
it "returns the allowlist in the model, and warns" do
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | true |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/spec/polyamorous/activerecord_compatibility_spec.rb | spec/polyamorous/activerecord_compatibility_spec.rb | require 'spec_helper'
module Polyamorous
describe "ActiveRecord Compatibility" do
it 'works with self joins and includes' do
trade_account = Account.create!
Account.create!(trade_account: trade_account)
accounts = Account.joins(:trade_account).includes(:trade_account, :agent_account)
account = accounts.first
expect(account.agent_account).to be_nil
end
end
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/spec/polyamorous/join_association_spec.rb | spec/polyamorous/join_association_spec.rb | require 'spec_helper'
module Polyamorous
describe JoinAssociation do
let(:join_dependency) { new_join_dependency Note, {} }
let(:reflection) { Note.reflect_on_association(:notable) }
let(:parent) { join_dependency.send(:join_root) }
let(:join_association) {
new_join_association(reflection, parent.children, Article)
}
subject { new_join_association(reflection, parent.children, Person) }
it 'leaves the original reflection intact for thread safety' do
reflection.instance_variable_set(:@klass, Article)
join_association
.swapping_reflection_klass(reflection, Person) do |new_reflection|
expect(new_reflection.options).not_to equal reflection.options
expect(new_reflection.options).not_to have_key(:polymorphic)
expect(new_reflection.klass).to eq(Person)
expect(reflection.klass).to eq(Article)
end
end
it 'sets the polymorphic option to true after initializing' do
expect(join_association.reflection.options[:polymorphic]).to be true
end
end
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/spec/polyamorous/join_spec.rb | spec/polyamorous/join_spec.rb | require 'spec_helper'
module Polyamorous
describe Join do
it 'is a tree node' do
join = new_join(:articles, :outer)
expect(join).to be_kind_of(TreeNode)
end
it 'can be added to a tree' do
join = new_join(:articles, :outer)
tree_hash = {}
join.add_to_tree(tree_hash)
expect(tree_hash[join]).to be {}
end
end
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/spec/polyamorous/join_dependency_spec.rb | spec/polyamorous/join_dependency_spec.rb | require 'spec_helper'
module Polyamorous
describe JoinDependency do
context 'with symbol joins' do
subject { new_join_dependency Person, articles: :comments }
specify { expect(subject.send(:join_root).drop(1).size)
.to eq(2) }
specify { expect(subject.send(:join_root).drop(1).map(&:join_type).uniq)
.to eq [Polyamorous::InnerJoin] }
end
context 'with has_many :through association' do
subject { new_join_dependency Person, :authored_article_comments }
specify { expect(subject.send(:join_root).drop(1).size)
.to eq 1 }
specify { expect(subject.send(:join_root).drop(1).first.table_name)
.to eq 'comments' }
end
context 'with outer join' do
subject { new_join_dependency Person, new_join(:articles, :outer) }
specify { expect(subject.send(:join_root).drop(1).size)
.to eq 1 }
specify { expect(subject.send(:join_root).drop(1).first.join_type)
.to eq Polyamorous::OuterJoin }
end
context 'with nested outer joins' do
subject { new_join_dependency Person,
new_join(:articles, :outer) => new_join(:comments, :outer) }
specify { expect(subject.send(:join_root).drop(1).size)
.to eq 2 }
specify { expect(subject.send(:join_root).drop(1).map(&:join_type))
.to eq [Polyamorous::OuterJoin, Polyamorous::OuterJoin] }
specify { expect(subject.send(:join_root).drop(1).map(&:join_type).uniq)
.to eq [Polyamorous::OuterJoin] }
end
context 'with polymorphic belongs_to join' do
subject { new_join_dependency Note, new_join(:notable, :inner, Person) }
specify { expect(subject.send(:join_root).drop(1).size)
.to eq 1 }
specify { expect(subject.send(:join_root).drop(1).first.join_type)
.to eq Polyamorous::InnerJoin }
specify { expect(subject.send(:join_root).drop(1).first.table_name)
.to eq 'people' }
end
context 'with polymorphic belongs_to join and nested symbol join' do
subject { new_join_dependency Note,
new_join(:notable, :inner, Person) => :comments }
specify { expect(subject.send(:join_root).drop(1).size)
.to eq 2 }
specify { expect(subject.send(:join_root).drop(1).map(&:join_type).uniq)
.to eq [Polyamorous::InnerJoin] }
specify { expect(subject.send(:join_root).drop(1).first.table_name)
.to eq 'people' }
specify { expect(subject.send(:join_root).drop(1)[1].table_name)
.to eq 'comments' }
end
context 'with polymorphic belongs_to join and nested join' do
subject { new_join_dependency Note,
new_join(:notable, :outer, Person) => :comments }
specify { expect(subject.send(:join_root).drop(1).size).to eq 2 }
specify { expect(subject.send(:join_root).drop(1).map(&:join_type)).to eq [Polyamorous::OuterJoin, Polyamorous::InnerJoin] }
specify { expect(subject.send(:join_root).drop(1).first.table_name)
.to eq 'people' }
specify { expect(subject.send(:join_root).drop(1)[1].table_name)
.to eq 'comments' }
end
end
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/lib/ransack.rb | lib/ransack.rb | require 'active_support/dependencies/autoload'
require 'active_support/deprecation'
require 'active_support/deprecator'
require 'active_support/core_ext'
require 'ransack/configuration'
require 'polyamorous/polyamorous'
module Ransack
extend Configuration
class UntraversableAssociationError < StandardError; end
end
Ransack.configure do |config|
Ransack::Constants::AREL_PREDICATES.each do |name|
config.add_predicate name, arel_predicate: name
end
Ransack::Constants::DERIVED_PREDICATES.each do |args|
config.add_predicate(*args)
end
end
require 'ransack/search'
require 'ransack/ransacker'
require 'ransack/translate'
require 'ransack/active_record'
require 'ransack/context'
require 'ransack/version'
ActiveSupport.on_load(:action_controller) do
require 'ransack/helpers'
ActionController::Base.helper Ransack::Helpers::FormHelper
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/lib/ransack/active_record.rb | lib/ransack/active_record.rb | require 'ransack/adapters/active_record/base'
ActiveSupport.on_load(:active_record) do
extend Ransack::Adapters::ActiveRecord::Base
Ransack::SUPPORTS_ATTRIBUTE_ALIAS =
begin
ActiveRecord::Base.respond_to?(:attribute_aliases)
rescue NameError
false
end
end
require 'ransack/adapters/active_record/context'
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/lib/ransack/predicate.rb | lib/ransack/predicate.rb | module Ransack
class Predicate
attr_reader :name, :arel_predicate, :type, :formatter, :validator,
:compound, :wants_array, :case_insensitive
class << self
def names
Ransack.predicates.keys
end
def named(name)
Ransack.predicates[(name || Ransack.options[:default_predicate]).to_s]
end
def detect_and_strip_from_string!(str)
detect_from_string str, chomp: true
end
def detect_from_string(str, chomp: false)
return unless str
Ransack.predicates.sorted_names_with_underscores.each do |predicate, underscored|
if str.end_with? underscored
str.chomp! underscored if chomp
return predicate
end
end
nil
end
end
def initialize(opts = {})
@name = opts[:name]
@arel_predicate = opts[:arel_predicate]
@type = opts[:type]
@formatter = opts[:formatter]
@validator = opts[:validator] ||
lambda { |v| v.respond_to?(:empty?) ? !v.empty? : !v.nil? }
@compound = opts[:compound]
@wants_array = opts.fetch(:wants_array,
@compound || Constants::IN_NOT_IN.include?(@arel_predicate))
@case_insensitive = opts[:case_insensitive]
end
def eql?(other)
self.class == other.class &&
self.name == other.name
end
alias :== :eql?
def hash
name.hash
end
def format(val)
if formatter
formatter.call(val)
else
val
end
end
def validate(vals, type = @type)
vals.any? { |v| validator.call(type ? v.cast(type) : v.value) }
end
def negative?
@name.include?("not_".freeze)
end
end
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/lib/ransack/ransacker.rb | lib/ransack/ransacker.rb | module Ransack
class Ransacker
attr_reader :name, :type, :formatter, :args
delegate :call, to: :@callable
def initialize(klass, name, opts = {}, &block)
@klass, @name = klass, name
@type = opts[:type] || :string
@args = opts[:args] || [:parent]
@formatter = opts[:formatter]
@callable = opts[:callable] || block ||
(@klass.method(name) if @klass.respond_to?(name)) ||
proc { |parent| parent.table[name] }
end
def attr_from(bindable)
call(*args.map { |arg| bindable.send(arg) })
end
end
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/lib/ransack/version.rb | lib/ransack/version.rb | module Ransack
VERSION = '4.4.1'
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/lib/ransack/translate.rb | lib/ransack/translate.rb | require 'i18n'
I18n.load_path += Dir[
File.join(File.dirname(__FILE__), 'locale'.freeze, '*.yml'.freeze)
]
module Ransack
module Translate
class << self
def word(key, options = {})
I18n.translate(:"ransack.#{key}", default: key.to_s)
end
def predicate(key, options = {})
I18n.translate(:"ransack.predicates.#{key}", default: key.to_s)
end
def attribute(key, options = {})
unless context = options.delete(:context)
raise ArgumentError, "A context is required to translate attributes"
end
original_name = key.to_s
base_class = context.klass
base_ancestors = base_class.ancestors.select {
|x| x.respond_to?(:model_name)
}
attributes_str = original_name.dup # will be modified by ⬇
predicate = Predicate.detect_and_strip_from_string!(attributes_str)
attribute_names = attributes_str.split(/_and_|_or_/)
combinator = attributes_str =~ /_and_/ ? :and : :or
defaults = base_ancestors.map do |klass|
"ransack.attributes.#{i18n_key(klass)}.#{original_name}".to_sym
end
defaults << options.delete(:default) if options[:default]
translated_names = attribute_names.map do |name|
attribute_name(context, name, options[:include_associations])
end
interpolations = {
attributes: translated_names.join(" #{Translate.word(combinator)} ")
}
if predicate
defaults << "%{attributes} %{predicate}".freeze
interpolations[:predicate] = Translate.predicate(predicate)
else
defaults << "%{attributes}".freeze
end
options.reverse_merge! count: 1, default: defaults
I18n.translate(defaults.shift, **options.merge(interpolations))
end
def association(key, options = {})
unless context = options.delete(:context)
raise ArgumentError, "A context is required to translate associations"
end
defaults =
if key.blank?
[:"ransack.models.#{i18n_key(context.klass)}",
:"#{context.klass.i18n_scope}.models.#{i18n_key(context.klass)}"]
else
[:"ransack.associations.#{i18n_key(context.klass)}.#{key}"]
end
defaults << context.traverse(key).model_name.human
options = { count: 1, default: defaults }
I18n.translate(defaults.shift, **options)
end
private
def attribute_name(context, name, include_associations = nil)
@context, @name = context, name
@assoc_path = context.association_path(name)
@attr_name = @name.sub(/^#{@assoc_path}_/, ''.freeze)
associated_class = @context.traverse(@assoc_path) if @assoc_path.present?
@include_associated = include_associations && associated_class
defaults = default_attribute_name << fallback_args
options = { count: 1, default: defaults }
interpolations = build_interpolations(associated_class)
I18n.translate(defaults.shift, **options.merge(interpolations))
end
def default_attribute_name
["ransack.attributes.#{i18n_key(@context.klass)}.#{@name}".to_sym]
end
def fallback_args
if @include_associated
'%{association_name} %{attr_fallback_name}'.freeze
else
'%{attr_fallback_name}'.freeze
end
end
def build_interpolations(associated_class)
{
attr_fallback_name: attr_fallback_name(associated_class),
association_name: association_name
}.reject { |_, value| value.nil? }
end
def attr_fallback_name(associated_class)
I18n.t(
:"ransack.attributes.#{fallback_class(associated_class)}.#{@attr_name}",
default: default_interpolation(associated_class)
)
end
def fallback_class(associated_class)
i18n_key(associated_class || @context.klass)
end
def association_name
association(@assoc_path, context: @context) if @include_associated
end
def default_interpolation(associated_class)
[
associated_attribute(associated_class),
".attributes.#{@attr_name}".to_sym,
@attr_name.humanize
].flatten
end
def associated_attribute(associated_class)
if associated_class
translated_attribute(associated_class)
else
translated_ancestor_attributes
end
end
def translated_attribute(associated_class)
key = "#{associated_class.i18n_scope}.attributes.#{
i18n_key(associated_class)}.#{@attr_name}"
["#{key}.one".to_sym, key.to_sym]
end
def translated_ancestor_attributes
@context.klass.ancestors
.select { |ancestor| ancestor.respond_to?(:model_name) }
.map { |ancestor| translated_attribute(ancestor) }
end
def i18n_key(klass)
klass.model_name.i18n_key
end
end
end
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/lib/ransack/invalid_search_error.rb | lib/ransack/invalid_search_error.rb | module Ransack
class InvalidSearchError < ArgumentError; end
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/lib/ransack/constants.rb | lib/ransack/constants.rb | module Ransack
module Constants
OR = 'or'.freeze
AND = 'and'.freeze
CAP_SEARCH = 'Search'.freeze
SEARCH = 'search'.freeze
SEARCHES = 'searches'.freeze
ATTRIBUTE = 'attribute'.freeze
ATTRIBUTES = 'attributes'.freeze
COMBINATOR = 'combinator'.freeze
TWO_COLONS = '::'.freeze
UNDERSCORE = '_'.freeze
LEFT_PARENTHESIS = '('.freeze
Q = 'q'.freeze
I = 'i'.freeze
DOT_ASTERIX = '.*'.freeze
STRING_JOIN = 'string_join'.freeze
ASSOCIATION_JOIN = 'association_join'.freeze
STASHED_JOIN = 'stashed_join'.freeze
JOIN_NODE = 'join_node'.freeze
TRUE_VALUES = [true, 1, '1', 't', 'T', 'true', 'TRUE'].to_set
FALSE_VALUES = [false, 0, '0', 'f', 'F', 'false', 'FALSE'].to_set
BOOLEAN_VALUES = (TRUE_VALUES + FALSE_VALUES).freeze
AND_OR = ['and'.freeze, 'or'.freeze].freeze
IN_NOT_IN = ['in'.freeze, 'not_in'.freeze].freeze
SUFFIXES = ['_any'.freeze, '_all'.freeze].freeze
AREL_PREDICATES = [
'eq'.freeze, 'not_eq'.freeze,
'matches'.freeze, 'does_not_match'.freeze,
'lt'.freeze, 'lteq'.freeze,
'gt'.freeze, 'gteq'.freeze,
'in'.freeze, 'not_in'.freeze
].freeze
A_S_I = ['a'.freeze, 's'.freeze, 'i'.freeze].freeze
EQ = 'eq'.freeze
NOT_EQ = 'not_eq'.freeze
EQ_ANY = 'eq_any'.freeze
NOT_EQ_ALL = 'not_eq_all'.freeze
CONT = 'cont'.freeze
RANSACK_SLASH_SEARCHES = 'ransack/searches'.freeze
RANSACK_SLASH_SEARCHES_SLASH_SEARCH = 'ransack/searches/search'.freeze
DISTINCT = 'DISTINCT '.freeze
DERIVED_PREDICATES = [
[CONT, {
arel_predicate: 'matches'.freeze,
formatter: proc { |v| "%#{escape_wildcards(v)}%" }
}
],
['not_cont'.freeze, {
arel_predicate: 'does_not_match'.freeze,
formatter: proc { |v| "%#{escape_wildcards(v)}%" }
}
],
['i_cont'.freeze, {
arel_predicate: 'matches'.freeze,
formatter: proc { |v| "%#{escape_wildcards(v.downcase)}%" },
case_insensitive: true
}
],
['not_i_cont'.freeze, {
arel_predicate: 'does_not_match'.freeze,
formatter: proc { |v| "%#{escape_wildcards(v.downcase)}%" },
case_insensitive: true
}
],
['start'.freeze, {
arel_predicate: 'matches'.freeze,
formatter: proc { |v| "#{escape_wildcards(v)}%" }
}
],
['not_start'.freeze, {
arel_predicate: 'does_not_match'.freeze,
formatter: proc { |v| "#{escape_wildcards(v)}%" }
}
],
['end'.freeze, {
arel_predicate: 'matches'.freeze,
formatter: proc { |v| "%#{escape_wildcards(v)}" }
}
],
['not_end'.freeze, {
arel_predicate: 'does_not_match'.freeze,
formatter: proc { |v| "%#{escape_wildcards(v)}" }
}
],
['true'.freeze, {
arel_predicate: proc { |v| v ? EQ : NOT_EQ },
compounds: false,
type: :boolean,
validator: proc { |v| BOOLEAN_VALUES.include?(v) },
formatter: proc { |v| true }
}
],
['not_true'.freeze, {
arel_predicate: proc { |v| v ? NOT_EQ : EQ },
compounds: false,
type: :boolean,
validator: proc { |v| BOOLEAN_VALUES.include?(v) },
formatter: proc { |v| true }
}
],
['false'.freeze, {
arel_predicate: proc { |v| v ? EQ : NOT_EQ },
compounds: false,
type: :boolean,
validator: proc { |v| BOOLEAN_VALUES.include?(v) },
formatter: proc { |v| false }
}
],
['not_false'.freeze, {
arel_predicate: proc { |v| v ? NOT_EQ : EQ },
compounds: false,
type: :boolean,
validator: proc { |v| BOOLEAN_VALUES.include?(v) },
formatter: proc { |v| false }
}
],
['present'.freeze, {
arel_predicate: proc { |v| v ? NOT_EQ_ALL : EQ_ANY },
compounds: false,
type: :boolean,
validator: proc { |v| BOOLEAN_VALUES.include?(v) },
formatter: proc { |v| [nil, ''.freeze].freeze }
}
],
['blank'.freeze, {
arel_predicate: proc { |v| v ? EQ_ANY : NOT_EQ_ALL },
compounds: false,
type: :boolean,
validator: proc { |v| BOOLEAN_VALUES.include?(v) },
formatter: proc { |v| [nil, ''.freeze].freeze }
}
],
['null'.freeze, {
arel_predicate: proc { |v| v ? EQ : NOT_EQ },
compounds: false,
type: :boolean,
validator: proc { |v| BOOLEAN_VALUES.include?(v) },
formatter: proc { |v| nil }
}
],
['not_null'.freeze, {
arel_predicate: proc { |v| v ? NOT_EQ : EQ },
compounds: false,
type: :boolean,
validator: proc { |v| BOOLEAN_VALUES.include?(v) },
formatter: proc { |v| nil } }
]
].freeze
module_function
# replace % \ to \% \\
def escape_wildcards(unescaped)
case ActiveRecord::Base.connection.adapter_name
when "Mysql2".freeze
# Necessary for MySQL
unescaped.to_s.gsub(/([\\%_])/, '\\\\\\1')
when "PostGIS".freeze, "PostgreSQL".freeze
# Necessary for PostgreSQL
unescaped.to_s.gsub(/([\\%_.])/, '\\\\\\1')
else
unescaped
end
end
end
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/lib/ransack/search.rb | lib/ransack/search.rb | require 'ransack/nodes/bindable'
require 'ransack/nodes/node'
require 'ransack/nodes/attribute'
require 'ransack/nodes/value'
require 'ransack/nodes/condition'
require 'ransack/nodes/sort'
require 'ransack/nodes/grouping'
require 'ransack/context'
require 'ransack/naming'
require 'ransack/invalid_search_error'
module Ransack
class Search
include Naming
attr_reader :base, :context
delegate :object, :klass, to: :context
delegate :new_grouping, :new_condition,
:build_grouping, :build_condition,
:translate, to: :base
def initialize(object, params = {}, options = {})
strip_whitespace = options.fetch(:strip_whitespace, Ransack.options[:strip_whitespace])
params = params.to_unsafe_h if params.respond_to?(:to_unsafe_h)
if params.is_a? Hash
params = params.dup
params = params.transform_values { |v| v.is_a?(String) && strip_whitespace ? v.strip : v }
params.delete_if { |k, v| [*v].all?{ |i| i.blank? && i != false } }
else
params = {}
end
@context = options[:context] || Context.for(object, options)
@context.auth_object = options[:auth_object]
@base = Nodes::Grouping.new(
@context, options[:grouping] || Constants::AND
)
@scope_args = {}
@sorts ||= []
@ignore_unknown_conditions = options[:ignore_unknown_conditions] == false ? false : true
build(params.with_indifferent_access)
end
def result(opts = {})
@context.evaluate(self, opts)
end
def build(params)
collapse_multiparameter_attributes!(params).each do |key, value|
if ['s'.freeze, 'sorts'.freeze].freeze.include?(key)
send("#{key}=", value)
elsif @context.ransackable_scope?(key, @context.object)
add_scope(key, value)
elsif base.attribute_method?(key)
base.send("#{key}=", value)
elsif !Ransack.options[:ignore_unknown_conditions] || !@ignore_unknown_conditions
raise InvalidSearchError, "Invalid search term #{key}"
end
end
self
end
def sorts=(args)
case args
when Array
args.each do |sort|
if sort.kind_of? Hash
sort = Nodes::Sort.new(@context).build(sort)
else
sort = Nodes::Sort.extract(@context, sort)
end
self.sorts << sort if sort
end
when Hash
args.each do |index, attrs|
sort = Nodes::Sort.new(@context).build(attrs)
self.sorts << sort
end
when String
self.sorts = [args]
else
raise InvalidSearchError,
"Invalid argument (#{args.class}) supplied to sorts="
end
end
alias :s= :sorts=
def sorts
@sorts
end
alias :s :sorts
def build_sort(opts = {})
new_sort(opts).tap do |sort|
self.sorts << sort
end
end
def new_sort(opts = {})
Nodes::Sort.new(@context).build(opts)
end
def method_missing(method_id, *args)
method_name = method_id.to_s
getter_name = method_name.sub(/=$/, ''.freeze)
if base.attribute_method?(getter_name)
base.send(method_id, *args)
elsif @context.ransackable_scope?(getter_name, @context.object)
if method_name =~ /=$/
add_scope getter_name, args
else
@scope_args[method_name]
end
else
super
end
end
def inspect
details = [
[:class, klass.name],
([:scope, @scope_args] if @scope_args.present?),
[:base, base.inspect]
]
.compact
.map { |d| d.join(': '.freeze) }
.join(', '.freeze)
"Ransack::Search<#{details}>"
end
private
def add_scope(key, args)
sanitized_args = if Ransack.options[:sanitize_scope_args] && !@context.ransackable_scope_skip_sanitize_args?(key, @context.object)
sanitized_scope_args(args)
else
args
end
if @context.scope_arity(key) == 1
@scope_args[key] = args.is_a?(Array) ? args[0] : args
else
@scope_args[key] = args.is_a?(Array) ? sanitized_args : args
end
@context.chain_scope(key, sanitized_args)
end
def sanitized_scope_args(args)
if args.is_a?(Array)
args = args.map(&method(:sanitized_scope_args))
end
if Constants::TRUE_VALUES.include? args
true
elsif Constants::FALSE_VALUES.include? args
false
else
args
end
end
def collapse_multiparameter_attributes!(attrs)
attrs.keys.each do |k|
if k.include?(Constants::LEFT_PARENTHESIS)
real_attribute, position = k.split(/\(|\)/)
cast =
if Constants::A_S_I.include?(position.last)
position.last
else
nil
end
position = position.to_i - 1
value = attrs.delete(k)
attrs[real_attribute] ||= []
attrs[real_attribute][position] =
if cast
if value.blank? && cast == Constants::I
nil
else
value.send("to_#{cast}")
end
else
value
end
elsif Hash === attrs[k]
collapse_multiparameter_attributes!(attrs[k])
end
end
attrs
end
end
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/lib/ransack/helpers.rb | lib/ransack/helpers.rb | require 'ransack/helpers/form_builder'
require 'ransack/helpers/form_helper'
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/lib/ransack/configuration.rb | lib/ransack/configuration.rb | require 'ransack/constants'
require 'ransack/predicate'
module Ransack
module Configuration
mattr_accessor :predicates, :options
class PredicateCollection
attr_reader :sorted_names_with_underscores
def initialize
@collection = {}
@sorted_names_with_underscores = []
end
delegate :[], :keys, :has_key?, to: :@collection
def []=(key, value)
@sorted_names_with_underscores << [key, '_' + key]
@sorted_names_with_underscores.sort! { |(a, _), (b, _)| b.length <=> a.length }
@collection[key] = value
end
end
self.predicates = PredicateCollection.new
self.options = {
search_key: :q,
ignore_unknown_conditions: true,
hide_sort_order_indicators: false,
up_arrow: '▼'.freeze,
down_arrow: '▲'.freeze,
default_arrow: nil,
sanitize_scope_args: true,
postgres_fields_sort_option: nil,
strip_whitespace: true
}
def configure
yield self
end
def add_predicate(name, opts = {})
name = name.to_s
opts[:name] = name
compounds = opts.delete(:compounds)
compounds = true if compounds.nil?
compounds = false if opts[:wants_array]
self.predicates[name] = Predicate.new(opts)
Constants::SUFFIXES.each do |suffix|
compound_name = name + suffix
self.predicates[compound_name] = Predicate.new(
opts.merge(
name: compound_name,
arel_predicate: arel_predicate_with_suffix(
opts[:arel_predicate], suffix
),
compound: true
)
)
end if compounds
end
# The default `search_key` name is `:q`. The default key may be overridden
# in an initializer file like `config/initializers/ransack.rb` as follows:
#
# Ransack.configure do |config|
# # Name the search_key `:query` instead of the default `:q`
# config.search_key = :query
# end
#
# Sometimes there are situations when the default search parameter name
# cannot be used, for instance if there were two searches on one page.
# Another name can be set using the `search_key` option with Ransack
# `ransack`, `search` and `@search_form_for` methods in controllers & views.
#
# In the controller:
# @search = Log.ransack(params[:log_search], search_key: :log_search)
#
# In the view:
# <%= f.search_form_for @search, as: :log_search %>
#
def search_key=(name)
self.options[:search_key] = name
end
# By default Ransack ignores errors if an unknown predicate, condition or
# attribute is passed into a search. The default may be overridden in an
# initializer file like `config/initializers/ransack.rb` as follows:
#
# Ransack.configure do |config|
# # Raise if an unknown predicate, condition or attribute is passed
# config.ignore_unknown_conditions = false
# end
#
def ignore_unknown_conditions=(boolean)
self.options[:ignore_unknown_conditions] = boolean
end
# By default Ransack ignores empty predicates. Ransack can also fallback to
# a default predicate by setting it in an initializer file
# like `config/initializers/ransack.rb` as follows:
#
# Ransack.configure do |config|
# # Use the 'eq' predicate if an unknown predicate is passed
# config.default_predicate = 'eq'
# end
#
def default_predicate=(name)
self.options[:default_predicate] = name
end
# By default, Ransack displays sort order indicator arrows with HTML codes:
#
# up_arrow: '▼'
# down_arrow: '▲'
#
# There is also a default arrow which is displayed if a column is not sorted.
# By default this is nil so nothing will be displayed.
#
# Any of the defaults may be globally overridden in an initializer file
# like `config/initializers/ransack.rb` as follows:
#
# Ransack.configure do |config|
# # Globally set the up arrow to an icon, and the down and default arrows to unicode.
# config.custom_arrows = {
# up_arrow: '<i class="fa fa-long-arrow-up"></i>',
# down_arrow: 'U+02193',
# default_arrow: 'U+11047'
# }
# end
#
def custom_arrows=(opts = {})
self.options[:up_arrow] = opts[:up_arrow].freeze if opts[:up_arrow]
self.options[:down_arrow] = opts[:down_arrow].freeze if opts[:down_arrow]
self.options[:default_arrow] = opts[:default_arrow].freeze if opts[:default_arrow]
end
# Ransack sanitizes many values in your custom scopes into booleans.
# [1, '1', 't', 'T', 'true', 'TRUE'] all evaluate to true.
# [0, '0', 'f', 'F', 'false', 'FALSE'] all evaluate to false.
#
# This default may be globally overridden in an initializer file like
# `config/initializers/ransack.rb` as follows:
#
# Ransack.configure do |config|
# # Accept my custom scope values as what they are.
# config.sanitize_custom_scope_booleans = false
# end
#
def sanitize_custom_scope_booleans=(boolean)
self.options[:sanitize_scope_args] = boolean
end
# The `NULLS FIRST` and `NULLS LAST` options can be used to determine
# whether nulls appear before or after non-null values in the sort ordering.
#
# User may want to configure it like this:
#
# Ransack.configure do |c|
# c.postgres_fields_sort_option = :nulls_first # or e.g. :nulls_always_last
# end
#
# See this feature: https://www.postgresql.org/docs/13/queries-order.html
#
def postgres_fields_sort_option=(setting)
self.options[:postgres_fields_sort_option] = setting
end
# By default, Ransack displays sort order indicator arrows in sort links.
# The default may be globally overridden in an initializer file like
# `config/initializers/ransack.rb` as follows:
#
# Ransack.configure do |config|
# # Hide sort link order indicators globally across the application
# config.hide_sort_order_indicators = true
# end
#
def hide_sort_order_indicators=(boolean)
self.options[:hide_sort_order_indicators] = boolean
end
# By default, Ransack displays strips all whitespace when searching for a string.
# The default may be globally changed in an initializer file like
# `config/initializers/ransack.rb` as follows:
#
# Ransack.configure do |config|
# # Enable whitespace stripping for string searches
# config.strip_whitespace = true
# end
#
def strip_whitespace=(boolean)
self.options[:strip_whitespace] = boolean
end
def arel_predicate_with_suffix(arel_predicate, suffix)
if arel_predicate === Proc
proc { |v| "#{arel_predicate.call(v)}#{suffix}" }
else
"#{arel_predicate}#{suffix}"
end
end
end
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/lib/ransack/visitor.rb | lib/ransack/visitor.rb | module Ransack
class Visitor
def accept(object)
visit(object)
end
def can_accept?(object)
respond_to? DISPATCH[object.class]
end
def visit_Array(object)
object.map { |o| accept(o) }.compact
end
def visit_Ransack_Nodes_Condition(object)
object.arel_predicate if object.valid?
end
def visit_Ransack_Nodes_Grouping(object)
if object.combinator == Constants::OR
visit_or(object)
else
visit_and(object)
end
end
def visit_and(object)
nodes = object.values.map { |o| accept(o) }.compact
return nil unless nodes.size > 0
if nodes.size > 1
Arel::Nodes::Grouping.new(Arel::Nodes::And.new(nodes))
else
nodes.first
end
end
def visit_or(object)
nodes = object.values.map { |o| accept(o) }.compact
nodes.inject(&:or)
end
def quoted?(object)
case object
when Arel::Nodes::SqlLiteral, Bignum, Fixnum
false
else
true
end
end
def visit(object)
send(DISPATCH[object.class], object)
end
def visit_Ransack_Nodes_Sort(object)
if object.valid?
if object.attr.is_a?(Arel::Attributes::Attribute)
object.attr.send(object.dir)
else
ordered(object)
end
else
scope_name = :"sort_by_#{object.name}_#{object.dir}"
scope_name if object.context.object.respond_to?(scope_name)
end
end
DISPATCH = Hash.new do |hash, klass|
hash[klass] = "visit_#{
klass.name.gsub(Constants::TWO_COLONS, Constants::UNDERSCORE)
}"
end
private
def ordered(object)
case object.dir
when 'asc'.freeze
Arel::Nodes::Ascending.new(object.attr)
when 'desc'.freeze
Arel::Nodes::Descending.new(object.attr)
end
end
end
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/lib/ransack/context.rb | lib/ransack/context.rb | require 'ransack/visitor'
module Ransack
class Context
attr_reader :search, :object, :klass, :base, :engine, :arel_visitor
attr_accessor :auth_object, :search_key
attr_reader :arel_visitor
class << self
def for_class(klass, options = {})
if klass < ActiveRecord::Base
Adapters::ActiveRecord::Context.new(klass, options)
end
end
def for_object(object, options = {})
case object
when ActiveRecord::Relation
Adapters::ActiveRecord::Context.new(object.klass, options)
end
end
def for(object, options = {})
context =
if Class === object
for_class(object, options)
else
for_object(object, options)
end
context or raise ArgumentError,
"Don't know what context to use for #{object}"
end
end # << self
def initialize(object, options = {})
@object = relation_for(object)
@klass = @object.klass
@join_dependency = join_dependency(@object)
@join_type = options[:join_type] || Polyamorous::OuterJoin
@search_key = options[:search_key] || Ransack.options[:search_key]
@associations_pot = {}
@tables_pot = {}
@lock_associations = []
@base = @join_dependency.instance_variable_get(:@join_root)
end
def bind_pair_for(key)
@bind_pairs ||= {}
@bind_pairs[key] ||= begin
parent, attr_name = get_parent_and_attribute_name(key.to_s)
[parent, attr_name] if parent && attr_name
end
end
def klassify(obj)
if Class === obj && ::ActiveRecord::Base > obj
obj
elsif obj.respond_to? :klass
obj.klass
else
raise ArgumentError, "Don't know how to klassify #{obj.inspect}"
end
end
# Convert a string representing a chain of associations and an attribute
# into the attribute itself
def contextualize(str)
parent, attr_name = bind_pair_for(str)
table_for(parent)[attr_name]
end
def chain_scope(scope, args)
return unless @klass.method(scope) && args != false
@object = if scope_arity(scope) < 1 && args == true
@object.public_send(scope)
elsif scope_arity(scope) == 1 && args.is_a?(Array)
# For scopes with arity 1, pass the array as a single argument instead of splatting
@object.public_send(scope, args)
else
@object.public_send(scope, *args)
end
end
def scope_arity(scope)
@klass.method(scope).arity
end
def bind(object, str)
return nil unless str
object.parent, object.attr_name = bind_pair_for(str)
end
def traverse(str, base = @base)
str ||= ''.freeze
segments = str.split(Constants::UNDERSCORE)
unless segments.empty?
remainder = []
found_assoc = nil
until found_assoc || segments.empty?
# Strip the _of_Model_type text from the association name, but hold
# onto it in klass, for use as the next base
assoc, klass = unpolymorphize_association(
segments.join(Constants::UNDERSCORE)
)
if found_assoc = get_association(assoc, base)
base = traverse(
remainder.join(Constants::UNDERSCORE), klass || found_assoc.klass
)
end
remainder.unshift segments.pop
end
unless found_assoc
raise(UntraversableAssociationError,
"No association matches #{str}")
end
end
klassify(base)
end
def association_path(str, base = @base)
base = klassify(base)
str ||= ''.freeze
path = []
segments = str.split(Constants::UNDERSCORE)
association_parts = []
unless segments.empty?
while !segments.empty? &&
!base.columns_hash[segments.join(Constants::UNDERSCORE)] &&
association_parts << segments.shift
assoc, klass = unpolymorphize_association(
association_parts.join(Constants::UNDERSCORE)
)
next unless found_assoc = get_association(assoc, base)
path += association_parts
association_parts = []
base = klassify(klass || found_assoc)
end
end
path.join(Constants::UNDERSCORE)
end
def unpolymorphize_association(str)
if (match = str.match(/_of_([^_]+?)_type$/))
[match.pre_match, Kernel.const_get(match.captures.first)]
else
[str, nil]
end
end
def ransackable_alias(str)
klass._ransack_aliases.fetch(str, klass._ransack_aliases.fetch(str.to_sym, str))
end
def ransackable_attribute?(str, klass)
klass.ransackable_attributes(auth_object).any? { |s| s.to_sym == str.to_sym } ||
klass.ransortable_attributes(auth_object).any? { |s| s.to_sym == str.to_sym }
end
def ransackable_association?(str, klass)
klass.ransackable_associations(auth_object).any? { |s| s.to_sym == str.to_sym }
end
def ransackable_scope?(str, klass)
klass.ransackable_scopes(auth_object).any? { |s| s.to_sym == str.to_sym }
end
def ransackable_scope_skip_sanitize_args?(str, klass)
klass.ransackable_scopes_skip_sanitize_args.any? { |s| s.to_sym == str.to_sym }
end
def searchable_attributes(str = ''.freeze)
traverse(str).ransackable_attributes(auth_object)
end
def sortable_attributes(str = ''.freeze)
traverse(str).ransortable_attributes(auth_object)
end
def searchable_associations(str = ''.freeze)
traverse(str).ransackable_associations(auth_object)
end
end
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/lib/ransack/naming.rb | lib/ransack/naming.rb | module Ransack
module Naming
def self.included(base)
base.extend ClassMethods
end
def persisted?
false
end
def to_key
nil
end
def to_param
nil
end
def to_model
self
end
def model_name
self.class.model_name
end
end
class Name < String
attr_reader :singular, :plural, :element, :collection, :partial_path,
:human, :param_key, :route_key, :i18n_key
alias_method :cache_key, :collection
def initialize
super(Constants::CAP_SEARCH)
@singular = Constants::SEARCH
@plural = Constants::SEARCHES
@element = Constants::SEARCH
@human = Constants::CAP_SEARCH
@collection = Constants::RANSACK_SLASH_SEARCHES
@partial_path = Constants::RANSACK_SLASH_SEARCHES_SLASH_SEARCH
@param_key = Constants::Q
@route_key = Constants::SEARCHES
@i18n_key = :ransack
end
end
module ClassMethods
def model_name
@_model_name ||= Name.new
end
def i18n_scope
:ransack
end
end
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/lib/ransack/helpers/form_helper.rb | lib/ransack/helpers/form_helper.rb | module Ransack
module Helpers
module FormHelper
# +search_form_for+
#
# <%= search_form_for(@q) do |f| %>
#
def search_form_for(record, options = {}, &proc)
search = extract_search_and_set_url(record, options, 'search_form_for')
options[:html] ||= {}
html_options = build_html_options(search, options, :get)
finalize_form_options(options, html_options)
form_for(record, options, &proc)
end
# +search_form_with+
#
# <%= search_form_with(model: @q) do |f| %>
#
def search_form_with(record_or_options = {}, options = {}, &proc)
if record_or_options.is_a?(Hash) && record_or_options.key?(:model)
# Called with keyword arguments: search_form_with(model: @q)
options = record_or_options
record = options.delete(:model)
else
# Called with positional arguments: search_form_with(@q)
record = record_or_options
end
search = extract_search_and_set_url(record, options, 'search_form_with')
options[:html] ||= {}
html_options = build_html_options(search, options, :get)
finalize_form_with_options(options, html_options)
form_with(model: search, **options, &proc)
end
# +turbo_search_form_for+
#
# <%= turbo_search_form_for(@q) do |f| %>
#
# This is a turbo-enabled version of search_form_for that submits via turbo streams
# instead of traditional HTML GET requests. Useful for seamless integration with
# paginated results and other turbo-enabled components.
#
def turbo_search_form_for(record, options = {}, &proc)
search = extract_search_and_set_url(record, options, 'turbo_search_form_for')
options[:html] ||= {}
turbo_options = build_turbo_options(options)
method = options.delete(:method) || :post
html_options = build_html_options(search, options, method).merge(turbo_options)
finalize_form_options(options, html_options)
form_for(record, options, &proc)
end
# +sort_link+
#
# <%= sort_link(@q, :name, [:name, 'kind ASC'], 'Player Name') %>
#
# You can also use a block:
#
# <%= sort_link(@q, :name, [:name, 'kind ASC']) do %>
# <strong>Player Name</strong>
# <% end %>
#
def sort_link(search_object, attribute, *args, &block)
search, routing_proxy = extract_search_and_routing_proxy(search_object)
unless Search === search
raise TypeError, 'First argument must be a Ransack::Search!'
end
args[args.first.is_a?(Array) ? 1 : 0, 0] = capture(&block) if block_given?
s = SortLink.new(search, attribute, args, params, &block)
link_to(s.name, url(routing_proxy, s.url_options), s.html_options(args))
end
# +sort_url+
# <%= sort_url(@q, :created_at, default_order: :desc) %>
#
def sort_url(search_object, attribute, *args)
search, routing_proxy = extract_search_and_routing_proxy(search_object)
unless Search === search
raise TypeError, 'First argument must be a Ransack::Search!'
end
s = SortLink.new(search, attribute, args, params)
url(routing_proxy, s.url_options)
end
private
def extract_search_and_set_url(record, options, method_name)
if record.is_a? Ransack::Search
search = record
options[:url] ||= polymorphic_path(
search.klass, format: options.delete(:format)
)
search
elsif record.is_a?(Array) &&
(search = record.detect { |o| o.is_a?(Ransack::Search) })
options[:url] ||= polymorphic_path(
options_for(record), format: options.delete(:format)
)
search
else
raise ArgumentError,
"No Ransack::Search object was provided to #{method_name}!"
end
end
def build_turbo_options(options)
data_options = {}
if options[:turbo_frame]
data_options[:turbo_frame] = options.delete(:turbo_frame)
end
data_options[:turbo_action] = options.delete(:turbo_action) || 'advance'
{ data: data_options }
end
def build_html_options(search, options, method)
{
class: html_option_for(options[:class], search),
id: html_option_for(options[:id], search),
method: method
}
end
def finalize_form_options(options, html_options)
options[:as] ||= Ransack.options[:search_key]
options[:html].reverse_merge!(html_options)
options[:builder] ||= FormBuilder
end
def finalize_form_with_options(options, html_options)
options[:scope] ||= Ransack.options[:search_key]
options[:html].reverse_merge!(html_options)
options[:builder] ||= FormBuilder
end
def options_for(record)
record.map { |r| parse_record(r) }
end
def parse_record(object)
return object.klass if object.is_a?(Ransack::Search)
object
end
def html_option_for(option, search)
return option.to_s if option.present?
"#{search.klass.to_s.underscore}_search"
end
def extract_search_and_routing_proxy(search)
return [search[1], search[0]] if search.is_a?(Array)
[search, nil]
end
def url(routing_proxy, options_for_url)
if routing_proxy && respond_to?(routing_proxy)
send(routing_proxy).url_for(options_for_url)
else
url_for(options_for_url)
end
end
class SortLink
def initialize(search, attribute, args, params)
@search = search
@params = parameters_hash(params)
@field = attribute.to_s
@sort_fields = extract_sort_fields_and_mutate_args!(args).compact
@current_dir = existing_sort_direction
@label_text = extract_label_and_mutate_args!(args)
@options = extract_options_and_mutate_args!(args)
@hide_indicator = @options.delete(:hide_indicator) ||
Ransack.options[:hide_sort_order_indicators]
@default_order = @options.delete :default_order
end
def up_arrow
Ransack.options[:up_arrow]
end
def down_arrow
Ransack.options[:down_arrow]
end
def default_arrow
Ransack.options[:default_arrow]
end
def name
[ERB::Util.h(@label_text), order_indicator]
.compact
.join(' '.freeze)
.html_safe
end
def url_options
@params.except(:host).merge(
@options.except(:class, :data, :host).merge(
@search.context.search_key => search_and_sort_params))
end
def html_options(args)
if args.empty?
html_options = @options
else
deprecation_message = "Passing two trailing hashes to `sort_link` is deprecated, merge the trailing hashes into a single one."
caller_location = caller_locations(2, 2).first
warn "#{deprecation_message} (called at #{caller_location.path}:#{caller_location.lineno})"
html_options = extract_options_and_mutate_args!(args)
end
html_options.merge(
class: [['sort_link'.freeze, @current_dir], html_options[:class]]
.compact.join(' '.freeze)
)
end
private
def parameters_hash(params)
if params.respond_to?(:to_unsafe_h)
params.to_unsafe_h
else
params
end
end
def extract_sort_fields_and_mutate_args!(args)
return args.shift if args[0].is_a?(Array)
[@field]
end
def extract_label_and_mutate_args!(args)
return args.shift if args[0].is_a?(String)
Translate.attribute(@field, context: @search.context)
end
def extract_options_and_mutate_args!(args)
return args.shift.with_indifferent_access if args[0].is_a?(Hash)
{}
end
def search_and_sort_params
search_params.merge(s: sort_params)
end
def search_params
query_params = @params[@search.context.search_key]
query_params.is_a?(Hash) ? query_params : {}
end
def sort_params
sort_array = recursive_sort_params_build(@sort_fields)
return sort_array[0] if sort_array.length == 1
sort_array
end
def recursive_sort_params_build(fields)
return [] if fields.empty?
[parse_sort(fields[0])] + recursive_sort_params_build(fields.drop 1)
end
def parse_sort(field)
attr_name, new_dir = field.to_s.split(/\s+/)
if no_sort_direction_specified?(new_dir)
new_dir = detect_previous_sort_direction_and_invert_it(attr_name)
end
"#{attr_name} #{new_dir}"
end
def detect_previous_sort_direction_and_invert_it(attr_name)
if sort_dir = existing_sort_direction(attr_name)
direction_text(sort_dir)
else
default_sort_order(attr_name) || 'asc'.freeze
end
end
def existing_sort_direction(f = @field)
return unless sort = @search.sorts.detect { |s| s && s.name == f }
sort.dir
end
def default_sort_order(attr_name)
return @default_order[attr_name] if Hash === @default_order
@default_order
end
def order_indicator
return if @hide_indicator
return default_arrow if no_sort_direction_specified?
if @current_dir == 'desc'.freeze
up_arrow
else
down_arrow
end
end
def no_sort_direction_specified?(dir = @current_dir)
dir != 'asc'.freeze && dir != 'desc'.freeze
end
def direction_text(dir)
return 'asc'.freeze if dir == 'desc'.freeze
'desc'.freeze
end
end
end
end
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/lib/ransack/helpers/form_builder.rb | lib/ransack/helpers/form_builder.rb | require 'action_view'
module ActionView::Helpers::Tags
# TODO: Find a better way to solve this issue!
# This patch is needed since this Rails commit:
# https://github.com/rails/rails/commit/c1a118a
class Base
private
def value
if @allow_method_names_outside_object
object.send @method_name if object && object.respond_to?(@method_name, true)
else
object.send @method_name if object
end
end
end
end
RANSACK_FORM_BUILDER = 'RANSACK_FORM_BUILDER'.freeze
require 'simple_form' if
(ENV[RANSACK_FORM_BUILDER] || ''.freeze).match('SimpleForm'.freeze)
module Ransack
module Helpers
class FormBuilder < (ENV[RANSACK_FORM_BUILDER].try(:constantize) ||
ActionView::Helpers::FormBuilder)
def label(method, *args, &block)
options = args.extract_options!
text = args.first
i18n = options[:i18n] || {}
text ||= object.translate(
method, i18n.reverse_merge(include_associations: true)
) if object.respond_to? :translate
super(method, text, options, &block)
end
def submit(value = nil, options = {})
value, options = nil, value if value.is_a?(Hash)
value ||= Translate.word(:search).titleize
super(value, options)
end
def attribute_select(options = nil, html_options = nil, action = nil)
options ||= {}
html_options ||= {}
action ||= Constants::SEARCH
default = options.delete(:default)
raise ArgumentError, formbuilder_error_message(
"#{action}_select") unless object.respond_to?(:context)
options[:include_blank] = true unless options.has_key?(:include_blank)
bases = [''.freeze].freeze + association_array(options[:associations])
if bases.size > 1
collection = attribute_collection_for_bases(action, bases)
object.name ||= default if can_use_default?(
default, :name, mapped_values(collection.flatten(2))
)
template_grouped_collection_select(collection, options, html_options)
else
collection = collection_for_base(action, bases.first)
object.name ||= default if can_use_default?(
default, :name, mapped_values(collection)
)
template_collection_select(:name, collection, options, html_options)
end
end
def sort_direction_select(options = {}, html_options = {})
unless object.respond_to?(:context)
raise ArgumentError,
formbuilder_error_message('sort_direction'.freeze)
end
template_collection_select(:dir, sort_array, options, html_options)
end
def sort_select(options = {}, html_options = {})
attribute_select(options, html_options, 'sort'.freeze) +
sort_direction_select(options, html_options)
end
def sort_fields(*args, &block)
search_fields(:s, args, block)
end
def sort_link(attribute, *args)
@template.sort_link @object, attribute, *args
end
def sort_url(attribute, *args)
@template.sort_url @object, attribute, *args
end
def condition_fields(*args, &block)
search_fields(:c, args, block)
end
def grouping_fields(*args, &block)
search_fields(:g, args, block)
end
def attribute_fields(*args, &block)
search_fields(:a, args, block)
end
def predicate_fields(*args, &block)
search_fields(:p, args, block)
end
def value_fields(*args, &block)
search_fields(:v, args, block)
end
def search_fields(name, args, block)
args << {} unless args.last.is_a?(Hash)
args.last[:builder] ||= options[:builder]
args.last[:parent_builder] = self
options = args.extract_options!
objects = args.shift
objects ||= @object.send(name)
objects = [objects] unless Array === objects
name = "#{options[:object_name] || object_name}[#{name}]"
objects.inject(ActiveSupport::SafeBuffer.new) do |output, child|
output << @template.fields_for("#{name}[#{options[:child_index] ||
nested_child_index(name)}]", child, options, &block)
end
end
def predicate_select(options = {}, html_options = {})
options[:compounds] = true if options[:compounds].nil?
default = options.delete(:default) || Constants::CONT
keys =
if options[:compounds]
Predicate.names
else
Predicate.names.reject { |k| k.match(/_(any|all)$/) }
end
if only = options[:only]
if only.respond_to? :call
keys = keys.select { |k| only.call(k) }
else
only = Array.wrap(only).map(&:to_s)
keys = keys.select {
|k| only.include? k.sub(/_(any|all)$/, ''.freeze)
}
end
end
collection = keys.map { |k| [k, Translate.predicate(k)] }
object.predicate ||= Predicate.named(default) if
can_use_default?(default, :predicate, keys)
template_collection_select(:p, collection, options, html_options)
end
def combinator_select(options = {}, html_options = {})
template_collection_select(
:m, combinator_choices, options, html_options)
end
private
def template_grouped_collection_select(collection, options, html_options)
@template.grouped_collection_select(
@object_name, :name, collection, :last, :first, :first, :last,
objectify_options(options), @default_options.merge(html_options)
)
end
def template_collection_select(name, collection, options, html_options)
@template.collection_select(
@object_name, name, collection, :first, :last,
objectify_options(options), @default_options.merge(html_options)
)
end
def can_use_default?(default, attribute, values)
object.respond_to?("#{attribute}=") && default &&
values.include?(default.to_s)
end
def mapped_values(values)
values.map { |v| v.is_a?(Array) ? v.first : nil }.compact
end
def sort_array
[
['asc'.freeze, object.translate('asc'.freeze)].freeze,
['desc'.freeze, object.translate('desc'.freeze)].freeze
].freeze
end
def combinator_choices
if Nodes::Condition === object
[
[Constants::OR, Translate.word(:any)],
[Constants::AND, Translate.word(:all)]
]
else
[
[Constants::AND, Translate.word(:all)],
[Constants::OR, Translate.word(:any)]
]
end
end
def association_array(obj, prefix = nil)
([prefix] + association_object(obj))
.compact
.flat_map { |v| [prefix, v].compact.join(Constants::UNDERSCORE) }
end
def association_object(obj)
case obj
when Array
obj
when Hash
association_hash(obj)
else
[obj]
end
end
def association_hash(obj)
obj.map do |key, value|
case value
when Array, Hash
association_array(value, key.to_s)
else
[key.to_s, [key, value].join(Constants::UNDERSCORE)]
end
end
end
def attribute_collection_for_bases(action, bases)
bases.map { |base| get_attribute_element(action, base) }.compact
end
def get_attribute_element(action, base)
begin
[
Translate.association(base, context: object.context),
collection_for_base(action, base)
]
rescue UntraversableAssociationError
nil
end
end
def attribute_collection_for_base(attributes, base = nil)
attributes.map do |c|
[
attr_from_base_and_column(base, c),
Translate.attribute(
attr_from_base_and_column(base, c), context: object.context
)
]
end
end
def collection_for_base(action, base)
attribute_collection_for_base(
object.context.send("#{action}able_attributes", base), base)
end
def attr_from_base_and_column(base, column)
[base, column].reject(&:blank?).join(Constants::UNDERSCORE)
end
def formbuilder_error_message(action)
"#{action.sub(Constants::SEARCH, Constants::ATTRIBUTE)
} must be called inside a search FormBuilder!"
end
end
end
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/lib/ransack/nodes/value.rb | lib/ransack/nodes/value.rb | module Ransack
module Nodes
class Value < Node
attr_accessor :value
delegate :present?, :blank?, to: :value
def initialize(context, value = nil)
super(context)
@value = value
end
def persisted?
false
end
def eql?(other)
self.class == other.class && self.value == other.value
end
alias :== :eql?
def hash
value.hash
end
def cast(type)
case type
when :date
cast_to_date(value)
when :datetime, :timestamp, :time, :timestamptz
cast_to_time(value)
when :boolean
cast_to_boolean(value)
when :integer
cast_to_integer(value)
when :float
cast_to_float(value)
when :decimal
cast_to_decimal(value)
when :money
cast_to_money(value)
else
cast_to_string(value)
end
end
def cast_to_date(val)
if val.respond_to?(:to_date)
val.to_date rescue nil
else
y, m, d = *[val].flatten
m ||= 1
d ||= 1
Date.new(y, m, d) rescue nil
end
end
def cast_to_time(val)
if val.is_a?(Array)
Time.zone.local(*val) rescue nil
else
unless val.acts_like?(:time)
val = val.is_a?(String) ? Time.zone.parse(val) : val.to_time rescue val
end
val.in_time_zone rescue nil
end
end
def cast_to_boolean(val)
if Constants::TRUE_VALUES.include?(val)
true
elsif Constants::FALSE_VALUES.include?(val)
false
else
nil
end
end
def cast_to_string(val)
val.respond_to?(:to_s) ? val.to_s : String.new(val)
end
def cast_to_integer(val)
val.respond_to?(:to_i) && !val.blank? ? val.to_i : nil
end
def cast_to_float(val)
val.blank? ? nil : val.to_f
end
def cast_to_decimal(val)
if val.blank?
nil
elsif val.class == BigDecimal
val
elsif val.respond_to?(:to_d)
val.to_d
else
val.to_s.to_d
end
end
def cast_to_money(val)
val.blank? ? nil : val.to_f.to_s
end
def inspect
"Value <#{value}>"
end
def array_of_arrays?(val)
Array === val && Array === val.first
end
end
end
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/lib/ransack/nodes/node.rb | lib/ransack/nodes/node.rb | module Ransack
module Nodes
class Node
attr_reader :context
delegate :contextualize, to: :context
class_attribute :i18n_words
class_attribute :i18n_aliases
self.i18n_words = []
self.i18n_aliases = {}
class << self
def i18n_word(*args)
self.i18n_words += args.map(&:to_s)
end
def i18n_alias(opts = {})
self.i18n_aliases.merge! Hash[opts.map { |k, v| [k.to_s, v.to_s] }]
end
end
def initialize(context)
@context = context
end
def translate(key, options = {})
key = i18n_aliases[key.to_s] if i18n_aliases.has_key?(key.to_s)
if i18n_words.include?(key.to_s)
Translate.word(key)
end
end
end
end
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/lib/ransack/nodes/attribute.rb | lib/ransack/nodes/attribute.rb | module Ransack
module Nodes
class Attribute < Node
include Bindable
attr_reader :name, :ransacker_args
delegate :blank?, :present?, to: :name
delegate :engine, to: :context
def initialize(context, name = nil, ransacker_args = [])
super(context)
self.name = name unless name.blank?
@ransacker_args = ransacker_args
end
def name=(name)
@name = name
end
def valid?
bound? && attr &&
context.klassify(parent).ransackable_attributes(context.auth_object)
.include?(attr_name.split('.').last)
end
def associated_collection?
parent.respond_to?(:reflection) && parent.reflection.collection?
end
def type
if ransacker
ransacker.type
else
context.type_for(self)
end
end
def eql?(other)
self.class == other.class &&
self.name == other.name
end
alias :== :eql?
def hash
self.name.hash
end
def persisted?
false
end
def inspect
"Attribute <#{name}>"
end
end
end
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/lib/ransack/nodes/sort.rb | lib/ransack/nodes/sort.rb | module Ransack
module Nodes
class Sort < Node
include Bindable
attr_reader :name, :dir, :ransacker_args
i18n_word :asc, :desc
class << self
def extract(context, str)
return if str.blank?
attr, direction = str.split(/\s+/, 2)
self.new(context).build(name: attr, dir: direction)
end
end
def build(params)
params.with_indifferent_access.each do |key, value|
if key.match(/^(name|dir|ransacker_args)$/)
self.send("#{key}=", value)
end
end
self
end
def valid?
bound? && attr &&
context.klassify(parent).ransortable_attributes(context.auth_object)
.include?(attr_name)
end
def name=(name)
@name = context.ransackable_alias(name) || name
context.bind(self, @name)
end
def dir=(dir)
dir = dir.downcase if dir
@dir =
if dir == 'asc'.freeze || dir == 'desc'.freeze
dir
else
'asc'.freeze
end
end
def ransacker_args=(ransack_args)
@ransacker_args = ransack_args
end
end
end
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/lib/ransack/nodes/bindable.rb | lib/ransack/nodes/bindable.rb | module Ransack
module Nodes
module Bindable
attr_accessor :parent, :attr_name
def attr
@attr ||= get_arel_attribute
end
alias :arel_attribute :attr
def ransacker
klass._ransackers[attr_name]
end
def klass
@klass ||= context.klassify(parent)
end
def bound?
attr_name.present? && parent.present?
end
def reset_binding!
@parent = @attr_name = @attr = @klass = nil
end
private
def get_arel_attribute
if ransacker
ransacker.attr_from(self)
else
get_attribute
end
end
def get_attribute
if is_alias_attribute?
context.table_for(parent)[parent.base_klass.attribute_aliases[attr_name]]
else
context.table_for(parent)[attr_name]
end
end
def is_alias_attribute?
Ransack::SUPPORTS_ATTRIBUTE_ALIAS &&
parent.base_klass.attribute_aliases.key?(attr_name)
end
end
end
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/lib/ransack/nodes/grouping.rb | lib/ransack/nodes/grouping.rb | module Ransack
module Nodes
class Grouping < Node
attr_reader :conditions
attr_accessor :combinator
alias :m :combinator
alias :m= :combinator=
i18n_word :condition, :and, :or
i18n_alias c: :condition, n: :and, o: :or
delegate :each, to: :values
def initialize(context, combinator = nil)
super(context)
self.combinator = combinator.to_s if combinator
end
def persisted?
false
end
def translate(key, options = {})
super or Translate.attribute(
key.to_s, options.merge(context: context)
)
end
def conditions
@conditions ||= []
end
alias :c :conditions
def conditions=(conditions)
case conditions
when Array
conditions.each do |attrs|
condition = Condition.new(@context).build(attrs)
self.conditions << condition if condition.valid?
end
when Hash
conditions.each do |index, attrs|
condition = Condition.new(@context).build(attrs)
self.conditions << condition if condition.valid?
end
end
remove_duplicate_conditions!
end
alias :c= :conditions=
def [](key)
conditions.detect { |c| c.key == key.to_s }
end
def []=(key, value)
conditions.reject! { |c| c.key == key.to_s && c&.value == value&.value }
self.conditions << value
end
def values
conditions + groupings
end
def respond_to?(method_id)
super or begin
method_name = method_id.to_s
attribute_method?(method_name) ? true : false
end
end
def build_condition(opts = {})
new_condition(opts).tap do |condition|
self.conditions << condition
end
end
def new_condition(opts = {})
attrs = opts[:attributes] || 1
vals = opts[:values] || 1
condition = Condition.new(@context)
attrs.times { condition.build_attribute }
vals.times { condition.build_value }
condition
end
def groupings
@groupings ||= []
end
alias :g :groupings
def groupings=(groupings)
case groupings
when Array
groupings.each do |attrs|
grouping_object = new_grouping(attrs)
self.groupings << grouping_object if grouping_object.values.any?
end
when Hash
groupings.each do |index, attrs|
grouping_object = new_grouping(attrs)
self.groupings << grouping_object if grouping_object.values.any?
end
else
raise ArgumentError,
"Invalid argument (#{groupings.class}) supplied to groupings="
end
end
alias :g= :groupings=
def method_missing(method_id, *args)
method_name = method_id.to_s.dup
writer = method_name.sub!(/\=$/, ''.freeze)
if attribute_method?(method_name)
if writer
write_attribute(method_name, *args)
else
read_attribute(method_name)
end
else
super
end
end
def attribute_method?(name)
stripped_name = strip_predicate_and_index(name)
return true if @context.attribute_method?(stripped_name) ||
@context.attribute_method?(name)
case stripped_name
when /^(g|c|m|groupings|conditions|combinator)=?$/
true
else
stripped_name
.split(/_and_|_or_/)
.none? { |n| !@context.attribute_method?(n) }
end
end
def build_grouping(params = {})
params ||= {}
new_grouping(params).tap do |new_grouping|
self.groupings << new_grouping
end
end
def new_grouping(params = {})
Grouping.new(@context).build(params)
end
def build(params)
params.with_indifferent_access.each do |key, value|
case key
when /^(g|c|m)$/
self.send("#{key}=", value)
else
write_attribute(key.to_s, value)
end
end
self
end
def inspect
data = [
['conditions'.freeze, conditions], [Constants::COMBINATOR, combinator]
]
.reject { |e| e[1].blank? }
.map { |v| "#{v[0]}: #{v[1]}" }
.join(', '.freeze)
"Grouping <#{data}>"
end
private
def write_attribute(name, val)
# TODO: Methods
if condition = Condition.extract(@context, name, val)
self[name] = condition
end
end
def read_attribute(name)
if self[name].respond_to?(:value)
self[name].value
else
self[name]
end
end
def strip_predicate_and_index(str)
string = str[/(.+?)\(/, 1] || str.dup
Predicate.detect_and_strip_from_string!(string)
string
end
def remove_duplicate_conditions!
# If self.conditions.uniq! is called without passing a block, then
# conditions differing only by ransacker_args within attributes are
# wrongly considered equal and are removed.
self.conditions.uniq! do |c|
c.attributes.map { |a| [a.name, a.ransacker_args] }.flatten +
[c.predicate.name] +
c.values.map { |v| v.value }
end
end
end
end
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/lib/ransack/nodes/condition.rb | lib/ransack/nodes/condition.rb | require 'ransack/invalid_search_error'
module Ransack
module Nodes
class Condition < Node
i18n_word :attribute, :predicate, :combinator, :value
i18n_alias a: :attribute, p: :predicate,
m: :combinator, v: :value
attr_accessor :predicate
class << self
def extract(context, key, values)
attributes, predicate, combinator =
extract_values_for_condition(key, context)
if attributes.size > 0 && predicate
condition = self.new(context)
condition.build(
a: attributes,
p: predicate.name,
m: combinator,
v: predicate.wants_array ? Array(values) : [values]
)
# TODO: Figure out what to do with multiple types of attributes,
# if anything. Tempted to go with "garbage in, garbage out" here.
if predicate.validate(condition.values, condition.default_type)
condition
else
nil
end
end
end
private
def extract_values_for_condition(key, context = nil)
str = key.dup
name = Predicate.detect_and_strip_from_string!(str)
predicate = Predicate.named(name)
unless predicate || Ransack.options[:ignore_unknown_conditions]
raise InvalidSearchError, "No valid predicate for #{key}"
end
if context.present?
str = context.ransackable_alias(str)
end
combinator =
if str.match(/_(or|and)_/)
$1
else
nil
end
if context.present? && context.attribute_method?(str)
attributes = [str]
else
attributes = str.split(/_and_|_or_/)
end
[attributes, predicate, combinator]
end
end
def valid?
attributes.detect(&:valid?) && predicate && valid_arity? &&
predicate.validate(values, default_type) && valid_combinator?
end
def valid_arity?
values.size <= 1 || predicate.wants_array
end
def attributes
@attributes ||= []
end
alias :a :attributes
def attributes=(args)
case args
when Array
args.each do |name|
build_attribute(name)
end
when Hash
args.each do |index, attrs|
build_attribute(attrs[:name], attrs[:ransacker_args])
end
else
raise ArgumentError,
"Invalid argument (#{args.class}) supplied to attributes="
end
end
alias :a= :attributes=
def values
@values ||= []
end
alias :v :values
def values=(args)
case args
when Array
args.each do |val|
val = Value.new(@context, val)
self.values << val
end
when Hash
args.each do |index, attrs|
val = Value.new(@context, attrs[:value])
self.values << val
end
else
raise ArgumentError,
"Invalid argument (#{args.class}) supplied to values="
end
end
alias :v= :values=
def combinator
@attributes.size > 1 ? @combinator : nil
end
def combinator=(val)
@combinator = Constants::AND_OR.detect { |v| v == val.to_s } || nil
end
alias :m= :combinator=
alias :m :combinator
# == build_attribute
#
# This method was originally called from Nodes::Grouping#new_condition
# only, without arguments, without #valid? checking, to build a new
# grouping condition.
#
# After refactoring in 235eae3, it is now called from 2 places:
#
# 1. Nodes::Condition#attributes=, with +name+ argument passed or +name+
# and +ransacker_args+. Attributes are included only if #valid?.
#
# 2. Nodes::Grouping#new_condition without arguments. In this case, the
# #valid? conditional needs to be bypassed, otherwise nothing is
# built. The `name.nil?` conditional below currently does this.
#
# TODO: Add test coverage for this behavior and ensure that `name.nil?`
# isn't fixing issue #701 by introducing untested regressions.
#
def build_attribute(name = nil, ransacker_args = [])
Attribute.new(@context, name, ransacker_args).tap do |attribute|
@context.bind(attribute, attribute.name)
self.attributes << attribute if name.nil? || attribute.valid?
if predicate && !negative?
@context.lock_association(attribute.parent)
end
end
end
def build_value(val = nil)
Value.new(@context, val).tap do |value|
self.values << value
end
end
def value
if predicate.wants_array
values.map { |v| v.cast(default_type) }
else
values.first.cast(default_type)
end
end
def build(params)
params.with_indifferent_access.each do |key, value|
if key.match(/^(a|v|p|m)$/)
self.send("#{key}=", value)
end
end
self
end
def persisted?
false
end
def key
@key ||= attributes.map(&:name).join("_#{combinator}_") +
"_#{predicate.name}"
end
def eql?(other)
self.class == other.class &&
self.attributes == other.attributes &&
self.predicate == other.predicate &&
self.values == other.values &&
self.combinator == other.combinator
end
alias :== :eql?
def hash
[attributes, predicate, values, combinator].hash
end
def predicate_name=(name)
self.predicate = Predicate.named(name)
unless negative?
attributes.each { |a| context.lock_association(a.parent) }
end
@predicate
end
alias :p= :predicate_name=
def predicate_name
predicate.name if predicate
end
alias :p :predicate_name
def arel_predicate
raise "not implemented"
end
def validated_values
values.select { |v| predicate.validator.call(v.value) }
end
def casted_values_for_attribute(attr)
validated_values.map { |v| v.cast(predicate.type || attr.type) }
end
def formatted_values_for_attribute(attr)
formatted = casted_values_for_attribute(attr).map do |val|
if attr.ransacker && attr.ransacker.formatter
val = attr.ransacker.formatter.call(val)
end
val = predicate.format(val)
if val.is_a?(String) && val.include?('%')
val = Arel::Nodes::Quoted.new(val)
end
val
end
if predicate.wants_array
formatted
else
formatted.first
end
end
def arel_predicate_for_attribute(attr)
if predicate.arel_predicate === Proc
values = casted_values_for_attribute(attr)
unless predicate.wants_array
values = values.first
end
predicate.arel_predicate.call(values)
else
predicate.arel_predicate
end
end
def attr_value_for_attribute(attr)
return attr.attr if ActiveRecord::Base.connection.adapter_name == "PostgreSQL"
predicate.case_insensitive ? attr.attr.lower : attr.attr
rescue
attr.attr
end
def default_type
predicate.type || (attributes.first && attributes.first.type)
end
def inspect
data = [
['attributes'.freeze, a.try(:map, &:name)],
['predicate'.freeze, p],
[Constants::COMBINATOR, m],
['values'.freeze, v.try(:map, &:value)]
]
.reject { |e| e[1].blank? }
.map { |v| "#{v[0]}: #{v[1]}" }
.join(', '.freeze)
"Condition <#{data}>"
end
def negative?
predicate.negative?
end
def arel_predicate
predicate = attributes.map { |attribute|
association = attribute.parent
parent_table = association.table
if negative? && attribute.associated_collection? && not_nested_condition(attribute, parent_table)
query = context.build_correlated_subquery(association)
context.remove_association(association)
case self.predicate_name
when 'not_null'
if self.value
query.where(format_predicate(attribute))
Arel::Nodes::In.new(context.primary_key, Arel.sql(query.to_sql))
else
query.where(format_predicate(attribute).not)
Arel::Nodes::NotIn.new(context.primary_key, Arel.sql(query.to_sql))
end
when 'not_cont'
query.where(attribute.attr.matches(formatted_values_for_attribute(attribute)))
Arel::Nodes::NotIn.new(context.primary_key, Arel.sql(query.to_sql))
else
query.where(format_predicate(attribute).not)
Arel::Nodes::NotIn.new(context.primary_key, Arel.sql(query.to_sql))
end
else
format_predicate(attribute)
end
}.reduce(combinator_method)
if replace_right_node?(predicate)
# Replace right node object to plain integer value in order to avoid
# ActiveModel::RangeError from Arel::Node::Casted.
# The error can be ignored here because RDBMSs accept large numbers
# in condition clauses.
plain_value = predicate.right.value
predicate.right = plain_value
end
predicate
end
def not_nested_condition(attribute, parent_table)
parent_table.class != Arel::Nodes::TableAlias && attribute.name.starts_with?(parent_table.name)
end
private
def combinator_method
combinator === Constants::OR ? :or : :and
end
def format_predicate(attribute)
arel_pred = arel_predicate_for_attribute(attribute)
arel_values = formatted_values_for_attribute(attribute)
# For LIKE predicates, wrap the value in Arel::Nodes.build_quoted to prevent
# ActiveRecord normalization from affecting wildcard patterns
if like_predicate?(arel_pred)
arel_values = Arel::Nodes.build_quoted(arel_values)
end
predicate = attr_value_for_attribute(attribute).public_send(arel_pred, arel_values)
if in_predicate?(predicate)
predicate.right = predicate.right.map do |pr|
casted_array?(pr) ? format_values_for(pr) : pr
end
end
predicate
end
def in_predicate?(predicate)
return unless defined?(Arel::Nodes::Casted)
predicate.class == Arel::Nodes::In || predicate.class == Arel::Nodes::NotIn
end
def like_predicate?(arel_predicate)
arel_predicate == 'matches' || arel_predicate == 'does_not_match'
end
def casted_array?(predicate)
predicate.is_a?(Arel::Nodes::Casted) && predicate.value.is_a?(Array)
end
def format_values_for(predicate)
predicate.value.map do |val|
val.is_a?(String) ? Arel::Nodes.build_quoted(val) : val
end
end
def replace_right_node?(predicate)
return false unless predicate.is_a?(Arel::Nodes::Binary)
arel_node = predicate.right
return false unless arel_node.is_a?(Arel::Nodes::Casted)
relation, name = arel_node.attribute.values
attribute_type = relation.type_for_attribute(name).type
attribute_type == :integer && arel_node.value.is_a?(Integer)
end
def valid_combinator?
attributes.size < 2 || Constants::AND_OR.include?(combinator)
end
end
end
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/lib/ransack/adapters/active_record/base.rb | lib/ransack/adapters/active_record/base.rb | module Ransack
module Adapters
module ActiveRecord
module Base
def self.extended(base)
base.class_eval do
class_attribute :_ransackers
class_attribute :_ransack_aliases
self._ransackers ||= {}
self._ransack_aliases ||= {}
end
end
def ransack(params = {}, options = {})
Search.new(self, params, options)
end
def ransack!(params = {}, options = {})
ransack(params, options.merge(ignore_unknown_conditions: false))
end
def ransacker(name, opts = {}, &block)
self._ransackers = _ransackers.merge name.to_s => Ransacker
.new(self, name, opts, &block)
end
def ransack_alias(new_name, old_name)
self._ransack_aliases = _ransack_aliases.merge new_name.to_s =>
old_name.to_s
end
# Ransackable_attributes, by default, returns all column names
# and any defined ransackers as an array of strings.
# For overriding with a whitelist array of strings.
#
def ransackable_attributes(auth_object = nil)
@ransackable_attributes ||= deprecated_ransackable_list(:ransackable_attributes)
end
# Ransackable_associations, by default, returns the names
# of all associations as an array of strings.
# For overriding with a whitelist array of strings.
#
def ransackable_associations(auth_object = nil)
@ransackable_associations ||= deprecated_ransackable_list(:ransackable_associations)
end
# Ransortable_attributes, by default, returns the names
# of all attributes available for sorting as an array of strings.
# For overriding with a whitelist array of strings.
#
def ransortable_attributes(auth_object = nil)
ransackable_attributes(auth_object)
end
# Ransackable_scopes, by default, returns an empty array
# i.e. no class methods/scopes are authorized.
# For overriding with a whitelist array of *symbols*.
#
def ransackable_scopes(auth_object = nil)
[]
end
# ransack_scope_skip_sanitize_args, by default, returns an empty array.
# i.e. use the sanitize_scope_args setting to determine if args should be converted.
# For overriding with a list of scopes which should be passed the args as-is.
#
def ransackable_scopes_skip_sanitize_args
[]
end
# Bare list of all potentially searchable attributes. Searchable attributes
# need to be explicitly allowlisted through the `ransackable_attributes`
# method in each model, but if you're allowing almost everything to be
# searched, this list can be used as a base for exclusions.
#
def authorizable_ransackable_attributes
if Ransack::SUPPORTS_ATTRIBUTE_ALIAS
column_names + _ransackers.keys + _ransack_aliases.keys +
attribute_aliases.keys
else
column_names + _ransackers.keys + _ransack_aliases.keys
end.uniq
end
# Bare list of all potentially searchable associations. Searchable
# associations need to be explicitly allowlisted through the
# `ransackable_associations` method in each model, but if you're
# allowing almost everything to be searched, this list can be used as a
# base for exclusions.
#
def authorizable_ransackable_associations
reflect_on_all_associations.map { |a| a.name.to_s }
end
private
def deprecated_ransackable_list(method)
list_type = method.to_s.delete_prefix("ransackable_")
if explicitly_defined?(method)
warn_deprecated <<~ERROR
Ransack's builtin `#{method}` method is deprecated and will result
in an error in the future. If you want to authorize the full list
of searchable #{list_type} for this model, use
`authorizable_#{method}` instead of delegating to `super`.
ERROR
public_send("authorizable_#{method}")
else
raise <<~MESSAGE
Ransack needs #{name} #{list_type} explicitly allowlisted as
searchable. Define a `#{method}` class method in your `#{name}`
model, watching out for items you DON'T want searchable (for
example, `encrypted_password`, `password_reset_token`, `owner` or
other sensitive information). You can use the following as a base:
```ruby
class #{name} < ApplicationRecord
# ...
def self.#{method}(auth_object = nil)
#{public_send("authorizable_#{method}").sort.inspect}
end
# ...
end
```
MESSAGE
end
end
def explicitly_defined?(method)
definer_ancestor = singleton_class.ancestors.find do |ancestor|
ancestor.instance_methods(false).include?(method)
end
definer_ancestor != Ransack::Adapters::ActiveRecord::Base
end
def warn_deprecated(message)
caller_location = caller_locations.find { |location| !location.path.start_with?(File.expand_path("../..", __dir__)) }
warn "DEPRECATION WARNING: #{message.squish} (called at #{caller_location.path}:#{caller_location.lineno})"
end
end
end
end
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/lib/ransack/adapters/active_record/context.rb | lib/ransack/adapters/active_record/context.rb | require 'ransack/context'
require 'polyamorous/polyamorous'
module Ransack
module Adapters
module ActiveRecord
class Context < ::Ransack::Context
def relation_for(object)
object.all
end
def type_for(attr)
return nil unless attr && attr.valid?
relation = attr.arel_attribute.relation
name = attr.arel_attribute.name.to_s
table = relation.respond_to?(:table_name) ? relation.table_name : relation.name
schema_cache = self.klass.connection.schema_cache
unless schema_cache.send(:data_source_exists?, table)
raise "No table named #{table} exists."
end
column = attr.klass.columns.find { |column| column.name == name }
column&.type
end
def evaluate(search, opts = {})
viz = Visitor.new
relation = @object.where(viz.accept(search.base))
if search.sorts.any?
relation = relation.except(:order)
# Rather than applying all of the search's sorts in one fell swoop,
# as the original implementation does, we apply one at a time.
#
# If the sort (returned by the Visitor above) is a symbol, we know
# that it represents a scope on the model and we can apply that
# scope.
#
# Otherwise, we fall back to the applying the sort with the "order"
# method as the original implementation did. Actually the original
# implementation used "reorder," which was overkill since we already
# have a clean slate after "relation.except(:order)" above.
viz.accept(search.sorts).each do |scope_or_sort|
if scope_or_sort.is_a?(Symbol)
relation = relation.send(scope_or_sort)
else
case Ransack.options[:postgres_fields_sort_option]
when :nulls_first
scope_or_sort = scope_or_sort.direction == :asc ? Arel.sql("#{scope_or_sort.to_sql} NULLS FIRST") : Arel.sql("#{scope_or_sort.to_sql} NULLS LAST")
when :nulls_last
scope_or_sort = scope_or_sort.direction == :asc ? Arel.sql("#{scope_or_sort.to_sql} NULLS LAST") : Arel.sql("#{scope_or_sort.to_sql} NULLS FIRST")
when :nulls_always_first
scope_or_sort = Arel.sql("#{scope_or_sort.to_sql} NULLS FIRST")
when :nulls_always_last
scope_or_sort = Arel.sql("#{scope_or_sort.to_sql} NULLS LAST")
end
relation = relation.order(scope_or_sort)
end
end
end
opts[:distinct] ? relation.distinct : relation
end
def attribute_method?(str, klass = @klass)
exists = false
if ransackable_attribute?(str, klass)
exists = true
elsif (segments = str.split(Constants::UNDERSCORE)).size > 1
remainder = []
found_assoc = nil
while !found_assoc && remainder.unshift(segments.pop) &&
segments.size > 0 do
assoc, poly_class = unpolymorphize_association(
segments.join(Constants::UNDERSCORE)
)
if found_assoc = get_association(assoc, klass)
exists = attribute_method?(
remainder.join(Constants::UNDERSCORE),
poly_class || found_assoc.klass
)
end
end
end
exists
end
def table_for(parent)
parent.table
end
def klassify(obj)
if Class === obj && ::ActiveRecord::Base > obj
obj
elsif obj.respond_to? :klass
obj.klass
elsif obj.respond_to? :base_klass
obj.base_klass
else
raise ArgumentError, "Don't know how to klassify #{obj}"
end
end
# All dependent Arel::Join nodes used in the search query.
#
# This could otherwise be done as `@object.arel.join_sources`, except
# that ActiveRecord's build_joins sets up its own JoinDependency.
# This extracts what we need to access the joins using our existing
# JoinDependency to track table aliases.
#
def join_sources
base, joins = begin
alias_tracker = @object.alias_tracker
constraints = @join_dependency.join_constraints(@object.joins_values, alias_tracker, @object.references_values)
[
Arel::SelectManager.new(@object.table),
constraints
]
end
joins.each do |aliased_join|
base.from(aliased_join)
end
base.join_sources
end
def alias_tracker
@join_dependency.send(:alias_tracker)
end
def lock_association(association)
@lock_associations << association
end
def remove_association(association)
return if @lock_associations.include?(association)
@join_dependency.instance_variable_get(:@join_root).children.delete_if { |stashed|
stashed.eql?(association)
}
@object.joins_values.delete_if { |jd|
jd.instance_variables.include?(:@join_root) &&
jd.instance_variable_get(:@join_root).children.map(&:object_id) == [association.object_id]
}
end
# Build an Arel subquery that selects keys for the top query,
# drawn from the first join association's foreign_key.
#
# Example: for an Article that has_and_belongs_to_many Tags
#
# context = Article.search.context
# attribute = Attribute.new(context, "tags_name").tap do |a|
# context.bind(a, a.name)
# end
# context.build_correlated_subquery(attribute.parent).to_sql
#
# # SELECT "articles_tags"."article_id" FROM "articles_tags"
# # INNER JOIN "tags" ON "tags"."id" = "articles_tags"."tag_id"
# # WHERE "articles_tags"."article_id" = "articles"."id"
#
# The WHERE condition on this query makes it invalid by itself,
# because it is correlated to the primary key on the outer query.
#
def build_correlated_subquery(association)
join_constraints = extract_joins(association)
join_root = join_constraints.shift
correlated_key = extract_correlated_key(join_root)
subquery = Arel::SelectManager.new(association.base_klass)
subquery.from(join_root.left)
subquery.project(correlated_key)
join_constraints.each do |j|
subquery.join_sources << Arel::Nodes::InnerJoin.new(j.left, j.right)
end
# Handle polymorphic associations where correlated_key is an array
if correlated_key.is_a?(Array)
# For polymorphic associations, we need to add conditions for both the foreign key and type
correlated_key.each_with_index do |key, index|
if index == 0
# This is the foreign key
subquery = subquery.where(key.eq(primary_key))
else
# This is the type key, which should be equal to the model name
subquery = subquery.where(key.eq(@klass.name))
end
end
else
# Original behavior for non-polymorphic associations
subquery = subquery.where(correlated_key.eq(primary_key))
end
subquery
end
def primary_key
@object.table[@object.primary_key]
end
private
def extract_correlated_key(join_root)
case join_root
when Arel::Nodes::OuterJoin
# one of join_root.right/join_root.left is expected to be Arel::Nodes::On
if join_root.right.is_a?(Arel::Nodes::On)
extract_correlated_key(join_root.right.expr)
elsif join_root.left.is_a?(Arel::Nodes::On)
extract_correlated_key(join_root.left.expr)
else
raise 'Ransack encountered an unexpected arel structure'
end
when Arel::Nodes::Equality
pk = primary_key
if join_root.left == pk
join_root.right
elsif join_root.right == pk
join_root.left
else
nil
end
when Arel::Nodes::And
# And may have multiple children, so we need to check all, not via left/right
if join_root.children.any?
join_root.children.each do |child|
key = extract_correlated_key(child)
return key if key
end
else
extract_correlated_key(join_root.left) || extract_correlated_key(join_root.right)
end
else
# eg parent was Arel::Nodes::And and the evaluated side was one of
# Arel::Nodes::Grouping or MultiTenant::TenantEnforcementClause
nil
end
end
def get_parent_and_attribute_name(str, parent = @base)
attr_name = nil
if ransackable_attribute?(str, klassify(parent))
attr_name = str
elsif (segments = str.split(Constants::UNDERSCORE)).size > 1
remainder = []
found_assoc = nil
while remainder.unshift(segments.pop) && segments.size > 0 &&
!found_assoc do
assoc, klass = unpolymorphize_association(
segments.join(Constants::UNDERSCORE)
)
if found_assoc = get_association(assoc, parent)
join = build_or_find_association(
found_assoc.name, parent, klass
)
parent, attr_name = get_parent_and_attribute_name(
remainder.join(Constants::UNDERSCORE), join
)
end
end
end
[parent, attr_name]
end
def get_association(str, parent = @base)
klass = klassify parent
ransackable_association?(str, klass) &&
klass.reflect_on_all_associations.detect { |a| a.name.to_s == str }
end
def join_dependency(relation)
if relation.respond_to?(:join_dependency) # Polyamorous enables this
relation.join_dependency
else
build_joins(relation)
end
end
# Checkout active_record/relation/query_methods.rb +build_joins+ for
# reference. Lots of duplicated code maybe we can avoid it
def build_joins(relation)
buckets = relation.joins_values + relation.left_outer_joins_values
buckets = buckets.group_by do |join|
case join
when String
:string_join
when Hash, Symbol, Array
:association_join
when Polyamorous::JoinDependency, Polyamorous::JoinAssociation
:stashed_join
when Arel::Nodes::Join
:join_node
else
raise 'unknown class: %s' % join.class.name
end
end
buckets.default = []
association_joins = buckets[:association_join]
stashed_association_joins = buckets[:stashed_join]
join_nodes = buckets[:join_node].uniq
string_joins = buckets[:string_join].map(&:strip)
string_joins.uniq!
join_list = join_nodes + convert_join_strings_to_ast(relation.table, string_joins)
alias_tracker = relation.alias_tracker(join_list)
join_dependency = Polyamorous::JoinDependency.new(relation.klass, relation.table, association_joins, Arel::Nodes::OuterJoin)
join_dependency.instance_variable_set(:@alias_tracker, alias_tracker)
join_nodes.each do |join|
join_dependency.send(:alias_tracker).aliases[join.left.name.downcase] = 1
end
join_dependency
end
def convert_join_strings_to_ast(table, joins)
joins.map! { |join| table.create_string_join(Arel.sql(join)) unless join.blank? }
joins.compact!
joins
end
def build_or_find_association(name, parent = @base, klass = nil)
find_association(name, parent, klass) or build_association(name, parent, klass)
end
def find_association(name, parent = @base, klass = nil)
@join_dependency.instance_variable_get(:@join_root).children.detect do |assoc|
assoc.reflection.name == name && assoc.table &&
(@associations_pot.empty? || @associations_pot[assoc] == parent || !@associations_pot.key?(assoc)) &&
(!klass || assoc.reflection.klass == klass)
end
end
def build_association(name, parent = @base, klass = nil)
jd = Polyamorous::JoinDependency.new(
parent.base_klass,
parent.table,
Polyamorous::Join.new(name, @join_type, klass),
@join_type
)
found_association = jd.instance_variable_get(:@join_root).children.last
@associations_pot[found_association] = parent
# TODO maybe we dont need to push associations here, we could loop
# through the @associations_pot instead
@join_dependency.instance_variable_get(:@join_root).children.push found_association
# Builds the arel nodes properly for this association
@tables_pot[found_association] = @join_dependency.construct_tables_for_association!(jd.instance_variable_get(:@join_root), found_association)
# Leverage the stashed association functionality in AR
@object = @object.joins(jd)
found_association
end
def extract_joins(association)
parent = @join_dependency.instance_variable_get(:@join_root)
reflection = association.reflection
join_constraints = association.join_constraints_with_tables(
parent.table,
parent.base_klass,
Arel::Nodes::OuterJoin,
@join_dependency.instance_variable_get(:@alias_tracker),
@tables_pot[association]
)
join_constraints.to_a.flatten
end
end
end
end
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/lib/polyamorous/tree_node.rb | lib/polyamorous/tree_node.rb | module Polyamorous
module TreeNode
def add_to_tree(hash)
raise NotImplementedError
end
end
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/lib/polyamorous/polyamorous.rb | lib/polyamorous/polyamorous.rb | ActiveSupport.on_load(:active_record) do
module Polyamorous
InnerJoin = Arel::Nodes::InnerJoin
OuterJoin = Arel::Nodes::OuterJoin
JoinDependency = ::ActiveRecord::Associations::JoinDependency
JoinAssociation = ::ActiveRecord::Associations::JoinDependency::JoinAssociation
end
require 'polyamorous/tree_node'
require 'polyamorous/join'
require 'polyamorous/swapping_reflection_class'
require 'polyamorous/activerecord/join_association'
require 'polyamorous/activerecord/join_dependency'
require 'polyamorous/activerecord/reflection'
if ::ActiveRecord.version >= ::Gem::Version.new("7.2") && ::ActiveRecord.version < ::Gem::Version.new("7.2.2.1")
require "polyamorous/activerecord/join_association_7_2"
end
ActiveRecord::Reflection::AbstractReflection.send(:prepend, Polyamorous::ReflectionExtensions)
Polyamorous::JoinDependency.send(:prepend, Polyamorous::JoinDependencyExtensions)
Polyamorous::JoinDependency.singleton_class.send(:prepend, Polyamorous::JoinDependencyExtensions::ClassMethods)
Polyamorous::JoinAssociation.send(:prepend, Polyamorous::JoinAssociationExtensions)
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/lib/polyamorous/swapping_reflection_class.rb | lib/polyamorous/swapping_reflection_class.rb | module Polyamorous
module SwappingReflectionClass
def swapping_reflection_klass(reflection, klass)
new_reflection = reflection.clone
new_reflection.instance_variable_set(:@options, reflection.options.clone)
new_reflection.options.delete(:polymorphic)
new_reflection.instance_variable_set(:@klass, klass)
yield new_reflection
end
end
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/lib/polyamorous/join.rb | lib/polyamorous/join.rb | module Polyamorous
class Join
include TreeNode
attr_accessor :name
attr_reader :type, :klass
def initialize(name, type = InnerJoin, klass = nil)
@name = name
@type = convert_to_arel_join_type(type)
@klass = convert_to_class(klass) if klass
end
def klass=(klass)
@klass = convert_to_class(klass) if klass
end
def type=(type)
@type = convert_to_arel_join_type(type) if type
end
def hash
[@name, @type, @klass].hash
end
def eql?(other)
self.class == other.class &&
self.name == other.name &&
self.type == other.type &&
self.klass == other.klass
end
alias :== :eql?
def add_to_tree(hash)
hash[self] ||= {}
end
private
def convert_to_arel_join_type(type)
case type
when 'inner', :inner
InnerJoin
when 'outer', :outer
OuterJoin
when Class
if [InnerJoin, OuterJoin].include? type
type
else
raise ArgumentError, "#{type} cannot be converted to an ARel join type"
end
else
raise ArgumentError, "#{type} cannot be converted to an ARel join type"
end
end
def convert_to_class(value)
case value
when String, Symbol
Kernel.const_get(value)
when Class
value
else
raise ArgumentError, "#{value} cannot be converted to a Class"
end
end
end
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/lib/polyamorous/activerecord/join_dependency.rb | lib/polyamorous/activerecord/join_dependency.rb | module Polyamorous
module JoinDependencyExtensions
# Replaces ActiveRecord::Associations::JoinDependency#build
def build(associations, base_klass)
associations.map do |name, right|
if name.is_a? Join
reflection = find_reflection base_klass, name.name
reflection.check_validity!
reflection.check_eager_loadable!
klass = if reflection.polymorphic?
name.klass || base_klass
else
reflection.klass
end
JoinAssociation.new(reflection, build(right, klass), name.klass, name.type)
else
reflection = find_reflection base_klass, name
reflection.check_validity!
reflection.check_eager_loadable!
if reflection.polymorphic?
raise ActiveRecord::EagerLoadPolymorphicError.new(reflection)
end
JoinAssociation.new(reflection, build(right, reflection.klass))
end
end
end
def join_constraints(joins_to_add, alias_tracker, references)
@alias_tracker = alias_tracker
@joined_tables = {}
@references = {}
references.each do |table_name|
@references[table_name.to_sym] = table_name if table_name.is_a?(String)
end
joins = make_join_constraints(join_root, join_type)
joins.concat joins_to_add.flat_map { |oj|
if join_root.match?(oj.join_root) && join_root.table.name == oj.join_root.table.name
walk join_root, oj.join_root, oj.join_type
else
make_join_constraints(oj.join_root, oj.join_type)
end
}
end
def construct_tables_for_association!(join_root, association)
tables = table_aliases_for(join_root, association)
association.table = tables.first
tables
end
private
def table_aliases_for(parent, node)
@joined_tables ||= {}
node.reflection.chain.map { |reflection|
table, terminated = @joined_tables[reflection]
root = reflection == node.reflection
if table && (!root || !terminated)
@joined_tables[reflection] = [table, true] if root
table
else
table = alias_tracker.aliased_table_for(reflection.klass.arel_table) do
name = reflection.alias_candidate(parent.table_name)
root ? name : "#{name}_join"
end
@joined_tables[reflection] ||= [table, root] if join_type == Arel::Nodes::OuterJoin
table
end
}
end
module ClassMethods
# Prepended before ActiveRecord::Associations::JoinDependency#walk_tree
#
def walk_tree(associations, hash)
case associations
when TreeNode
associations.add_to_tree(hash)
when Hash
associations.each do |k, v|
cache =
if TreeNode === k
k.add_to_tree(hash)
else
hash[k] ||= {}
end
walk_tree(v, cache)
end
else
super(associations, hash)
end
end
end
end
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/lib/polyamorous/activerecord/join_association.rb | lib/polyamorous/activerecord/join_association.rb | module Polyamorous
module JoinAssociationExtensions
include SwappingReflectionClass
def self.prepended(base)
base.class_eval { attr_reader :join_type }
end
def initialize(reflection, children, polymorphic_class = nil, join_type = Arel::Nodes::InnerJoin)
@join_type = join_type
if polymorphic_class && ::ActiveRecord::Base > polymorphic_class
swapping_reflection_klass(reflection, polymorphic_class) do |reflection|
super(reflection, children)
self.reflection.options[:polymorphic] = true
end
else
super(reflection, children)
end
end
# Same as #join_constraints, but instead of constructing tables from the
# given block, uses the ones passed
def join_constraints_with_tables(foreign_table, foreign_klass, join_type, alias_tracker, tables)
joins = []
chain = []
reflection.chain.each.with_index do |reflection, i|
table = tables[i]
@table ||= table
chain << [reflection, table]
end
# The chain starts with the target table, but we want to end with it here (makes
# more sense in this context), so we reverse
chain.reverse_each do |reflection, table|
klass = reflection.klass
join_scope = reflection.join_scope(table, foreign_table, foreign_klass)
unless join_scope.references_values.empty?
join_dependency = join_scope.construct_join_dependency(
join_scope.eager_load_values | join_scope.includes_values, Arel::Nodes::OuterJoin
)
join_scope.joins!(join_dependency)
end
arel = join_scope.arel(alias_tracker.aliases)
nodes = arel.constraints.first
if nodes.is_a?(Arel::Nodes::And)
others = nodes.children.extract! do |node|
!Arel.fetch_attribute(node) { |attr| attr.relation.name == table.name }
end
end
joins << table.create_join(table, table.create_on(nodes), join_type)
if others && !others.empty?
joins.concat arel.join_sources
append_constraints(joins.last, others)
end
# The current table in this iteration becomes the foreign table in the next
foreign_table, foreign_klass = table, klass
end
joins
end
end
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/lib/polyamorous/activerecord/join_association_7_2.rb | lib/polyamorous/activerecord/join_association_7_2.rb | module Polyamorous
module JoinAssociationExtensions
# Same as #join_constraints, but instead of constructing tables from the
# given block, uses the ones passed
def join_constraints_with_tables(foreign_table, foreign_klass, join_type, alias_tracker, tables)
joins = []
chain = []
reflection.chain.each.with_index do |reflection, i|
table = tables[i]
@table ||= table
chain << [reflection, table]
end
base_klass.with_connection do |connection|
# The chain starts with the target table, but we want to end with it here (makes
# more sense in this context), so we reverse
chain.reverse_each do |reflection, table|
klass = reflection.klass
join_scope = reflection.join_scope(table, foreign_table, foreign_klass)
unless join_scope.references_values.empty?
join_dependency = join_scope.construct_join_dependency(
join_scope.eager_load_values | join_scope.includes_values, Arel::Nodes::OuterJoin
)
join_scope.joins!(join_dependency)
end
arel = join_scope.arel(alias_tracker.aliases)
nodes = arel.constraints.first
if nodes.is_a?(Arel::Nodes::And)
others = nodes.children.extract! do |node|
!Arel.fetch_attribute(node) { |attr| attr.relation.name == table.name }
end
end
joins << table.create_join(table, table.create_on(nodes), join_type)
if others && !others.empty?
joins.concat arel.join_sources
append_constraints(connection, joins.last, others)
end
# The current table in this iteration becomes the foreign table in the next
foreign_table, foreign_klass = table, klass
end
joins
end
end
end
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
activerecord-hackery/ransack | https://github.com/activerecord-hackery/ransack/blob/271cb42db33a2fe168f74b4844b9198253f52674/lib/polyamorous/activerecord/reflection.rb | lib/polyamorous/activerecord/reflection.rb | module Polyamorous
module ReflectionExtensions
def join_scope(table, foreign_table, foreign_klass)
if respond_to?(:polymorphic?) && polymorphic?
super.where!(foreign_table[foreign_type].eq(klass.name))
else
super
end
end
end
end
| ruby | MIT | 271cb42db33a2fe168f74b4844b9198253f52674 | 2026-01-04T15:41:47.582999Z | false |
aasm/aasm | https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/test/minitest_helper.rb | test/minitest_helper.rb | $LOAD_PATH.unshift(File.expand_path(File.dirname(__FILE__)))
$LOAD_PATH.unshift(File.expand_path(File.join(File.dirname(__FILE__), '..', 'spec', 'models')))
$LOAD_PATH.unshift(File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib')))
require 'aasm'
require 'minitest/autorun'
require 'aasm/minitest_spec'
require 'pry'
# require 'ruby-debug'; Debugger.settings[:autoeval] = true; debugger; rubys_debugger = 'annoying'
# require 'ruby-debug/completion'
# require 'pry'
SEQUEL_DB = defined?(JRUBY_VERSION) ? 'jdbc:sqlite::memory:' : 'sqlite:/'
def load_schema
require 'logger'
config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml'))
ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log")
ActiveRecord::Base.establish_connection(config['sqlite3'])
require File.dirname(__FILE__) + "/database.rb"
end
# Dynamoid initialization
begin
require 'dynamoid'
if Gem::Version.new(Dynamoid::VERSION) >= Gem::Version.new('3.0.0')
require 'aws-sdk-dynamodb'
else
require 'aws-sdk-resources'
end
ENV['ACCESS_KEY'] ||= 'abcd'
ENV['SECRET_KEY'] ||= '1234'
Aws.config.update({
region: 'us-west-2',
credentials: Aws::Credentials.new(ENV['ACCESS_KEY'], ENV['SECRET_KEY'])
})
Dynamoid.configure do |config|
config.namespace = 'dynamoid_tests'
config.endpoint = "http://#{ENV['DYNAMODB_HOST'] || '127.0.0.1'}:30180"
config.warn_on_scan = false
end
Dynamoid.logger.level = Logger::FATAL
class Minitest::Spec
before do
Dynamoid.adapter.list_tables.each do |table|
Dynamoid.adapter.delete_table(table) if table =~ /^#{Dynamoid::Config.namespace}/
end
Dynamoid.adapter.tables.clear
end
end
rescue LoadError
# Without Dynamoid settings
end
# example model classes
Dir[File.expand_path(File.join(File.dirname(__FILE__), '..', 'spec', 'models')) + '/*.rb'].sort.each { |f| require File.expand_path(f) }
| ruby | MIT | 726a578808e0f403bfd24e505f9a45319670a6b7 | 2026-01-04T15:43:55.088186Z | false |
aasm/aasm | https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/test/unit/minitest_matcher_test.rb | test/unit/minitest_matcher_test.rb | require 'minitest_helper'
class StateMachineTest < Minitest::Spec
let(:simple) { SimpleExample.new }
let(:multiple) { SimpleMultipleExample.new }
describe 'transition_from' do
it "works for simple state machines" do
simple.must_transition_from :initialised, to: :filled_out, on_event: :fill_out
simple.wont_transition_from :initialised, to: :authorised, on_event: :fill_out
end
it "works for multiple state machines" do
multiple.must_transition_from :standing, to: :walking, on_event: :walk, on: :move
multiple.wont_transition_from :standing, to: :running, on_event: :walk, on: :move
multiple.must_transition_from :sleeping, to: :processing, on_event: :start, on: :work
multiple.wont_transition_from :sleeping, to: :sleeping, on_event: :start, on: :work
end
end
describe 'allow_transition_to' do
it "works for simple state machines" do
simple.must_allow_transition_to :filled_out
simple.wont_allow_transition_to :authorised
end
it "works for multiple state machines" do
multiple.must_allow_transition_to :walking, on: :move
multiple.wont_allow_transition_to :standing, on: :move
multiple.must_allow_transition_to :processing, on: :work
multiple.wont_allow_transition_to :sleeping, on: :work
end
end
describe "have_state" do
it "works for simple state machines" do
simple.must_have_state :initialised
simple.wont_have_state :filled_out
simple.fill_out
simple.must_have_state :filled_out
end
it "works for multiple state machines" do
multiple.must_have_state :standing, on: :move
multiple.wont_have_state :walking, on: :move
multiple.walk
multiple.must_have_state :walking, on: :move
multiple.must_have_state :sleeping, on: :work
multiple.wont_have_state :processing, on: :work
multiple.start
multiple.must_have_state :processing, on: :work
end
end
describe "allow_event" do
it "works for simple state machines" do
simple.must_allow_event :fill_out
simple.wont_allow_event :authorise
simple.fill_out
simple.must_allow_event :authorise
end
it "works for multiple state machines" do
multiple.must_allow_event :walk, on: :move
multiple.wont_allow_event :hold, on: :move
multiple.walk
multiple.must_allow_event :hold, on: :move
multiple.must_allow_event :start, on: :work
multiple.wont_allow_event :stop, on: :work
multiple.start
multiple.must_allow_event :stop, on: :work
end
end
end
| ruby | MIT | 726a578808e0f403bfd24e505f9a45319670a6b7 | 2026-01-04T15:43:55.088186Z | false |
aasm/aasm | https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/spec_helper.rb | spec/spec_helper.rb | require 'simplecov'
SimpleCov.start do
add_filter '/spec/'
end
if ENV['CI'] == 'true'
require 'simplecov-cobertura'
SimpleCov.formatter = SimpleCov::Formatter::CoberturaFormatter
end
$LOAD_PATH.unshift(File.expand_path(File.dirname(__FILE__)))
$LOAD_PATH.unshift(File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib')))
require 'aasm'
require 'rspec'
require 'aasm/rspec'
require 'i18n'
require 'pry'
# require 'ruby-debug'; Debugger.settings[:autoeval] = true; debugger; rubys_debugger = 'annoying'
# require 'ruby-debug/completion'
# require 'pry'
SEQUEL_DB = defined?(JRUBY_VERSION) ? 'jdbc:sqlite::memory:' : 'sqlite:/'
def load_schema
require 'logger'
config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml'))
ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log")
ActiveRecord::Base.establish_connection(config['sqlite3'])
require File.dirname(__FILE__) + "/database.rb"
end
# custom spec helpers
Dir[File.dirname(__FILE__) + "/spec_helpers/**/*.rb"].sort.each { |f| require File.expand_path(f) }
# example model classes
Dir[File.dirname(__FILE__) + "/models/*.rb"].sort.each { |f| require File.expand_path(f) }
I18n.load_path << 'spec/en.yml'
I18n.enforce_available_locales = false
I18n.default_locale = :en
| ruby | MIT | 726a578808e0f403bfd24e505f9a45319670a6b7 | 2026-01-04T15:43:55.088186Z | false |
aasm/aasm | https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/database.rb | spec/database.rb | ActiveRecord::Migration.suppress_messages do
%w{gates multiple_gates readers writers transients simples no_scopes multiple_no_scopes no_direct_assignments multiple_no_direct_assignments thieves multiple_thieves localizer_test_models persisted_states provided_and_persisted_states with_enums with_enum_without_columns multiple_with_enum_without_columns with_true_enums with_false_enums false_states multiple_with_enums multiple_with_true_enums multiple_with_false_enums multiple_false_states readme_jobs}.each do |table_name|
ActiveRecord::Migration.create_table table_name, :force => true do |t|
t.string "aasm_state"
end
end
%w(simple_new_dsls multiple_simple_new_dsls implemented_abstract_class_dsls users multiple_namespaceds).each do |table_name|
ActiveRecord::Migration.create_table table_name, :force => true do |t|
t.string "status"
end
end
ActiveRecord::Migration.create_table "complex_active_record_examples", :force => true do |t|
t.string "left"
t.string "right"
end
ActiveRecord::Migration.create_table "works", :force => true do |t|
t.string "status"
end
%w(validators multiple_validators workers invalid_persistors multiple_invalid_persistors silent_persistors multiple_silent_persistors active_record_callbacks).each do |table_name|
ActiveRecord::Migration.create_table table_name, :force => true do |t|
t.string "name"
t.string "status"
end
end
%w(transactors no_lock_transactors lock_transactors lock_no_wait_transactors no_transactors multiple_transactors).each do |table_name|
ActiveRecord::Migration.create_table table_name, :force => true do |t|
t.string "name"
t.string "status"
t.integer "worker_id"
end
end
ActiveRecord::Migration.create_table "fathers", :force => true do |t|
t.string "aasm_state"
t.string "type"
end
ActiveRecord::Migration.create_table "basic_active_record_two_state_machines_examples", :force => true do |t|
t.string "search"
t.string "sync"
end
ActiveRecord::Migration.create_table "instance_level_skip_validation_examples", :force => true do |t|
t.string "state"
t.string "some_string"
end
ActiveRecord::Migration.create_table "timestamp_examples", :force => true do |t|
t.string "aasm_state"
t.datetime "opened_at"
end
end
| ruby | MIT | 726a578808e0f403bfd24e505f9a45319670a6b7 | 2026-01-04T15:43:55.088186Z | false |
aasm/aasm | https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/models/guardian_without_from_specified.rb | spec/models/guardian_without_from_specified.rb | class GuardianWithoutFromSpecified
include AASM
aasm do
state :alpha, :initial => true
state :beta
state :gamma
event :use_guards_where_the_first_fails do
transitions :to => :beta, :guard => :fail
transitions :to => :gamma, :guard => :succeed
end
end
def fail; false; end
def succeed; true; end
end
| ruby | MIT | 726a578808e0f403bfd24e505f9a45319670a6b7 | 2026-01-04T15:43:55.088186Z | false |
aasm/aasm | https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/models/class_with_keyword_arguments.rb | spec/models/class_with_keyword_arguments.rb | # frozen_string_literal: true
class CallbackWithOptionalKeywordArguments
def initialize(state_machine, my_optional_arg: nil, **_args)
@state_machine = state_machine
@my_optional_arg = my_optional_arg
end
def call
@state_machine.my_attribute = @my_optional_arg if @my_optional_arg
end
end
class CallbackWithRequiredKeywordArguments
def initialize(state_machine, my_required_arg:)
@state_machine = state_machine
@my_required_arg = my_required_arg
end
def call
@state_machine.my_attribute = @my_required_arg
end
end
class ClassWithKeywordArguments
include AASM
aasm do
state :open, :initial => true, :column => :status
state :closed
event :close_forever do
before :_before_close
transitions from: :open,
to: :closed
end
event :close_temporarily do
before :_before_close
transitions from: :open,
to: :closed,
after: [CallbackWithOptionalKeywordArguments]
end
event :close_then_something_else do
before :_before_close
transitions from: :open,
to: :closed,
after: [CallbackWithRequiredKeywordArguments, CallbackWithRequiredKeywordArguments]
end
end
def _before_close
@my_attribute = "closed_forever"
end
attr_accessor :my_attribute
end | ruby | MIT | 726a578808e0f403bfd24e505f9a45319670a6b7 | 2026-01-04T15:43:55.088186Z | false |
aasm/aasm | https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/models/event_with_keyword_arguments.rb | spec/models/event_with_keyword_arguments.rb | class EventWithKeywordArguments
include AASM
aasm do
state :open, :initial => true, :column => :status
state :closed
event :close do
before :_before_close
transitions from: :open, to: :closed
end
event :another_close do
before :_before_another_close
transitions from: :open, to: :closed
end
end
def _before_close(key:)
end
def _before_another_close(foo, key: nil)
end
end
| ruby | MIT | 726a578808e0f403bfd24e505f9a45319670a6b7 | 2026-01-04T15:43:55.088186Z | false |
aasm/aasm | https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/models/foo_callback_multiple.rb | spec/models/foo_callback_multiple.rb | class FooCallbackMultiple
include AASM
aasm(:left) do
state :open, :initial => true, :before_exit => :before_exit
state :closed, :before_enter => :before_enter
state :final
event :close, :success => :success_callback do
transitions :from => [:open], :to => [:closed]
end
event :null do
transitions :from => [:open], :to => [:closed, :final], :guard => :always_false
end
end
aasm(:right, :column => :right) do
state :green, :initial => true
state :yellow
state :red
event :green do
transitions :from => [:yellow], :to => :green
end
event :yellow do
transitions :from => [:green, :red], :to => :yellow
end
event :red do
transitions :from => [:yellow], :to => :red
end
end
def always_false
false
end
def success_callback
end
def before_enter
end
def before_exit
end
end
| ruby | MIT | 726a578808e0f403bfd24e505f9a45319670a6b7 | 2026-01-04T15:43:55.088186Z | false |
aasm/aasm | https://github.com/aasm/aasm/blob/726a578808e0f403bfd24e505f9a45319670a6b7/spec/models/parametrised_event.rb | spec/models/parametrised_event.rb | class ParametrisedEvent
include AASM
aasm do
state :sleeping, :initial => true
state :showering
state :working
state :dating
state :prettying_up
event :wakeup do
transitions :from => :sleeping, :to => [:showering, :working]
end
event :shower do
transitions :from => :sleeping, :to => :showering, :after => :wet_hair, :success => :wear_clothes
end
event :dress do
transitions :from => :sleeping, :to => :working, :after => :wear_clothes, :success => :wear_makeup
transitions :from => :showering, :to => [:working, :dating], :after => Proc.new { |*args| wear_clothes(*args) }, :success => proc { |*args| wear_makeup(*args) }
transitions :from => :showering, :to => :prettying_up, :after => [:condition_hair, :fix_hair], :success => [:touch_up_hair]
end
end
def wear_clothes(shirt_color, trouser_type=nil)
end
def wear_makeup(makeup, moisturizer)
end
def wet_hair(dryer)
end
def condition_hair
end
def fix_hair
end
def touch_up_hair
end
end
| ruby | MIT | 726a578808e0f403bfd24e505f9a45319670a6b7 | 2026-01-04T15:43:55.088186Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.