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/rails-contributors
https://github.com/rails/rails-contributors/blob/dc10cffec6a3e3680e704bf0ddfed5c54cb3cdc9/config/application.rb
config/application.rb
require_relative "boot" require "rails" # Pick the frameworks you want: require "active_model/railtie" # require "active_job/railtie" require "active_record/railtie" # require "active_storage/engine" require "action_controller/railtie" # require "action_mailer/railtie" # require "action_mailbox/engine" # require "action_text/engine" require "action_view/railtie" # require "action_cable/engine" require "rails/test_unit/railtie" # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) require_relative "../lib/bot_killer" module RailsContributors class Application < Rails::Application # Initialize configuration defaults for originally generated Rails version. config.load_defaults 8.0 config.middleware.insert 0, BotKiller # Please, add to the `ignore` list any other `lib` subdirectories that do # not contain `.rb` files, or that should not be reloaded or eager loaded. # Common ones are `templates`, `generators`, or `middleware`, for example. # config.autoload_lib(ignore: %w[assets tasks]) # Configuration for the application, engines, and railties goes here. # # These settings can be overridden in specific environments using the files # in config/environments, which are processed later. # # config.time_zone = "Central Time (US & Canada)" # config.eager_load_paths << Rails.root.join("extras") end end
ruby
MIT
dc10cffec6a3e3680e704bf0ddfed5c54cb3cdc9
2026-01-04T17:44:10.559232Z
false
rails/rails-contributors
https://github.com/rails/rails-contributors/blob/dc10cffec6a3e3680e704bf0ddfed5c54cb3cdc9/config/environment.rb
config/environment.rb
# Load the Rails application. require_relative "application" # Initialize the Rails application. Rails.application.initialize!
ruby
MIT
dc10cffec6a3e3680e704bf0ddfed5c54cb3cdc9
2026-01-04T17:44:10.559232Z
false
rails/rails-contributors
https://github.com/rails/rails-contributors/blob/dc10cffec6a3e3680e704bf0ddfed5c54cb3cdc9/config/puma.rb
config/puma.rb
# This configuration file will be evaluated by Puma. The top-level methods that # are invoked here are part of Puma's configuration DSL. For more information # about methods provided by the DSL, see https://puma.io/puma/Puma/DSL.html. # # Puma starts a configurable number of processes (workers) and each process # serves each request in a thread from an internal thread pool. # # You can control the number of workers using ENV["WEB_CONCURRENCY"]. You # should only set this value when you want to run 2 or more workers. The # default is already 1. You can set it to `auto` to automatically start a worker # for each available processor. # # The ideal number of threads per worker depends both on how much time the # application spends waiting for IO operations and on how much you wish to # prioritize throughput over latency. # # As a rule of thumb, increasing the number of threads will increase how much # traffic a given process can handle (throughput), but due to CRuby's # Global VM Lock (GVL) it has diminishing returns and will degrade the # response time (latency) of the application. # # The default is set to 3 threads as it's deemed a decent compromise between # throughput and latency for the average Rails application. # # Any libraries that use a connection pool or another resource pool should # be configured to provide at least as many connections as the number of # threads. This includes Active Record's `pool` parameter in `database.yml`. threads_count = ENV.fetch("RAILS_MAX_THREADS", 3) threads threads_count, threads_count # Specifies the `port` that Puma will listen on to receive requests; default is 3000. port ENV.fetch("PORT", 3000) # Allow puma to be restarted by `bin/rails restart` command. plugin :tmp_restart # Run the Solid Queue supervisor inside of Puma for single-server deployments. plugin :solid_queue if ENV["SOLID_QUEUE_IN_PUMA"] # Specify the PID file. Defaults to tmp/pids/server.pid in development. # In other environments, only set the PID file if requested. pidfile ENV["PIDFILE"] if ENV["PIDFILE"]
ruby
MIT
dc10cffec6a3e3680e704bf0ddfed5c54cb3cdc9
2026-01-04T17:44:10.559232Z
false
rails/rails-contributors
https://github.com/rails/rails-contributors/blob/dc10cffec6a3e3680e704bf0ddfed5c54cb3cdc9/config/routes.rb
config/routes.rb
Rails.application.routes.draw do get 'contributors/in-time-window/:time_window' => 'contributors#in_time_window', as: 'contributors_in_time_window' resources :contributors, only: 'index' do get 'commits/in-time-window/:time_window' => 'commits#in_time_window', as: 'commits_in_time_window' get 'commits/in-release/:release_id' => 'commits#in_release', as: 'commits_in_release' get 'commits/in-edge' => 'commits#in_edge', as: 'commits_in_edge' resources :commits, only: 'index' end resources :releases, only: 'index' do resources :commits, only: 'index' resources :contributors, only: 'index' end get 'edge/contributors' => 'contributors#in_edge', as: 'contributors_in_edge' resource :faq, only: :show root to: 'contributors#index' end
ruby
MIT
dc10cffec6a3e3680e704bf0ddfed5c54cb3cdc9
2026-01-04T17:44:10.559232Z
false
rails/rails-contributors
https://github.com/rails/rails-contributors/blob/dc10cffec6a3e3680e704bf0ddfed5c54cb3cdc9/config/deploy.rb
config/deploy.rb
lock '~> 3.10' set :application, 'rails-contributors' set :branch, 'main' set :repo_url, 'https://github.com/rails/rails-contributors.git' set :deploy_to, '/home/rails/rails-contributors' set :log_level, :info set :linked_files, %w{config/database.yml config/master.key} set :linked_dirs, %w{log tmp/pids tmp/cache tmp/sockets public/system public/assets rails.git} set :keep_releases, 5 set :bundle_without, %w{development test deployment}.join(' ') set :bundle_gemfile, -> { release_path.join('Gemfile') } set :puma_bind, "unix://#{shared_path}/tmp/sockets/puma.sock" set :puma_systemctl_user, :system
ruby
MIT
dc10cffec6a3e3680e704bf0ddfed5c54cb3cdc9
2026-01-04T17:44:10.559232Z
false
rails/rails-contributors
https://github.com/rails/rails-contributors/blob/dc10cffec6a3e3680e704bf0ddfed5c54cb3cdc9/config/boot.rb
config/boot.rb
ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__) require "bundler/setup" # Set up gems listed in the Gemfile.
ruby
MIT
dc10cffec6a3e3680e704bf0ddfed5c54cb3cdc9
2026-01-04T17:44:10.559232Z
false
rails/rails-contributors
https://github.com/rails/rails-contributors/blob/dc10cffec6a3e3680e704bf0ddfed5c54cb3cdc9/config/initializers/content_security_policy.rb
config/initializers/content_security_policy.rb
# Be sure to restart your server when you modify this file. # Define an application-wide content security policy. # See the Securing Rails Applications Guide for more information: # https://guides.rubyonrails.org/security.html#content-security-policy-header # Rails.application.configure do # config.content_security_policy do |policy| # policy.default_src :self, :https # policy.font_src :self, :https, :data # policy.img_src :self, :https, :data # policy.object_src :none # policy.script_src :self, :https # policy.style_src :self, :https # # Specify URI for violation reports # # policy.report_uri "/csp-violation-report-endpoint" # end # # # Generate session nonces for permitted importmap, inline scripts, and inline styles. # config.content_security_policy_nonce_generator = ->(request) { request.session.id.to_s } # config.content_security_policy_nonce_directives = %w(script-src style-src) # # # Automatically add `nonce` to `javascript_tag`, `javascript_include_tag`, and `stylesheet_link_tag` # # if the corresponding directives are specified in `content_security_policy_nonce_directives`. # # config.content_security_policy_nonce_auto = true # # # Report violations without enforcing the policy. # # config.content_security_policy_report_only = true # end
ruby
MIT
dc10cffec6a3e3680e704bf0ddfed5c54cb3cdc9
2026-01-04T17:44:10.559232Z
false
rails/rails-contributors
https://github.com/rails/rails-contributors/blob/dc10cffec6a3e3680e704bf0ddfed5c54cb3cdc9/config/initializers/filter_parameter_logging.rb
config/initializers/filter_parameter_logging.rb
# Be sure to restart your server when you modify this file. # Configure parameters to be partially matched (e.g. passw matches password) and filtered from the log file. # Use this to limit dissemination of sensitive information. # See the ActiveSupport::ParameterFilter documentation for supported notations and behaviors. Rails.application.config.filter_parameters += [ :passw, :email, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn, :cvv, :cvc ]
ruby
MIT
dc10cffec6a3e3680e704bf0ddfed5c54cb3cdc9
2026-01-04T17:44:10.559232Z
false
rails/rails-contributors
https://github.com/rails/rails-contributors/blob/dc10cffec6a3e3680e704bf0ddfed5c54cb3cdc9/config/initializers/application_controller_renderer.rb
config/initializers/application_controller_renderer.rb
# Be sure to restart your server when you modify this file. # ActiveSupport::Reloader.to_prepare do # ApplicationController.renderer.defaults.merge!( # http_host: 'example.org', # https: false # ) # end
ruby
MIT
dc10cffec6a3e3680e704bf0ddfed5c54cb3cdc9
2026-01-04T17:44:10.559232Z
false
rails/rails-contributors
https://github.com/rails/rails-contributors/blob/dc10cffec6a3e3680e704bf0ddfed5c54cb3cdc9/config/initializers/core_extensions.rb
config/initializers/core_extensions.rb
UNF_NORMALIZER = UNF::Normalizer.new module StringExtensions def parameterize super.gsub('ß', 'ss').gsub('ø', 'o') end def nfc UNF_NORMALIZER.normalize(self, :nfc) end end String.prepend(StringExtensions)
ruby
MIT
dc10cffec6a3e3680e704bf0ddfed5c54cb3cdc9
2026-01-04T17:44:10.559232Z
false
rails/rails-contributors
https://github.com/rails/rails-contributors/blob/dc10cffec6a3e3680e704bf0ddfed5c54cb3cdc9/config/initializers/new_framework_defaults_8_1.rb
config/initializers/new_framework_defaults_8_1.rb
# Be sure to restart your server when you modify this file. # # This file eases your Rails 8.1 framework defaults upgrade. # # Uncomment each configuration one by one to switch to the new default. # Once your application is ready to run with all new defaults, you can remove # this file and set the `config.load_defaults` to `8.1`. # # Read the Guide for Upgrading Ruby on Rails for more info on each option. # https://guides.rubyonrails.org/upgrading_ruby_on_rails.html ### # Skips escaping HTML entities and line separators. When set to `false`, the # JSON renderer no longer escapes these to improve performance. # # Example: # class PostsController < ApplicationController # def index # render json: { key: "\u2028\u2029<>&" } # end # end # # Renders `{"key":"\u2028\u2029\u003c\u003e\u0026"}` with the previous default, but `{"key":"

<>&"}` with the config # set to `false`. # # Applications that want to keep the escaping behavior can set the config to `true`. #++ # Rails.configuration.action_controller.escape_json_responses = false ### # Skips escaping LINE SEPARATOR (U+2028) and PARAGRAPH SEPARATOR (U+2029) in JSON. # # Historically these characters were not valid inside JavaScript literal strings but that changed in ECMAScript 2019. # As such it's no longer a concern in modern browsers: https://caniuse.com/mdn-javascript_builtins_json_json_superset. #++ # Rails.configuration.active_support.escape_js_separators_in_json = false ### # Raises an error when order dependent finder methods (e.g. `#first`, `#second`) are called without `order` values # on the relation, and the model does not have any order columns (`implicit_order_column`, `query_constraints`, or # `primary_key`) to fall back on. # # The current behavior of not raising an error has been deprecated, and this configuration option will be removed in # Rails 8.2. #++ # Rails.configuration.active_record.raise_on_missing_required_finder_order_columns = true ### # Controls how Rails handles path relative URL redirects. # When set to `:raise`, Rails will raise an `ActionController::Redirecting::UnsafeRedirectError` # for relative URLs without a leading slash, which can help prevent open redirect vulnerabilities. # # Example: # redirect_to "example.com" # Raises UnsafeRedirectError # redirect_to "@attacker.com" # Raises UnsafeRedirectError # redirect_to "/safe/path" # Works correctly # # Applications that want to allow these redirects can set the config to `:log` (previous default) # to only log warnings, or `:notify` to send ActiveSupport notifications. #++ # Rails.configuration.action_controller.action_on_path_relative_redirect = :raise ### # Use a Ruby parser to track dependencies between Action View templates #++ # Rails.configuration.action_view.render_tracker = :ruby ### # When enabled, hidden inputs generated by `form_tag`, `token_tag`, `method_tag`, and the hidden parameter fields # included in `button_to` forms will omit the `autocomplete="off"` attribute. # # Applications that want to keep generating the `autocomplete` attribute for those tags can set it to `false`. #++ # Rails.configuration.action_view.remove_hidden_field_autocomplete = true
ruby
MIT
dc10cffec6a3e3680e704bf0ddfed5c54cb3cdc9
2026-01-04T17:44:10.559232Z
false
rails/rails-contributors
https://github.com/rails/rails-contributors/blob/dc10cffec6a3e3680e704bf0ddfed5c54cb3cdc9/config/initializers/page_cache_logger.rb
config/initializers/page_cache_logger.rb
ActiveSupport::Notifications.subscribe("write_page.action_controller") do |event| Rails.logger.info "Page cached: #{event.payload[:path]}" end ActiveSupport::Notifications.subscribe("expire_page.action_controller") do |event| Rails.logger.info "Page expired: #{event.payload[:path]}" end
ruby
MIT
dc10cffec6a3e3680e704bf0ddfed5c54cb3cdc9
2026-01-04T17:44:10.559232Z
false
rails/rails-contributors
https://github.com/rails/rails-contributors/blob/dc10cffec6a3e3680e704bf0ddfed5c54cb3cdc9/config/initializers/nfc_attribute_normalization.rb
config/initializers/nfc_attribute_normalization.rb
require 'nfc_attribute_normalizer' class ActiveRecord::Base extend NFCAttributeNormalizer end
ruby
MIT
dc10cffec6a3e3680e704bf0ddfed5c54cb3cdc9
2026-01-04T17:44:10.559232Z
false
rails/rails-contributors
https://github.com/rails/rails-contributors/blob/dc10cffec6a3e3680e704bf0ddfed5c54cb3cdc9/config/initializers/wrap_parameters.rb
config/initializers/wrap_parameters.rb
# Be sure to restart your server when you modify this file. # This file contains settings for ActionController::ParamsWrapper which # is enabled by default. # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. ActiveSupport.on_load(:action_controller) do wrap_parameters format: [:json] end # To enable root element in JSON for ActiveRecord objects. # ActiveSupport.on_load(:active_record) do # self.include_root_in_json = true # end
ruby
MIT
dc10cffec6a3e3680e704bf0ddfed5c54cb3cdc9
2026-01-04T17:44:10.559232Z
false
rails/rails-contributors
https://github.com/rails/rails-contributors/blob/dc10cffec6a3e3680e704bf0ddfed5c54cb3cdc9/config/initializers/inflections.rb
config/initializers/inflections.rb
# Be sure to restart your server when you modify this file. # Add new inflection rules using the following format. Inflections # are locale specific, and you may define rules for as many different # locales as you wish. All of these examples are active by default: # ActiveSupport::Inflector.inflections(:en) do |inflect| # inflect.plural /^(ox)$/i, "\\1en" # inflect.singular /^(ox)en/i, "\\1" # inflect.irregular "person", "people" # inflect.uncountable %w( fish sheep ) # end # These inflection rules are supported but not enabled by default: # ActiveSupport::Inflector.inflections(:en) do |inflect| # inflect.acronym "RESTful" # end
ruby
MIT
dc10cffec6a3e3680e704bf0ddfed5c54cb3cdc9
2026-01-04T17:44:10.559232Z
false
rails/rails-contributors
https://github.com/rails/rails-contributors/blob/dc10cffec6a3e3680e704bf0ddfed5c54cb3cdc9/config/initializers/permissions_policy.rb
config/initializers/permissions_policy.rb
# Be sure to restart your server when you modify this file. # Define an application-wide HTTP permissions policy. For further # information see: https://developers.google.com/web/updates/2018/06/feature-policy # Rails.application.config.permissions_policy do |policy| # policy.camera :none # policy.gyroscope :none # policy.microphone :none # policy.usb :none # policy.fullscreen :self # policy.payment :self, "https://secure.example.com" # end
ruby
MIT
dc10cffec6a3e3680e704bf0ddfed5c54cb3cdc9
2026-01-04T17:44:10.559232Z
false
rails/rails-contributors
https://github.com/rails/rails-contributors/blob/dc10cffec6a3e3680e704bf0ddfed5c54cb3cdc9/config/initializers/ensure_rails_git_is_cloned.rb
config/initializers/ensure_rails_git_is_cloned.rb
RAILS_GIT = "#{Rails.root}/rails.git" unless Dir.exist?(RAILS_GIT) puts <<~EOS Please, mirror the Rails repository using the command git clone --mirror https://github.com/rails/rails.git from the host computer. Once that is done, if you want to run the website please populate the database with dc/sync This takes a while and it is not necessary if you only want to run the test suite. EOS exit 1 end
ruby
MIT
dc10cffec6a3e3680e704bf0ddfed5c54cb3cdc9
2026-01-04T17:44:10.559232Z
false
rails/rails-contributors
https://github.com/rails/rails-contributors/blob/dc10cffec6a3e3680e704bf0ddfed5c54cb3cdc9/config/initializers/assets.rb
config/initializers/assets.rb
# Be sure to restart your server when you modify this file. # Version of your assets, change this if you want to expire all your assets. Rails.application.config.assets.version = "1.0" # Add additional assets to the asset load path. # Rails.application.config.assets.paths << Emoji.images_path
ruby
MIT
dc10cffec6a3e3680e704bf0ddfed5c54cb3cdc9
2026-01-04T17:44:10.559232Z
false
rails/rails-contributors
https://github.com/rails/rails-contributors/blob/dc10cffec6a3e3680e704bf0ddfed5c54cb3cdc9/config/initializers/backtrace_silencers.rb
config/initializers/backtrace_silencers.rb
# Be sure to restart your server when you modify this file. # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. # Rails.backtrace_cleaner.add_silencer { |line| /my_noisy_library/.match?(line) } # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code # by setting BACKTRACE=1 before calling your invocation, like "BACKTRACE=1 ./bin/rails runner 'MyClass.perform'". Rails.backtrace_cleaner.remove_silencers! if ENV["BACKTRACE"]
ruby
MIT
dc10cffec6a3e3680e704bf0ddfed5c54cb3cdc9
2026-01-04T17:44:10.559232Z
false
rails/rails-contributors
https://github.com/rails/rails-contributors/blob/dc10cffec6a3e3680e704bf0ddfed5c54cb3cdc9/config/initializers/mime_types.rb
config/initializers/mime_types.rb
# Be sure to restart your server when you modify this file. # Add new mime types for use in respond_to blocks: # Mime::Type.register "text/richtext", :rtf
ruby
MIT
dc10cffec6a3e3680e704bf0ddfed5c54cb3cdc9
2026-01-04T17:44:10.559232Z
false
rails/rails-contributors
https://github.com/rails/rails-contributors/blob/dc10cffec6a3e3680e704bf0ddfed5c54cb3cdc9/config/puma/production.rb
config/puma/production.rb
#!/usr/bin/env puma shared_path = "/home/rails/rails-contributors/shared" directory '/home/rails/rails-contributors/current' rackup "/home/rails/rails-contributors/current/config.ru" environment 'production' pidfile "#{shared_path}/tmp/pids/puma.pid" state_path "#{shared_path}/tmp/pids/puma.state" workers 2 threads 3,3 bind "unix://#{shared_path}/tmp/sockets/puma.sock" restart_command 'bundle exec puma' prune_bundler on_restart do puts 'Refreshing Gemfile' ENV["BUNDLE_GEMFILE"] = "/home/rails/rails-contributors/current/Gemfile" end
ruby
MIT
dc10cffec6a3e3680e704bf0ddfed5c54cb3cdc9
2026-01-04T17:44:10.559232Z
false
rails/rails-contributors
https://github.com/rails/rails-contributors/blob/dc10cffec6a3e3680e704bf0ddfed5c54cb3cdc9/config/deploy/production.rb
config/deploy/production.rb
DOCS_SERVER_IP = '138.197.6.175' set :ssh_options, port: 987 server DOCS_SERVER_IP, user: 'rails', roles: %w(web app db) set :rvm_ruby_version, '3.4.5' set :rvm_custom_path, '/home/rails/.rvm' set :puma_access_log, "journal" set :puma_error_log, "journal" namespace :deploy do after :normalize_assets, :gzip_assets do on release_roles(fetch(:assets_roles)) do assets_path = release_path.join('public', fetch(:assets_prefix)) within assets_path do execute :find, ". \\( -name '*.js' -o -name '*.css' \\) -print0 | xargs -0 gzip --keep --best --quiet --force" end end end end after 'deploy:finished', :trigger_webhook do run_locally do execute "curl -X POST http://#{DOCS_SERVER_IP}:9292/rails-master-hook" end end after 'deploy:finished', 'deploy:cleanup_assets'
ruby
MIT
dc10cffec6a3e3680e704bf0ddfed5c54cb3cdc9
2026-01-04T17:44:10.559232Z
false
rails/rails-contributors
https://github.com/rails/rails-contributors/blob/dc10cffec6a3e3680e704bf0ddfed5c54cb3cdc9/config/environments/test.rb
config/environments/test.rb
# The test environment is used exclusively to run your application's # test suite. You never need to work with it otherwise. Remember that # your test database is "scratch space" for the test suite and is wiped # and recreated between test runs. Don't rely on the data there! Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # While tests run files are not watched, reloading is not necessary. config.enable_reloading = false # Eager loading loads your entire application. When running a single test locally, # this is usually not necessary, and can slow down your test suite. However, it's # recommended that you enable it in continuous integration systems to ensure eager # loading is working properly before deploying your code. config.eager_load = ENV["CI"].present? # Configure public file server for tests with cache-control for performance. config.public_file_server.headers = { "cache-control" => "public, max-age=3600" } # Show full error reports. config.consider_all_requests_local = true config.action_controller.perform_caching = false config.cache_store = :null_store # Render exception templates for rescuable exceptions and raise for other exceptions. config.action_dispatch.show_exceptions = :rescuable # Disable request forgery protection in test environment. config.action_controller.allow_forgery_protection = false # Print deprecation notices to the stderr. config.active_support.deprecation = :stderr # Raises error for missing translations. # config.i18n.raise_on_missing_translations = true # Annotate rendered view with file names. # config.action_view.annotate_rendered_view_with_filenames = true # Raise error when a before_action's only/except options reference missing actions. config.action_controller.raise_on_missing_callback_actions = true end
ruby
MIT
dc10cffec6a3e3680e704bf0ddfed5c54cb3cdc9
2026-01-04T17:44:10.559232Z
false
rails/rails-contributors
https://github.com/rails/rails-contributors/blob/dc10cffec6a3e3680e704bf0ddfed5c54cb3cdc9/config/environments/development.rb
config/environments/development.rb
require "active_support/core_ext/integer/time" Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # Make code changes take effect immediately without server restart. config.enable_reloading = true # Do not eager load code on boot. config.eager_load = false # Show full error reports. config.consider_all_requests_local = true # Enable server timing. config.server_timing = true # Enable/disable Action Controller caching. By default Action Controller caching is disabled. # Run rails dev:cache to toggle Action Controller caching. if Rails.root.join("tmp/caching-dev.txt").exist? config.action_controller.perform_caching = true config.action_controller.enable_fragment_cache_logging = true config.public_file_server.headers = { "cache-control" => "public, max-age=#{2.days.to_i}" } else config.action_controller.perform_caching = false end # Change to :null_store to avoid any caching. config.cache_store = :memory_store # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raise an error on page load if there are pending migrations. config.active_record.migration_error = :page_load # Highlight code that triggered database queries in logs. config.active_record.verbose_query_logs = true # Append comments with runtime information tags to SQL queries in logs. config.active_record.query_log_tags_enabled = true # Highlight code that triggered redirect in logs. config.action_dispatch.verbose_redirect_logs = true # Debug mode disables concatenation and preprocessing of assets. # This option may cause significant delays in view rendering with a large # number of complex assets. config.assets.debug = true # Suppress logger output for asset requests. config.assets.quiet = true # Raises error for missing translations. # config.i18n.raise_on_missing_translations = true # Annotate rendered view with file names. config.action_view.annotate_rendered_view_with_filenames = true # Raise error when a before_action's only/except options reference missing actions. config.action_controller.raise_on_missing_callback_actions = true end
ruby
MIT
dc10cffec6a3e3680e704bf0ddfed5c54cb3cdc9
2026-01-04T17:44:10.559232Z
false
rails/rails-contributors
https://github.com/rails/rails-contributors/blob/dc10cffec6a3e3680e704bf0ddfed5c54cb3cdc9/config/environments/staging.rb
config/environments/staging.rb
require "active_support/core_ext/integer/time" Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # Code is not reloaded between requests. config.enable_reloading = false # Eager load code on boot for better performance and memory savings (ignored by Rake tasks). config.eager_load = true # Full error reports are disabled. config.consider_all_requests_local = false # Turn on fragment caching in view templates. config.action_controller.perform_caching = true config.action_controller.page_cache_directory = "#{Rails.root}/public/cache" # Cache assets for far-future expiry since they are all digest stamped. config.public_file_server.headers = { "cache-control" => "public, max-age=#{1.year.to_i}" } # Do not fall back to assets pipeline if a precompiled asset is missed. config.assets.compile = false # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.asset_host = "http://assets.example.com" # Assume all access to the app is happening through a SSL-terminating reverse proxy. config.assume_ssl = true # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. config.force_ssl = true # Skip http-to-https redirect for the default health check endpoint. # config.ssl_options = { redirect: { exclude: ->(request) { request.path == "/up" } } } # Log to STDOUT with the current request id as a default log tag. config.log_tags = [ :request_id ] config.logger = ActiveSupport::TaggedLogging.logger(STDOUT) # Change to "debug" to log everything (including potentially personally-identifiable information!). config.log_level = ENV.fetch("RAILS_LOG_LEVEL", "info") # Prevent health checks from clogging up the logs. config.silence_healthcheck_path = "/up" # Don't log any deprecations. config.active_support.report_deprecations = false # Replace the default in-process memory cache store with a durable alternative. # config.cache_store = :mem_cache_store # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation cannot be found). config.i18n.fallbacks = true # Do not dump schema after migrations. config.active_record.dump_schema_after_migration = false # Only use :id for inspections in production. config.active_record.attributes_for_inspect = [ :id ] # Enable DNS rebinding protection and other `Host` header attacks. # config.hosts = [ # "example.com", # Allow requests from example.com # /.*\.example\.com/ # Allow requests from subdomains like `www.example.com` # ] # # Skip DNS rebinding protection for the default health check endpoint. # config.host_authorization = { exclude: ->(request) { request.path == "/up" } } end
ruby
MIT
dc10cffec6a3e3680e704bf0ddfed5c54cb3cdc9
2026-01-04T17:44:10.559232Z
false
rails/rails-contributors
https://github.com/rails/rails-contributors/blob/dc10cffec6a3e3680e704bf0ddfed5c54cb3cdc9/config/environments/production.rb
config/environments/production.rb
require "active_support/core_ext/integer/time" Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # Code is not reloaded between requests. config.enable_reloading = false # Eager load code on boot for better performance and memory savings (ignored by Rake tasks). config.eager_load = true # Full error reports are disabled. config.consider_all_requests_local = false # Turn on fragment caching in view templates. config.action_controller.perform_caching = true config.action_controller.page_cache_directory = "#{Rails.root}/public/cache" # Cache assets for far-future expiry since they are all digest stamped. config.public_file_server.headers = { "cache-control" => "public, max-age=#{1.year.to_i}" } # Do not fall back to assets pipeline if a precompiled asset is missed. config.assets.compile = false # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.asset_host = "http://assets.example.com" # Assume all access to the app is happening through a SSL-terminating reverse proxy. config.assume_ssl = true # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. config.force_ssl = true # Skip http-to-https redirect for the default health check endpoint. # config.ssl_options = { redirect: { exclude: ->(request) { request.path == "/up" } } } # Log to STDOUT with the current request id as a default log tag. config.log_tags = [ :request_id ] config.logger = ActiveSupport::TaggedLogging.logger(STDOUT) # Change to "debug" to log everything (including potentially personally-identifiable information!). config.log_level = ENV.fetch("RAILS_LOG_LEVEL", "info") # Prevent health checks from clogging up the logs. config.silence_healthcheck_path = "/up" # Don't log any deprecations. config.active_support.report_deprecations = false # Replace the default in-process memory cache store with a durable alternative. # config.cache_store = :mem_cache_store # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation cannot be found). config.i18n.fallbacks = true # Do not dump schema after migrations. config.active_record.dump_schema_after_migration = false # Only use :id for inspections in production. config.active_record.attributes_for_inspect = [ :id ] # Enable DNS rebinding protection and other `Host` header attacks. # config.hosts = [ # "example.com", # Allow requests from example.com # /.*\.example\.com/ # Allow requests from subdomains like `www.example.com` # ] # # Skip DNS rebinding protection for the default health check endpoint. # config.host_authorization = { exclude: ->(request) { request.path == "/up" } } end
ruby
MIT
dc10cffec6a3e3680e704bf0ddfed5c54cb3cdc9
2026-01-04T17:44:10.559232Z
false
ejschmitt/jsvars
https://github.com/ejschmitt/jsvars/blob/6a928dc9d0fbe6878384050fe76f4389caec3da2/uninstall.rb
uninstall.rb
# Uninstall hook code here
ruby
MIT
6a928dc9d0fbe6878384050fe76f4389caec3da2
2026-01-04T17:44:24.744730Z
false
ejschmitt/jsvars
https://github.com/ejschmitt/jsvars/blob/6a928dc9d0fbe6878384050fe76f4389caec3da2/install.rb
install.rb
# Install hook code here
ruby
MIT
6a928dc9d0fbe6878384050fe76f4389caec3da2
2026-01-04T17:44:24.744730Z
false
ejschmitt/jsvars
https://github.com/ejschmitt/jsvars/blob/6a928dc9d0fbe6878384050fe76f4389caec3da2/init.rb
init.rb
ActionController::Base.send :include, Jsvars ActionController::Base.send :after_filter, :include_jsvars
ruby
MIT
6a928dc9d0fbe6878384050fe76f4389caec3da2
2026-01-04T17:44:24.744730Z
false
ejschmitt/jsvars
https://github.com/ejschmitt/jsvars/blob/6a928dc9d0fbe6878384050fe76f4389caec3da2/test/jsvars_test.rb
test/jsvars_test.rb
require 'test_helper' class JsvarsTest < ActiveSupport::TestCase # Replace this with your real tests. test "the truth" do assert true end end
ruby
MIT
6a928dc9d0fbe6878384050fe76f4389caec3da2
2026-01-04T17:44:24.744730Z
false
ejschmitt/jsvars
https://github.com/ejschmitt/jsvars/blob/6a928dc9d0fbe6878384050fe76f4389caec3da2/test/test_helper.rb
test/test_helper.rb
require 'rubygems' require 'active_support' require 'active_support/test_case'
ruby
MIT
6a928dc9d0fbe6878384050fe76f4389caec3da2
2026-01-04T17:44:24.744730Z
false
ejschmitt/jsvars
https://github.com/ejschmitt/jsvars/blob/6a928dc9d0fbe6878384050fe76f4389caec3da2/lib/jsvars.rb
lib/jsvars.rb
require 'json' module Jsvars def self.included(base) base.send(:include, InstanceMethods) end module InstanceMethods def jsvars(option = nil) @jsvars ||= Hash.new if option == false @vars_off = true end @jsvars end def include_jsvars jsvars = @jsvars name = 'jsvars' return unless jsvars && response && response.content_type && response.content_type[/html|fbml/i] return if @vars_off js_assignments = [] jsvars.each do |variable, value| js_assignments << if variable.to_s[/\./] # allows usage like jsvars['myObj.myVar.myValue'] = "number" object_tests = [] objects = variable.split('.') (0...objects.length - 1).each do |i| object_name = objects[0..i].join('.') object_tests << " if (#{ object_name } === undefined) { #{ "var" if i == 0 } #{ object_name } = {}; } " end object_tests.join + "#{ variable } = #{ value.to_json };" else " if (typeof(#{ variable }) === 'object') { jsvars.objExtend(#{ variable }, #{ value.to_json }); } else { var #{ variable } = #{ value.to_json }; } " end end methods = ' var jsvars = { objExtend: function (mainObject) { for (var i = 1; i < arguments.length; i += 1) { for (prop in arguments[i]){ if (arguments[i].hasOwnProperty(prop)) { mainObject[prop] = (arguments[i][prop]); } } } return mainObject; } } ' methods = methods.gsub(/\n|\r|\t/, ' ').squeeze(' ') added_script = "<!-- added by the #{ name } plugin --> <script type='text/javascript'> #{ methods } #{ js_assignments.join } </script> <!-- end #{ name } plugin code -->" if index = response.body.index(/<\/body>/i) response.body.insert index, added_script else response.body << added_script end end end end
ruby
MIT
6a928dc9d0fbe6878384050fe76f4389caec3da2
2026-01-04T17:44:24.744730Z
false
gjtorikian/tailwind_merge
https://github.com/gjtorikian/tailwind_merge/blob/83ef21d415234e01c1f7188d64f37ebaec9c21ea/test/test_malicious_input.rb
test/test_malicious_input.rb
# frozen_string_literal: true require "test_helper" class TestMaliciousInput < Minitest::Test def setup @merger = TailwindMerge::Merger.new end def test_handles_wonky_input assert_equal("block", @merger.merge(" block")) assert_equal("block", @merger.merge("block ")) assert_equal("block", @merger.merge(" block ")) assert_equal("block px-2 py-4", @merger.merge(" block px-2 py-4 ")) assert_equal("block px-2 py-4", @merger.merge([" block px-2", " ", " py-4 "])) assert_equal("block px-2", @merger.merge("block\npx-2")) assert_equal("block px-2", @merger.merge("\nblock\npx-2\n")) assert_equal("block px-2 py-4", @merger.merge(" block\n \n px-2 \n py-4 ")) assert_equal("block px-2 py-4", @merger.merge("\r block\n\r \n px-2 \n py-4 ")) end end
ruby
MIT
83ef21d415234e01c1f7188d64f37ebaec9c21ea
2026-01-04T17:44:23.457574Z
false
gjtorikian/tailwind_merge
https://github.com/gjtorikian/tailwind_merge/blob/83ef21d415234e01c1f7188d64f37ebaec9c21ea/test/test_theme.rb
test/test_theme.rb
# frozen_string_literal: true require "test_helper" class TestTheme < Minitest::Test def test_theme_scale_can_be_extended merger = TailwindMerge::Merger.new(config: { theme: { "spacing" => ["my-space"], "leading" => ["my-leading"], }, }) assert_equal("p-my-space p-my-margin", merger.merge("p-3 p-my-space p-my-margin")) assert_equal("leading-my-leading", merger.merge("leading-3 leading-my-space leading-my-leading")) end # def test_theme_object_can_be_extended # merger = TailwindMerge::Merger.new(config: { # theme: { # "spacing" => ["my-space"], # "margin" => ["my-margin"], # }, # }) # assert_equal("p-3 p-hello p-hallo", merger.merge("p-3 p-hello p-hallo")) # assert_equal("px-hallo", merger.merge("px-3 px-hello px-hallo")) # end end
ruby
MIT
83ef21d415234e01c1f7188d64f37ebaec9c21ea
2026-01-04T17:44:23.457574Z
false
gjtorikian/tailwind_merge
https://github.com/gjtorikian/tailwind_merge/blob/83ef21d415234e01c1f7188d64f37ebaec9c21ea/test/test_arbitrary_variants.rb
test/test_arbitrary_variants.rb
# frozen_string_literal: true require "test_helper" class TestArbitraryVariants < Minitest::Test def setup @merger = TailwindMerge::Merger.new end def test_basic_arbitrary_variants assert_equal("[p]:line-through", @merger.merge("[p]:underline [p]:line-through")) assert_equal("[&>*]:line-through", @merger.merge("[&>*]:underline [&>*]:line-through")) assert_equal("[&>*]:line-through [&_div]:line-through", @merger.merge("[&>*]:underline [&>*]:line-through [&_div]:line-through")) assert_equal("supports-[display:grid]:grid", @merger.merge("supports-[display:grid]:flex supports-[display:grid]:grid")) end def test_arbitrary_variants_with_modifiers assert_equal("dark:lg:hover:[&>*]:line-through", @merger.merge("dark:lg:hover:[&>*]:underline dark:lg:hover:[&>*]:line-through")) assert_equal("dark:hover:lg:[&>*]:line-through", @merger.merge("dark:lg:hover:[&>*]:underline dark:hover:lg:[&>*]:line-through")) # Whether a modifier is before or after arbitrary variant matters assert_equal("hover:[&>*]:underline [&>*]:hover:line-through", @merger.merge("hover:[&>*]:underline [&>*]:hover:line-through")) assert_equal("dark:hover:[&>*]:underline dark:[&>*]:hover:line-through", @merger.merge("hover:dark:[&>*]:underline dark:hover:[&>*]:underline dark:[&>*]:hover:line-through")) end def test_arbitrary_variants_with_complex_syntax_in_them assert_equal("[@media_screen{@media(hover:hover)}]:line-through", @merger.merge("[@media_screen{@media(hover:hover)}]:underline [@media_screen{@media(hover:hover)}]:line-through")) assert_equal("hover:[@media_screen{@media(hover:hover)}]:line-through", @merger.merge("hover:[@media_screen{@media(hover:hover)}]:underline hover:[@media_screen{@media(hover:hover)}]:line-through")) end def test_arbitrary_variants_with_attribute_selectors assert_equal("[&[data-open]]:line-through", @merger.merge("[&[data-open]]:underline [&[data-open]]:line-through")) end def test_arbitrary_variants_with_multiple_attribute_selectors assert_equal("[&[data-foo][data-bar]:not([data-baz])]:line-through", @merger.merge("[&[data-foo][data-bar]:not([data-baz])]:underline [&[data-foo][data-bar]:not([data-baz])]:line-through")) end def test_multiple_arbitrary_variants assert_equal("[&>*]:[&_div]:line-through", @merger.merge("[&>*]:[&_div]:underline [&>*]:[&_div]:line-through")) assert_equal("[&>*]:[&_div]:underline [&_div]:[&>*]:line-through", @merger.merge("[&>*]:[&_div]:underline [&_div]:[&>*]:line-through")) assert_equal("dark:hover:[&>*]:disabled:focus:[&_div]:line-through", @merger.merge("hover:dark:[&>*]:focus:disabled:[&_div]:underline dark:hover:[&>*]:disabled:focus:[&_div]:line-through")) assert_equal("hover:dark:[&>*]:focus:[&_div]:disabled:underline dark:hover:[&>*]:disabled:focus:[&_div]:line-through", @merger.merge("hover:dark:[&>*]:focus:[&_div]:disabled:underline dark:hover:[&>*]:disabled:focus:[&_div]:line-through")) end def test_arbitrary_variants_with_arbitrary_properties assert_equal("[&>*]:[color:blue]", @merger.merge("[&>*]:[color:red] [&>*]:[color:blue]")) assert_equal("[&[data-foo][data-bar]:not([data-baz])]:noa:nod:[color:blue]", @merger.merge("[&[data-foo][data-bar]:not([data-baz])]:nod:noa:[color:red] [&[data-foo][data-bar]:not([data-baz])]:noa:nod:[color:blue]")) end end
ruby
MIT
83ef21d415234e01c1f7188d64f37ebaec9c21ea
2026-01-04T17:44:23.457574Z
false
gjtorikian/tailwind_merge
https://github.com/gjtorikian/tailwind_merge/blob/83ef21d415234e01c1f7188d64f37ebaec9c21ea/test/test_per_side_border_colors.rb
test/test_per_side_border_colors.rb
# frozen_string_literal: true require "test_helper" class TestPerSideBorderColorsClasses < Minitest::Test def setup @merger = TailwindMerge::Merger.new end def test_merges_classes_with_per_side_border_colors_correctly assert_equal("border-t-other-blue", @merger.merge("border-t-some-blue border-t-other-blue")) assert_equal("border-some-blue", @merger.merge("border-t-some-blue border-some-blue")) assert_equal("border-some-blue border-s-some-blue", @merger.merge("border-some-blue border-s-some-blue")) assert_equal("border-some-blue", @merger.merge("border-e-some-blue border-some-blue")) end end
ruby
MIT
83ef21d415234e01c1f7188d64f37ebaec9c21ea
2026-01-04T17:44:23.457574Z
false
gjtorikian/tailwind_merge
https://github.com/gjtorikian/tailwind_merge/blob/83ef21d415234e01c1f7188d64f37ebaec9c21ea/test/test_non_tailwind_classes.rb
test/test_non_tailwind_classes.rb
# frozen_string_literal: true require "test_helper" class TestNonTailwindClasses < Minitest::Test def setup @merger = TailwindMerge::Merger.new end def test_does_not_alter_non_tailwind_classes assert_equal("non-tailwind-class block", @merger.merge("non-tailwind-class inline block")) assert_equal("block inline-1", @merger.merge("inline block inline-1")) assert_equal("block i-inline", @merger.merge("inline block i-inline")) assert_equal("focus:block focus:inline-1", @merger.merge("focus:inline focus:block focus:inline-1")) end end
ruby
MIT
83ef21d415234e01c1f7188d64f37ebaec9c21ea
2026-01-04T17:44:23.457574Z
false
gjtorikian/tailwind_merge
https://github.com/gjtorikian/tailwind_merge/blob/83ef21d415234e01c1f7188d64f37ebaec9c21ea/test/test_colors.rb
test/test_colors.rb
# frozen_string_literal: true require "test_helper" class TesColors < Minitest::Test def setup @merger = TailwindMerge::Merger.new end def test_handles_color_conflicts_properly assert_equal("bg-hotpink", @merger.merge("bg-grey-5 bg-hotpink")) assert_equal("hover:bg-hotpink", @merger.merge("hover:bg-grey-5 hover:bg-hotpink")) assert_equal("stroke-[hsl(350_80%_0%)] stroke-[10px]", @merger.merge("stroke-[hsl(350_80%_0%)] stroke-[10px]")) end end
ruby
MIT
83ef21d415234e01c1f7188d64f37ebaec9c21ea
2026-01-04T17:44:23.457574Z
false
gjtorikian/tailwind_merge
https://github.com/gjtorikian/tailwind_merge/blob/83ef21d415234e01c1f7188d64f37ebaec9c21ea/test/test_important_modifier.rb
test/test_important_modifier.rb
# frozen_string_literal: true require "test_helper" class TestImportantModifier < Minitest::Test def setup @merger = TailwindMerge::Merger.new end def test_merges_tailwind_classes_with_important_modifier_correctly assert_equal("font-bold!", @merger.merge("font-medium! font-bold!")) assert_equal("font-bold! font-thin", @merger.merge("font-medium! font-bold! font-thin")) assert_equal("-inset-x-px!", @merger.merge("right-2! -inset-x-px!")) assert_equal("focus:block!", @merger.merge("focus:inline! focus:block!")) assert_equal("[--my-var:30px]!", @merger.merge("[--my-var:20px]! [--my-var:30px]!")) # Tailwind CSS v3 legacy syntax assert_equal("!font-bold", @merger.merge("font-medium! !font-bold")) assert_equal("!font-bold", @merger.merge("!font-medium !font-bold")) assert_equal("!font-bold font-thin", @merger.merge("!font-medium !font-bold font-thin")) assert_equal("!-inset-x-px", @merger.merge("!right-2 !-inset-x-px")) assert_equal("focus:!block", @merger.merge("focus:!inline focus:!block")) assert_equal("![--my-var:30px]", @merger.merge("![--my-var:20px] ![--my-var:30px]")) end end
ruby
MIT
83ef21d415234e01c1f7188d64f37ebaec9c21ea
2026-01-04T17:44:23.457574Z
false
gjtorikian/tailwind_merge
https://github.com/gjtorikian/tailwind_merge/blob/83ef21d415234e01c1f7188d64f37ebaec9c21ea/test/test_validators.rb
test/test_validators.rb
# frozen_string_literal: true require "test_helper" class TestValidators < Minitest::Test include TailwindMerge::Validators def test_is_any assert(IS_ANY.call) assert(IS_ANY.call("")) assert(IS_ANY.call("something")) end def test_is_any_non_arbitrary assert(IS_ANY_NON_ARBITRARY.call("test")) assert(IS_ANY_NON_ARBITRARY.call("1234-hello-world")) assert(IS_ANY_NON_ARBITRARY.call("[hello")) assert(IS_ANY_NON_ARBITRARY.call("hello]")) assert(IS_ANY_NON_ARBITRARY.call("[)")) assert(IS_ANY_NON_ARBITRARY.call("(hello]")) refute(IS_ANY_NON_ARBITRARY.call("[test]")) refute(IS_ANY_NON_ARBITRARY.call("[label:test]")) refute(IS_ANY_NON_ARBITRARY.call("(test)")) refute(IS_ANY_NON_ARBITRARY.call("(label:test)")) end def test_is_arbitrary_image assert(IS_ARBITRARY_IMAGE.call("[url:var(--my-url)]")) assert(IS_ARBITRARY_IMAGE.call("[url(something)]")) assert(IS_ARBITRARY_IMAGE.call("[url:bla]")) assert(IS_ARBITRARY_IMAGE.call("[image:bla]")) assert(IS_ARBITRARY_IMAGE.call("[linear-gradient(something)]")) assert(IS_ARBITRARY_IMAGE.call("[repeating-conic-gradient(something)]")) refute(IS_ARBITRARY_IMAGE.call("[var(--my-url)]")) refute(IS_ARBITRARY_IMAGE.call("[bla]")) refute(IS_ARBITRARY_IMAGE.call("url:2px")) refute(IS_ARBITRARY_IMAGE.call("url(2px)")) end def test_is_arbitrary_length assert(IS_ARBITRARY_LENGTH.call("[3.7%]")) assert(IS_ARBITRARY_LENGTH.call("[481px]")) assert(IS_ARBITRARY_LENGTH.call("[19.1rem]")) assert(IS_ARBITRARY_LENGTH.call("[50vw]")) assert(IS_ARBITRARY_LENGTH.call("[56vh]")) assert(IS_ARBITRARY_LENGTH.call("[length:var(--arbitrary)]")) refute(IS_ARBITRARY_LENGTH.call("1")) refute(IS_ARBITRARY_LENGTH.call("3px")) refute(IS_ARBITRARY_LENGTH.call("1d5")) refute(IS_ARBITRARY_LENGTH.call("[1]")) refute(IS_ARBITRARY_LENGTH.call("[12px")) refute(IS_ARBITRARY_LENGTH.call("12px]")) refute(IS_ARBITRARY_LENGTH.call("one")) end def test_is_arbitrary_number assert(IS_ARBITRARY_NUMBER.call("[number:black]")) assert(IS_ARBITRARY_NUMBER.call("[number:bla]")) assert(IS_ARBITRARY_NUMBER.call("[number:230]")) assert(IS_ARBITRARY_NUMBER.call("[450]")) refute(IS_ARBITRARY_NUMBER.call("[2px]")) refute(IS_ARBITRARY_NUMBER.call("[bla]")) refute(IS_ARBITRARY_NUMBER.call("[black]")) refute(IS_ARBITRARY_NUMBER.call("black")) refute(IS_ARBITRARY_NUMBER.call("450")) end def test_is_arbitrary_position assert(IS_ARBITRARY_POSITION.call("[position:2px]")) assert(IS_ARBITRARY_POSITION.call("[position:bla]")) assert(IS_ARBITRARY_POSITION.call("[percentage:bla]")) refute(IS_ARBITRARY_POSITION.call("[2px]")) refute(IS_ARBITRARY_POSITION.call("[bla]")) refute(IS_ARBITRARY_POSITION.call("position:2px")) end def test_is_arbitrary_shadow assert(IS_ARBITRARY_SHADOW.call("[0_35px_60px_-15px_rgba(0,0,0,0.3)]")) assert(IS_ARBITRARY_SHADOW.call("[inset_0_1px_0,inset_0_-1px_0]")) assert(IS_ARBITRARY_SHADOW.call("[0_0_#00f]")) assert(IS_ARBITRARY_SHADOW.call("[.5rem_0_rgba(5,5,5,5)]")) assert(IS_ARBITRARY_SHADOW.call("[-.5rem_0_#123456]")) assert(IS_ARBITRARY_SHADOW.call("[0.5rem_-0_#123456]")) assert(IS_ARBITRARY_SHADOW.call("[0.5rem_-0.005vh_#123456]")) assert(IS_ARBITRARY_SHADOW.call("[0.5rem_-0.005vh]")) refute(IS_ARBITRARY_SHADOW.call("[rgba(5,5,5,5)]")) refute(IS_ARBITRARY_SHADOW.call("[#00f]")) refute(IS_ARBITRARY_SHADOW.call("[something-else]")) end def test_is_arbitrary_size assert(IS_ARBITRARY_SIZE.call("[size:2px]")) assert(IS_ARBITRARY_SIZE.call("[size:bla]")) assert(IS_ARBITRARY_SIZE.call("[length:bla]")) refute(IS_ARBITRARY_SIZE.call("[2px]")) refute(IS_ARBITRARY_SIZE.call("[bla]")) refute(IS_ARBITRARY_SIZE.call("size:2px")) refute(IS_ARBITRARY_SIZE.call("[percentage:bla]")) end def test_is_arbitrary_value assert(IS_ARBITRARY_VALUE.call("[1]")) assert(IS_ARBITRARY_VALUE.call("[bla]")) assert(IS_ARBITRARY_VALUE.call("[not-an-arbitrary-value?]")) assert(IS_ARBITRARY_VALUE.call("[auto,auto,minmax(0,1fr),calc(100vw-50%)]")) refute(IS_ARBITRARY_VALUE.call("[]")) refute(IS_ARBITRARY_VALUE.call("[1")) refute(IS_ARBITRARY_VALUE.call("1]")) refute(IS_ARBITRARY_VALUE.call("1")) refute(IS_ARBITRARY_VALUE.call("one")) refute(IS_ARBITRARY_VALUE.call("o[n]e")) end def test_is_arbitrary_variable assert(IS_ARBITRARY_VARIABLE.call("(1)")) assert(IS_ARBITRARY_VARIABLE.call("(bla)")) assert(IS_ARBITRARY_VARIABLE.call("(not-an-arbitrary-value?)")) assert(IS_ARBITRARY_VARIABLE.call("(--my-arbitrary-variable)")) assert(IS_ARBITRARY_VARIABLE.call("(label:--my-arbitrary-variable)")) refute(IS_ARBITRARY_VARIABLE.call("()")) refute(IS_ARBITRARY_VARIABLE.call("(1")) refute(IS_ARBITRARY_VARIABLE.call("1)")) refute(IS_ARBITRARY_VARIABLE.call("1")) refute(IS_ARBITRARY_VARIABLE.call("one")) refute(IS_ARBITRARY_VARIABLE.call("o(n)e")) end def test_is_arbitrary_variable_family_name assert(IS_ARBITRARY_VARIABLE_FAMILY_NAME.call("(family-name:test)")) refute(IS_ARBITRARY_VARIABLE_FAMILY_NAME.call("(other:test)")) refute(IS_ARBITRARY_VARIABLE_FAMILY_NAME.call("(test)")) refute(IS_ARBITRARY_VARIABLE_FAMILY_NAME.call("family-name:test")) end def test_is_arbitrary_variable_image assert(IS_ARBITRARY_VARIABLE_IMAGE.call("(image:test)")) assert(IS_ARBITRARY_VARIABLE_IMAGE.call("(url:test)")) refute(IS_ARBITRARY_VARIABLE_IMAGE.call("(other:test)")) refute(IS_ARBITRARY_VARIABLE_IMAGE.call("(test)")) refute(IS_ARBITRARY_VARIABLE_IMAGE.call("image:test")) end def test_is_arbitrary_variable_length assert(IS_ARBITRARY_VARIABLE_LENGTH.call("(length:test)")) refute(IS_ARBITRARY_VARIABLE_LENGTH.call("(other:test)")) refute(IS_ARBITRARY_VARIABLE_LENGTH.call("(test)")) refute(IS_ARBITRARY_VARIABLE_LENGTH.call("length:test")) end def test_is_arbitrary_variable_position assert(IS_ARBITRARY_VARIABLE_POSITION.call("(position:test)")) refute(IS_ARBITRARY_VARIABLE_POSITION.call("(other:test)")) refute(IS_ARBITRARY_VARIABLE_POSITION.call("(test)")) refute(IS_ARBITRARY_VARIABLE_POSITION.call("position:test")) refute(IS_ARBITRARY_VARIABLE_POSITION.call("percentage:test")) end def test_is_arbitrary_variable_shadow assert(IS_ARBITRARY_VARIABLE_SHADOW.call("(shadow:test)")) assert(IS_ARBITRARY_VARIABLE_SHADOW.call("(test)")) refute(IS_ARBITRARY_VARIABLE_SHADOW.call("(other:test)")) refute(IS_ARBITRARY_VARIABLE_SHADOW.call("shadow:test")) end def test_is_arbitrary_variable_size assert(IS_ARBITRARY_VARIABLE_SIZE.call("(size:test)")) assert(IS_ARBITRARY_VARIABLE_SIZE.call("(length:test)")) refute(IS_ARBITRARY_VARIABLE_SIZE.call("(other:test)")) refute(IS_ARBITRARY_VARIABLE_SIZE.call("(test)")) refute(IS_ARBITRARY_VARIABLE_SIZE.call("size:test")) refute(IS_ARBITRARY_VARIABLE_SIZE.call("percentage:test")) end def test_is_fraction assert(IS_FRACTION.call("1/2")) assert(IS_FRACTION.call("123/209")) refute(IS_FRACTION.call("1")) refute(IS_FRACTION.call("1/2/3")) refute(IS_FRACTION.call("[1/2]")) end def test_is_integer assert(IS_INTEGER.call("1")) assert(IS_INTEGER.call("123")) assert(IS_INTEGER.call("8312")) refute(IS_INTEGER.call("[8312]")) refute(IS_INTEGER.call("[2]")) refute(IS_INTEGER.call("[8312px]")) refute(IS_INTEGER.call("[8312%]")) refute(IS_INTEGER.call("[8312rem]")) refute(IS_INTEGER.call("8312.2")) refute(IS_INTEGER.call("1.2")) refute(IS_INTEGER.call("one")) refute(IS_INTEGER.call("1/2")) refute(IS_INTEGER.call("1%")) refute(IS_INTEGER.call("1px")) end def test_is_number assert(IS_NUMBER.call("1")) assert(IS_NUMBER.call("123")) assert(IS_NUMBER.call("8312")) assert(IS_NUMBER.call("8312.2")) assert(IS_NUMBER.call("1.2")) refute(IS_NUMBER.call("[8312]")) refute(IS_NUMBER.call("[2]")) refute(IS_NUMBER.call("[8312px]")) refute(IS_NUMBER.call("[8312%]")) refute(IS_NUMBER.call("[8312rem]")) refute(IS_NUMBER.call("one")) refute(IS_NUMBER.call("1/2")) refute(IS_NUMBER.call("1%")) refute(IS_NUMBER.call("1px")) end def test_is_percent assert(IS_PERCENT.call("1%")) assert(IS_PERCENT.call("100.001%")) assert(IS_PERCENT.call(".01%")) assert(IS_PERCENT.call("0%")) refute(IS_PERCENT.call("0")) refute(IS_PERCENT.call("one%")) end def test_is_tshirt_size assert(IS_TSHIRT_SIZE.call("xs")) assert(IS_TSHIRT_SIZE.call("sm")) assert(IS_TSHIRT_SIZE.call("md")) assert(IS_TSHIRT_SIZE.call("lg")) assert(IS_TSHIRT_SIZE.call("xl")) assert(IS_TSHIRT_SIZE.call("2xl")) assert(IS_TSHIRT_SIZE.call("2.5xl")) assert(IS_TSHIRT_SIZE.call("10xl")) assert(IS_TSHIRT_SIZE.call("2xs")) assert(IS_TSHIRT_SIZE.call("2lg")) refute(IS_TSHIRT_SIZE.call("")) refute(IS_TSHIRT_SIZE.call("hello")) refute(IS_TSHIRT_SIZE.call("1")) refute(IS_TSHIRT_SIZE.call("xl3")) refute(IS_TSHIRT_SIZE.call("2xl3")) refute(IS_TSHIRT_SIZE.call("-xl")) refute(IS_TSHIRT_SIZE.call("[sm]")) end end
ruby
MIT
83ef21d415234e01c1f7188d64f37ebaec9c21ea
2026-01-04T17:44:23.457574Z
false
gjtorikian/tailwind_merge
https://github.com/gjtorikian/tailwind_merge/blob/83ef21d415234e01c1f7188d64f37ebaec9c21ea/test/test_tailwind_merge.rb
test/test_tailwind_merge.rb
# frozen_string_literal: true require "test_helper" class TestTailwindMerge < Minitest::Test def setup @merger = TailwindMerge::Merger.new end def test_that_it_has_a_version_number refute_nil(::TailwindMerge::VERSION) end def test_it_works_with_single_string assert_equal("mix-blend-multiply", @merger.merge("mix-blend-normal mix-blend-multiply")) assert_equal("h-min", @merger.merge("h-10 h-min")) assert_equal("stroke-black stroke-1", @merger.merge("stroke-black stroke-1")) assert_equal("stroke-[3]", @merger.merge("stroke-2 stroke-[3]")) assert_equal("outline-black outline-1", @merger.merge("outline-black outline-1")) assert_equal("grayscale-[50%]", @merger.merge("grayscale-0 grayscale-[50%]")) assert_equal("grow-[2]", @merger.merge("grow grow-[2]")) end def test_it_with_array assert_equal("mix-blend-multiply", @merger.merge(["mix-blend-normal", "mix-blend-multiply"])) assert_equal("h-min", @merger.merge(["h-10", "h-min"])) assert_equal("stroke-black stroke-1", @merger.merge(["stroke-black", "stroke-1"])) assert_equal("stroke-[3]", @merger.merge(["stroke-2", "stroke-[3]"])) assert_equal("outline-black outline-1", @merger.merge(["outline-black", "outline-1"])) assert_equal("grayscale-[50%]", @merger.merge(["grayscale-0", "grayscale-[50%]"])) assert_equal("grow-[2]", @merger.merge(["grow", "grow-[2]"])) end def test_removes_duplicates original = "bg-red-500 border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm border-indigo-500 text-indigo-600 bg-red-500 border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm" merged = "bg-red-500 border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm" refute_equal(original, @merger.merge(original)) assert_equal(merged, @merger.merge(original)) end end
ruby
MIT
83ef21d415234e01c1f7188d64f37ebaec9c21ea
2026-01-04T17:44:23.457574Z
false
gjtorikian/tailwind_merge
https://github.com/gjtorikian/tailwind_merge/blob/83ef21d415234e01c1f7188d64f37ebaec9c21ea/test/test_config.rb
test/test_config.rb
# frozen_string_literal: true require "test_helper" class TestConfig < Minitest::Test def test_default_config_has_correct_types config = TailwindMerge::Config::DEFAULTS assert_equal(500, config[:cache_size]) assert(config[:ignore_empty_cache]) refute(config[:nonexistent]) assert_equal("block", config[:class_groups]["display"].first) assert_equal("auto", config[:class_groups]["overflow"].first["overflow"].first) refute(config[:class_groups]["overflow"].first[:nonexistent]) end end
ruby
MIT
83ef21d415234e01c1f7188d64f37ebaec9c21ea
2026-01-04T17:44:23.457574Z
false
gjtorikian/tailwind_merge
https://github.com/gjtorikian/tailwind_merge/blob/83ef21d415234e01c1f7188d64f37ebaec9c21ea/test/test_arbitrary_values.rb
test/test_arbitrary_values.rb
# frozen_string_literal: true require "test_helper" class TestArbitraryValues < Minitest::Test def setup @merger = TailwindMerge::Merger.new end def test_handles_simple_conflicts_with_arbitrary_values_correctly assert_equal("m-[10px]", @merger.merge("m-[2px] m-[10px]")) assert_equal("z-[99]", @merger.merge("z-20 z-[99]")) assert_equal("m-[10dvh]", @merger.merge("m-[2px] m-[11svmin] m-[12in] m-[13lvi] m-[14vb] m-[15vmax] m-[16mm] m-[17%] m-[18em] m-[19px] m-[10dvh]")) assert_equal("h-[16cqmax]", @merger.merge("h-[10px] h-[11cqw] h-[12cqh] h-[13cqi] h-[14cqb] h-[15cqmin] h-[16cqmax]")) assert_equal("m-[10rem]", @merger.merge("my-[2px] m-[10rem]")) assert_equal("cursor-[grab]", @merger.merge("cursor-pointer cursor-[grab]")) assert_equal("m-[calc(100%-var(--arbitrary))]", @merger.merge("m-[2px] m-[calc(100%-var(--arbitrary))]")) assert_equal("m-[length:var(--mystery-var)]", @merger.merge("m-[2px] m-[length:var(--mystery-var)]")) assert_equal("opacity-[0.025]", @merger.merge("opacity-10 opacity-[0.025]")) assert_equal("scale-[1.7]", @merger.merge("scale-75 scale-[1.7]")) assert_equal("brightness-[1.75]", @merger.merge("brightness-90 brightness-[1.75]")) # Handling of value `0` assert_equal("min-h-[0]", @merger.merge("min-h-[0.5px] min-h-[0]")) assert_equal("text-[0.5px] text-[color:0]", @merger.merge("text-[0.5px] text-[color:0]")) assert_equal("text-[0.5px] text-(--my-0)", @merger.merge("text-[0.5px] text-(--my-0)")) end def test_handles_arbitrary_length_conflicts_with_labels_and_modifiers_correctly assert_equal("hover:m-[length:var(--c)]", @merger.merge("hover:m-[2px] hover:m-[length:var(--c)]")) assert_equal("focus:hover:m-[length:var(--c)]", @merger.merge("hover:focus:m-[2px] focus:hover:m-[length:var(--c)]")) assert_equal("border-b border-[color:rgb(var(--color-gray-500-rgb)/50%))]", @merger.merge("border-b border-[color:rgb(var(--color-gray-500-rgb)/50%))]")) assert_equal("border-[color:rgb(var(--color-gray-500-rgb)/50%))] border-b", @merger.merge("border-[color:rgb(var(--color-gray-500-rgb)/50%))] border-b")) assert_equal("border-b border-some-coloooor", @merger.merge("border-b border-[color:rgb(var(--color-gray-500-rgb)/50%))] border-some-coloooor")) end def test_handles_complex_arbitrary_value_conflicts_correctly assert_equal("grid-rows-2", @merger.merge("grid-rows-[1fr,auto] grid-rows-2")) assert_equal("grid-rows-3", @merger.merge("grid-rows-[repeat(20,minmax(0,1fr))] grid-rows-3")) end def test_handles_ambiguous_arbitrary_values_correctly assert_equal("mt-[calc(theme(fontSize.4xl)/1.125)]", @merger.merge("mt-2 mt-[calc(theme(fontSize.4xl)/1.125)]")) assert_equal("p-[calc(theme(fontSize.4xl)/1.125)_10px]", @merger.merge("p-2 p-[calc(theme(fontSize.4xl)/1.125)_10px]")) assert_equal("mt-[length:theme(someScale.someValue)]", @merger.merge("mt-2 mt-[length:theme(someScale.someValue)]")) assert_equal("mt-[theme(someScale.someValue)]", @merger.merge("mt-2 mt-[theme(someScale.someValue)]")) assert_equal("text-[length:theme(someScale.someValue)]", @merger.merge("text-2xl text-[length:theme(someScale.someValue)]")) assert_equal("text-[calc(theme(fontSize.4xl)/1.125)]", @merger.merge("text-2xl text-[calc(theme(fontSize.4xl)/1.125)]")) assert_equal("bg-[percentage:30%] bg-[length:200px_100px]", @merger.merge("bg-cover bg-[percentage:30%] bg-[size:200px_100px] bg-[length:200px_100px]")) assert_equal("bg-linear-to-r", @merger.merge("bg-none bg-[url(.)] bg-[image:.] bg-[url:.] bg-[linear-gradient(.)] bg-linear-to-r")) assert_equal("border-[color-mix(in_oklab,var(--background),var(--calendar-color)_30%)] border", @merger.merge("border-[color-mix(in_oklab,var(--background),var(--calendar-color)_30%)] border")) end def test_handles_arbitrary_custom_properties_correctly assert_equal("bg-(--other-red) bg-(position:-my-pos)", @merger.merge("bg-red bg-(--other-red) bg-bottom bg-(position:-my-pos)")) assert_equal("shadow-(--some-other-shadow) shadow-(color:--some-color)", @merger.merge("shadow-xs shadow-(shadow:--something) shadow-red shadow-(--some-other-shadow) shadow-(color:--some-color)")) end end
ruby
MIT
83ef21d415234e01c1f7188d64f37ebaec9c21ea
2026-01-04T17:44:23.457574Z
false
gjtorikian/tailwind_merge
https://github.com/gjtorikian/tailwind_merge/blob/83ef21d415234e01c1f7188d64f37ebaec9c21ea/test/test_helper.rb
test/test_helper.rb
# frozen_string_literal: true if ENV.fetch("DEBUG", false) require "amazing_print" require "debug" end $LOAD_PATH.unshift(File.expand_path("../lib", __dir__)) require "tailwind_merge" require "minitest/autorun" require "minitest/focus" require "minitest/pride"
ruby
MIT
83ef21d415234e01c1f7188d64f37ebaec9c21ea
2026-01-04T17:44:23.457574Z
false
gjtorikian/tailwind_merge
https://github.com/gjtorikian/tailwind_merge/blob/83ef21d415234e01c1f7188d64f37ebaec9c21ea/test/test_prefixes.rb
test/test_prefixes.rb
# frozen_string_literal: true require "test_helper" class TestPrefixes < Minitest::Test def setup @merger = TailwindMerge::Merger.new(config: { prefix: "tw" }) end def test_prefix_working_correctly # assert_equal("tw:hidden", @merger.merge("tw:block tw:hidden")) assert_equal("block hidden", @merger.merge("block hidden")) # assert_equal("tw:p-2", @merger.merge("tw:p-3 tw:p-2")) # assert_equal("p-3 p-2", @merger.merge("p-3 p-2")) # assert_equal("!tw:inset-0", @merger.merge("!tw:right-0 !tw:inset-0")) # assert_equal("focus:hover:!tw:inset-0", @merger.merge("hover:focus:!tw:right-0 focus:hover:!tw:inset-0")) end end
ruby
MIT
83ef21d415234e01c1f7188d64f37ebaec9c21ea
2026-01-04T17:44:23.457574Z
false
gjtorikian/tailwind_merge
https://github.com/gjtorikian/tailwind_merge/blob/83ef21d415234e01c1f7188d64f37ebaec9c21ea/test/test_tailwind_css_versions.rb
test/test_tailwind_css_versions.rb
# frozen_string_literal: true require "test_helper" require "set" class TestTailwindCSSVersions < Minitest::Test def setup @merger = TailwindMerge::Merger.new end def test_tailwind_3_3_features assert_equal("text-red text-lg/8", @merger.merge("text-red text-lg/7 text-lg/8")) assert_equal("start-1 end-1 ps-1 pe-1 ms-1 me-1 rounded-s-md rounded-e-md rounded-ss-md rounded-ee-md", @merger.merge("start-0 start-1 end-0 end-1 ps-0 ps-1 pe-0 pe-1 ms-0 ms-1 me-0 me-1 rounded-s-sm rounded-s-md rounded-e-sm rounded-e-md rounded-ss-sm rounded-ss-md rounded-ee-sm rounded-ee-md")) assert_equal("inset-0 p-0 m-0 rounded-s", @merger.merge("start-0 end-0 inset-0 ps-0 pe-0 p-0 ms-0 me-0 m-0 rounded-ss rounded-es rounded-s")) assert_equal("hyphens-manual", @merger.merge("hyphens-auto hyphens-manual")) assert_equal("from-[12.5%] via-[12.5%] to-[12.5%]", @merger.merge("from-0% from-10% from-[12.5%] via-0% via-10% via-[12.5%] to-0% to-10% to-[12.5%]")) assert_equal("from-0% from-red", @merger.merge("from-0% from-red")) assert_equal("list-image-[var(--value)]", @merger.merge("list-image-none list-image-[url(./my-image.png)] list-image-[var(--value)]")) assert_equal("caption-bottom", @merger.merge("caption-top caption-bottom")) assert_equal("line-clamp-[10]", @merger.merge("line-clamp-2 line-clamp-none line-clamp-[10]")) assert_equal("delay-0 duration-0", @merger.merge("delay-150 delay-0 duration-150 duration-0")) assert_equal("justify-stretch", @merger.merge("justify-normal justify-center justify-stretch")) assert_equal("content-stretch", @merger.merge("content-normal content-center content-stretch")) assert_equal("whitespace-break-spaces", @merger.merge("whitespace-nowrap whitespace-break-spaces")) end def test_tailwind_3_4_features assert_equal("h-dvh w-dvw", @merger.merge("h-svh h-dvh w-svw w-dvw")) assert_equal("has-[[data-potato]]:p-2 group-has-[:checked]:flex", @merger.merge("has-[[data-potato]]:p-1 has-[[data-potato]]:p-2 group-has-[:checked]:grid group-has-[:checked]:flex")) assert_equal("text-pretty", @merger.merge("text-wrap text-pretty")) assert_equal("size-10 w-12", @merger.merge("w-5 h-3 size-10 w-12")) assert_equal("grid-cols-subgrid grid-rows-subgrid", @merger.merge("grid-cols-2 grid-cols-subgrid grid-rows-5 grid-rows-subgrid")) assert_equal("min-w-px max-w-px", @merger.merge("min-w-0 min-w-50 min-w-px max-w-0 max-w-50 max-w-px")) assert_equal("forced-color-adjust-auto", @merger.merge("forced-color-adjust-none forced-color-adjust-auto")) assert_equal("appearance-auto", @merger.merge("appearance-none appearance-auto")) assert_equal("float-end clear-end", @merger.merge("float-start float-end clear-start clear-end")) assert_equal("*:p-20 hover:*:p-20", @merger.merge("*:p-10 *:p-20 hover:*:p-10 hover:*:p-20")) end def test_tailwind_4_0_features assert_equal("transform-flat", @merger.merge("transform-3d transform-flat")) assert_equal("rotate-x-2 rotate-none rotate-y-3", @merger.merge("rotate-12 rotate-x-2 rotate-none rotate-y-3")) assert_equal("perspective-midrange", @merger.merge("perspective-dramatic perspective-none perspective-midrange")) assert_equal("perspective-origin-top-left", @merger.merge("perspective-origin-center perspective-origin-top-left")) assert_equal("bg-linear-45", @merger.merge("bg-linear-to-r bg-linear-45")) assert_equal("bg-conic-10", @merger.merge("bg-linear-to-r bg-radial-[something] bg-conic-10")) assert_equal("ring-4 ring-orange inset-ring-3 inset-ring-blue", @merger.merge("ring-4 ring-orange inset-ring inset-ring-3 inset-ring-blue")) assert_equal("field-sizing-fixed", @merger.merge("field-sizing-content field-sizing-fixed")) assert_equal("scheme-dark", @merger.merge("scheme-normal scheme-dark")) assert_equal("font-stretch-50%", @merger.merge("font-stretch-expanded font-stretch-[66.66%] font-stretch-50%")) assert_equal("col-2 row-4", @merger.merge("col-span-full col-2 row-span-3 row-4")) assert_equal("via-(--mobile-header-gradient)", @merger.merge("via-red-500 via-(--mobile-header-gradient)")) assert_equal("via-red-500 via-(length:--mobile-header-gradient)", @merger.merge("via-red-500 via-(length:--mobile-header-gradient)")) end def test_tailwind_4_1_features assert_equal("items-baseline-last", @merger.merge("items-baseline items-baseline-last")) assert_equal("self-baseline-last", @merger.merge("self-baseline self-baseline-last")) assert_equal("place-content-center-safe", @merger.merge("place-content-center place-content-end-safe place-content-center-safe")) assert_equal("items-end-safe", @merger.merge("items-center-safe items-baseline items-end-safe")) assert_equal("wrap-anywhere", @merger.merge("wrap-break-word wrap-normal wrap-anywhere")) assert_equal("text-shadow-2xl", @merger.merge("text-shadow-none text-shadow-2xl")) assert_equal( "text-shadow-md text-shadow-red-500 shadow-red shadow-3xs", @merger.merge("text-shadow-none text-shadow-md text-shadow-red text-shadow-red-500 shadow-red shadow-3xs"), ) assert_equal("mask-subtract", @merger.merge("mask-add mask-subtract")) assert_equal( "mask-none mask-linear-2 mask-linear-from-3 mask-linear-to-3 mask-linear-from-color-3 mask-linear-to-color-3 mask-t-from-3 mask-t-to-3 mask-t-from-color-3 mask-radial-[test] mask-radial-from-3 mask-radial-to-3 mask-radial-from-color-3", @merger.merge( "mask-(--foo) mask-[foo] mask-none " \ "mask-linear-1 mask-linear-2 " \ "mask-linear-from-[position:test] mask-linear-from-3 " \ "mask-linear-to-[position:test] mask-linear-to-3 " \ "mask-linear-from-color-red mask-linear-from-color-3 " \ "mask-linear-to-color-red mask-linear-to-color-3 " \ "mask-t-from-[position:test] mask-t-from-3 " \ "mask-t-to-[position:test] mask-t-to-3 " \ "mask-t-from-color-red mask-t-from-color-3 " \ "mask-radial-(--test) mask-radial-[test] " \ "mask-radial-from-[position:test] mask-radial-from-3 " \ "mask-radial-to-[position:test] mask-radial-to-3 " \ "mask-radial-from-color-red mask-radial-from-color-3", ), ) assert_equal( "mask-[something] mask-position-[1px_1px]", @merger.merge( "mask-(--something) mask-[something] " \ "mask-top-left mask-center mask-(position:--var) mask-[position:1px_1px] mask-position-(--var) mask-position-[1px_1px]", ), ) assert_equal( "mask-[something] mask-contain", @merger.merge( "mask-(--something) mask-[something] " \ "mask-auto mask-[size:foo] mask-(size:--foo) mask-size-[foo] mask-size-(--foo) mask-cover mask-contain", ), ) assert_equal("mask-type-alpha", @merger.merge("mask-type-luminance mask-type-alpha")) assert_equal("shadow-lg/25 text-shadow-lg/25", @merger.merge("shadow-md shadow-lg/25 text-shadow-md text-shadow-lg/25")) assert_equal( "drop-shadow-[#123456] drop-shadow-[10px_0]", @merger.merge("drop-shadow-some-color drop-shadow-[#123456] drop-shadow-lg drop-shadow-[10px_0]"), ) assert_equal("drop-shadow-some-color", @merger.merge("drop-shadow-[#123456] drop-shadow-some-color")) assert_equal("drop-shadow-[shadow:foo]", @merger.merge("drop-shadow-2xl drop-shadow-[shadow:foo]")) end def test_tailwind_4_15_features assert_equal("h-lh", @merger.merge("h-12 h-lh")) assert_equal("min-h-lh", @merger.merge("min-h-12 min-h-lh")) assert_equal("max-h-lh", @merger.merge("max-h-12 max-h-lh")) end end
ruby
MIT
83ef21d415234e01c1f7188d64f37ebaec9c21ea
2026-01-04T17:44:23.457574Z
false
gjtorikian/tailwind_merge
https://github.com/gjtorikian/tailwind_merge/blob/83ef21d415234e01c1f7188d64f37ebaec9c21ea/test/test_arbitrary_properties.rb
test/test_arbitrary_properties.rb
# frozen_string_literal: true require "test_helper" class TestArbitraryProperties < Minitest::Test def setup @merger = TailwindMerge::Merger.new end def test_handles_arbitrary_property_conflicts_correctly assert_equal("[paint-order:normal]", @merger.merge("[paint-order:markers] [paint-order:normal]")) assert_equal("[paint-order:normal] [--my-var:4px]", @merger.merge("[paint-order:markers] [--my-var:2rem] [paint-order:normal] [--my-var:4px]")) end def test_handles_arbitrary_property_conflicts_with_modifiers_correctly assert_equal("[paint-order:markers] hover:[paint-order:normal]", @merger.merge("[paint-order:markers] hover:[paint-order:normal]")) assert_equal("hover:[paint-order:normal]", @merger.merge("hover:[paint-order:markers] hover:[paint-order:normal]")) assert_equal("focus:hover:[paint-order:normal]", @merger.merge("hover:focus:[paint-order:markers] focus:hover:[paint-order:normal]")) assert_equal("[paint-order:normal] [--my-var:2rem] lg:[--my-var:4px]", @merger.merge("[paint-order:markers] [paint-order:normal] [--my-var:2rem] lg:[--my-var:4px]")) assert_equal("bg-[#B91C1C] bg-radial-[at_25%_25%]", @merger.merge("bg-[#B91C1C] bg-radial-[at_50%_75%] bg-radial-[at_25%_25%]")) end def test_handles_complex_arbitrary_property_conflicts_correctly assert_equal("[-unknown-prop:url(https://hi.com)]", @merger.merge("[-unknown-prop:::123:::] [-unknown-prop:url(https://hi.com)]")) end def test_handles_important_modifier_correctly assert_equal("![some:prop] [some:other]", @merger.merge("![some:prop] [some:other]")) assert_equal("[some:one] ![some:another]", @merger.merge("![some:prop] [some:other] [some:one] ![some:another]")) end end
ruby
MIT
83ef21d415234e01c1f7188d64f37ebaec9c21ea
2026-01-04T17:44:23.457574Z
false
gjtorikian/tailwind_merge
https://github.com/gjtorikian/tailwind_merge/blob/83ef21d415234e01c1f7188d64f37ebaec9c21ea/test/test_conflicts_across_class_groups.rb
test/test_conflicts_across_class_groups.rb
# frozen_string_literal: true require "test_helper" class TestConflictsAcrossClassGroups < Minitest::Test def setup @merger = TailwindMerge::Merger.new end def test_handles_conflicts_across_class_groups_correctly assert_equal("inset-1 inset-x-1", @merger.merge("inset-1 inset-x-1")) assert_equal("inset-1", @merger.merge("inset-x-1 inset-1")) assert_equal("inset-1", @merger.merge("inset-x-1 left-1 inset-1")) assert_equal("inset-1 left-1", @merger.merge("inset-x-1 inset-1 left-1")) assert_equal("inset-1", @merger.merge("inset-x-1 right-1 inset-1")) assert_equal("inset-x-1", @merger.merge("inset-x-1 right-1 inset-x-1")) assert_equal("inset-x-1 right-1 inset-y-1", @merger.merge("inset-x-1 right-1 inset-y-1")) assert_equal("inset-x-1 inset-y-1", @merger.merge("right-1 inset-x-1 inset-y-1")) assert_equal("hover:left-1 inset-1", @merger.merge("inset-x-1 hover:left-1 inset-1")) end def test_ring_and_shadow_classes_do_not_create_conflict assert_equal("ring shadow", @merger.merge("ring shadow")) assert_equal("ring-2 shadow-md", @merger.merge("ring-2 shadow-md")) assert_equal("shadow ring", @merger.merge("shadow ring")) assert_equal("shadow-md ring-2", @merger.merge("shadow-md ring-2")) end def test_touch_classes_do_create_conflicts_correctly assert_equal("touch-pan-right", @merger.merge("touch-pan-x touch-pan-right")) assert_equal("touch-pan-x", @merger.merge("touch-none touch-pan-x")) assert_equal("touch-none", @merger.merge("touch-pan-x touch-none")) assert_equal("touch-pan-x touch-pan-y touch-pinch-zoom", @merger.merge("touch-pan-x touch-pan-y touch-pinch-zoom")) assert_equal("touch-pan-x touch-pan-y touch-pinch-zoom", @merger.merge("touch-manipulation touch-pan-x touch-pan-y touch-pinch-zoom")) assert_equal("touch-auto", @merger.merge("touch-pan-x touch-pan-y touch-pinch-zoom touch-auto")) assert_equal("line-clamp-1", @merger.merge("overflow-auto inline line-clamp-1")) assert_equal("line-clamp-1 overflow-auto inline", @merger.merge("line-clamp-1 overflow-auto inline")) end end
ruby
MIT
83ef21d415234e01c1f7188d64f37ebaec9c21ea
2026-01-04T17:44:23.457574Z
false
gjtorikian/tailwind_merge
https://github.com/gjtorikian/tailwind_merge/blob/83ef21d415234e01c1f7188d64f37ebaec9c21ea/test/test_standalone_classes.rb
test/test_standalone_classes.rb
# frozen_string_literal: true require "test_helper" class TestStandaloneClasses < Minitest::Test def setup @merger = TailwindMerge::Merger.new end def test_merges_standalone_classes_from_same_group_correctly assert_equal("block", @merger.merge("inline block")) assert_equal("hover:inline", @merger.merge("hover:block hover:inline")) assert_equal("hover:block", @merger.merge("hover:block hover:block")) assert_equal("inline focus:inline hover:block hover:focus:block", @merger.merge("inline hover:inline focus:inline hover:block hover:focus:block")) assert_equal("line-through", @merger.merge("underline line-through")) assert_equal("no-underline", @merger.merge("line-through no-underline")) end end
ruby
MIT
83ef21d415234e01c1f7188d64f37ebaec9c21ea
2026-01-04T17:44:23.457574Z
false
gjtorikian/tailwind_merge
https://github.com/gjtorikian/tailwind_merge/blob/83ef21d415234e01c1f7188d64f37ebaec9c21ea/test/test_non_conflicting_classes.rb
test/test_non_conflicting_classes.rb
# frozen_string_literal: true require "test_helper" class TestNonConflictingClasses < Minitest::Test def setup @merger = TailwindMerge::Merger.new end def test_merges_non_conflicting_classes_correctly assert_equal("border-t border-white/10", @merger.merge("border-t border-white/10")) assert_equal("border-t border-white", @merger.merge("border-t border-white")) assert_equal("text-3.5xl text-black", @merger.merge("text-3.5xl text-black")) end end
ruby
MIT
83ef21d415234e01c1f7188d64f37ebaec9c21ea
2026-01-04T17:44:23.457574Z
false
gjtorikian/tailwind_merge
https://github.com/gjtorikian/tailwind_merge/blob/83ef21d415234e01c1f7188d64f37ebaec9c21ea/test/test_content_utilities.rb
test/test_content_utilities.rb
# frozen_string_literal: true require "test_helper" class TestContentUtilities < Minitest::Test def setup @merger = TailwindMerge::Merger.new end def test_merges_content_utilities_correctly assert_equal("content-[attr(data-content)]", @merger.merge("content-['hello'] content-[attr(data-content)]")) end end
ruby
MIT
83ef21d415234e01c1f7188d64f37ebaec9c21ea
2026-01-04T17:44:23.457574Z
false
gjtorikian/tailwind_merge
https://github.com/gjtorikian/tailwind_merge/blob/83ef21d415234e01c1f7188d64f37ebaec9c21ea/test/test_pseudo_variants.rb
test/test_pseudo_variants.rb
# frozen_string_literal: true require "test_helper" class TestPseudoVariants < Minitest::Test def setup @merger = TailwindMerge::Merger.new end def test_handles_pseudo_variants_conflicts_properly assert_equal("empty:p-3", @merger.merge("empty:p-2 empty:p-3")) # assert_equal("hover:empty:p-3", @merger.merge("hover:empty:p-2 hover:empty:p-3")) # assert_equal("read-only:p-3", @merger.merge("read-only:p-2 read-only:p-3")) end def test_handles_pseudo_variant_group_conflicts_properly assert_equal("group-empty:p-3", @merger.merge("group-empty:p-2 group-empty:p-3")) assert_equal("peer-empty:p-3", @merger.merge("peer-empty:p-2 peer-empty:p-3")) assert_equal("group-empty:p-2 peer-empty:p-3", @merger.merge("group-empty:p-2 peer-empty:p-3")) assert_equal("hover:group-empty:p-3", @merger.merge("hover:group-empty:p-2 hover:group-empty:p-3")) assert_equal("group-read-only:p-3", @merger.merge("group-read-only:p-2 group-read-only:p-3")) end end
ruby
MIT
83ef21d415234e01c1f7188d64f37ebaec9c21ea
2026-01-04T17:44:23.457574Z
false
gjtorikian/tailwind_merge
https://github.com/gjtorikian/tailwind_merge/blob/83ef21d415234e01c1f7188d64f37ebaec9c21ea/test/test_modifiers.rb
test/test_modifiers.rb
# frozen_string_literal: true require "test_helper" class TestModifiers < Minitest::Test def setup @merger = TailwindMerge::Merger.new end def test_conflicts_across_prefix_modifiers assert_equal("hover:inline", @merger.merge("hover:block hover:inline")) assert_equal("hover:block hover:focus:inline", @merger.merge("hover:block hover:focus:inline")) assert_equal("hover:block focus:hover:inline", @merger.merge("hover:block hover:focus:inline focus:hover:inline")) assert_equal("focus-within:block", @merger.merge("focus-within:inline focus-within:block")) end def test_conflicts_across_postfix_modifiers assert_equal("text-lg/8", @merger.merge("text-lg/7 text-lg/8")) assert_equal("text-lg/none leading-9", @merger.merge("text-lg/none leading-9")) assert_equal("text-lg/none", @merger.merge("leading-9 text-lg/none")) assert_equal("w-1/2", @merger.merge("w-full w-1/2")) config = { cache_size: 10, theme: {}, class_groups: { foo: ["foo-1/2", "foo-2/3"], bar: ["bar-1", "bar-2"], baz: ["baz-1", "baz-2"], }, conflicting_class_groups: {}, conflicting_class_group_modifiers: { baz: ["bar"], }, order_sensitive_modifiers: [], } custom_merger = TailwindMerge::Merger.new(config:) assert_equal("foo-2/3", custom_merger.merge("foo-1/2 foo-2/3")) assert_equal("foo-2/3", custom_merger.merge("foo-1/2 foo-2/3")) assert_equal("bar-2", custom_merger.merge("bar-1 bar-2")) assert_equal("bar-1 baz-1", custom_merger.merge("bar-1 baz-1")) assert_equal("bar-2", custom_merger.merge("bar-1/2 bar-2")) assert_equal("bar-1/2", custom_merger.merge("bar-2 bar-1/2")) assert_equal("baz-1/2", custom_merger.merge("bar-1 baz-1/2")) end def test_sorts_modifiers_correctly assert_equal("d:c:e:inline", @merger.merge("c:d:e:block d:c:e:inline")) assert_equal("*:before:inline", @merger.merge("*:before:block *:before:inline")) assert_equal("*:before:block before:*:inline", @merger.merge("*:before:block before:*:inline")) assert_equal("y:x:*:z:inline", @merger.merge("x:y:*:z:block y:x:*:z:inline")) end def test_sorts_modifiers_correctly_according_to_order_sensitive_modifiers config = { cache_size: 10, theme: {}, class_groups: { foo: ["foo-1", "foo-2"], }, conflicting_class_groups: {}, conflicting_class_group_modifiers: {}, order_sensitive_modifiers: ["a", "b"], } custom_merger = TailwindMerge::Merger.new(config:) assert_equal("d:c:e:foo-2", custom_merger.merge("c:d:e:foo-1 d:c:e:foo-2")) assert_equal("a:b:foo-2", custom_merger.merge("a:b:foo-1 a:b:foo-2")) assert_equal("a:b:foo-1 b:a:foo-2", custom_merger.merge("a:b:foo-1 b:a:foo-2")) assert_equal("y:x:a:z:foo-2", custom_merger.merge("x:y:a:z:foo-1 y:x:a:z:foo-2")) end end
ruby
MIT
83ef21d415234e01c1f7188d64f37ebaec9c21ea
2026-01-04T17:44:23.457574Z
false
gjtorikian/tailwind_merge
https://github.com/gjtorikian/tailwind_merge/blob/83ef21d415234e01c1f7188d64f37ebaec9c21ea/test/test_class_map.rb
test/test_class_map.rb
# frozen_string_literal: true require "test_helper" require "set" class TestClassMap < Minitest::Test def setup @class_utils = TailwindMerge::ClassGroupUtils.new(TailwindMerge::Config::DEFAULTS) @class_map = @class_utils.class_map end def class_groups_in_class_part(class_part) class_group_id = class_part[:class_group_id] validators = class_part[:validators] next_part = class_part[:next_part] class_groups = Set.new if class_group_id class_groups.add(class_group_id) end validators.each do |validator| class_groups.add(validator[:class_group_id]) end next_part.values.each do |next_class_part| class_groups_in_class_part(next_class_part).each do |class_group| class_groups.add(class_group) end end class_groups end def test_class_map_has_correct_class_groups_at_first_part result = {} @class_map[:next_part].each do |key, value| result[key] = class_groups_in_class_part(value).to_a.sort end refute(@class_map[:class_group_id]) assert_equal(0, @class_map[:validators].length) result = result.sort.to_h assert_equal( { "absolute" => ["position"], "accent" => ["accent"], "align" => ["vertical-align"], "animate" => ["animate"], "antialiased" => ["font-smoothing"], "appearance" => ["appearance"], "aspect" => ["aspect"], "auto" => ["auto-cols", "auto-rows"], "backdrop" => [ "backdrop-blur", "backdrop-brightness", "backdrop-contrast", "backdrop-filter", "backdrop-grayscale", "backdrop-hue-rotate", "backdrop-invert", "backdrop-opacity", "backdrop-saturate", "backdrop-sepia", ], "backface" => ["backface"], "basis" => ["basis"], "bg" => [ "bg-attachment", "bg-blend", "bg-clip", "bg-color", "bg-image", "bg-origin", "bg-position", "bg-repeat", "bg-size", ], "block" => ["display"], "blur" => ["blur"], "border" => [ "border-collapse", "border-color", "border-color-b", "border-color-e", "border-color-l", "border-color-r", "border-color-s", "border-color-t", "border-color-x", "border-color-y", "border-spacing", "border-spacing-x", "border-spacing-y", "border-style", "border-w", "border-w-b", "border-w-e", "border-w-l", "border-w-r", "border-w-s", "border-w-t", "border-w-x", "border-w-y", ], "bottom" => ["bottom"], "box" => ["box", "box-decoration"], "break" => ["break", "break-after", "break-before", "break-inside"], "brightness" => ["brightness"], "capitalize" => ["text-transform"], "caption" => ["caption"], "caret" => ["caret-color"], "clear" => ["clear"], "col" => ["col-end", "col-start", "col-start-end"], "collapse" => ["visibility"], "columns" => ["columns"], "container" => ["container"], "content" => ["align-content", "content"], "contents" => ["display"], "contrast" => ["contrast"], "cursor" => ["cursor"], "decoration" => ["text-decoration-color", "text-decoration-style", "text-decoration-thickness"], "delay" => ["delay"], "diagonal" => ["fvn-fraction"], "divide" => [ "divide-color", "divide-style", "divide-x", "divide-x-reverse", "divide-y", "divide-y-reverse", ], "drop" => ["drop-shadow", "drop-shadow-color"], "duration" => ["duration"], "ease" => ["ease"], "end" => ["end"], "field" => ["field-sizing"], "fill" => ["fill"], "filter" => ["filter"], "fixed" => ["position"], "flex" => ["display", "flex", "flex-direction", "flex-wrap"], "float" => ["float"], "flow" => ["display"], "font" => ["font-family", "font-stretch", "font-weight"], "forced" => ["forced-color-adjust"], "from" => ["gradient-from", "gradient-from-pos"], "gap" => ["gap", "gap-x", "gap-y"], "grayscale" => ["grayscale"], "grid" => ["display", "grid-cols", "grid-flow", "grid-rows"], "grow" => ["grow"], "h" => ["h"], "hidden" => ["display"], "hue" => ["hue-rotate"], "hyphens" => ["hyphens"], "indent" => ["indent"], "inline" => ["display"], "inset" => [ "inset", "inset-ring-color", "inset-ring-w", "inset-shadow", "inset-shadow-color", "inset-x", "inset-y", ], "invert" => ["invert"], "invisible" => ["visibility"], "isolate" => ["isolation"], "isolation" => ["isolation"], "italic" => ["font-style"], "items" => ["align-items"], "justify" => ["justify-content", "justify-items", "justify-self"], "leading" => ["leading"], "left" => ["left"], "line" => ["line-clamp", "text-decoration"], "lining" => ["fvn-figure"], "list" => ["display", "list-image", "list-style-position", "list-style-type"], "lowercase" => ["text-transform"], "m" => ["m"], "mask" => [ "mask-clip", "mask-composite", "mask-image", "mask-image-b-from-color", "mask-image-b-from-pos", "mask-image-b-to-color", "mask-image-b-to-pos", "mask-image-conic-from-color", "mask-image-conic-from-pos", "mask-image-conic-pos", "mask-image-conic-to-color", "mask-image-conic-to-pos", "mask-image-l-from-color", "mask-image-l-from-pos", "mask-image-l-to-color", "mask-image-l-to-pos", "mask-image-linear-from-color", "mask-image-linear-from-pos", "mask-image-linear-pos", "mask-image-linear-to-color", "mask-image-linear-to-pos", "mask-image-r-from-color", "mask-image-r-from-pos", "mask-image-r-to-color", "mask-image-r-to-pos", "mask-image-radial", "mask-image-radial-from-color", "mask-image-radial-from-pos", "mask-image-radial-pos", "mask-image-radial-shape", "mask-image-radial-size", "mask-image-radial-to-color", "mask-image-radial-to-pos", "mask-image-t-from-color", "mask-image-t-from-pos", "mask-image-t-to-color", "mask-image-t-to-pos", "mask-image-x-from-color", "mask-image-x-from-pos", "mask-image-x-to-color", "mask-image-x-to-pos", "mask-image-y-from-color", "mask-image-y-from-pos", "mask-image-y-to-color", "mask-image-y-to-pos", "mask-mode", "mask-origin", "mask-position", "mask-repeat", "mask-size", "mask-type", ], "max" => ["max-h", "max-w"], "mb" => ["mb"], "me" => ["me"], "min" => ["min-h", "min-w"], "mix" => ["mix-blend"], "ml" => ["ml"], "mr" => ["mr"], "ms" => ["ms"], "mt" => ["mt"], "mx" => ["mx"], "my" => ["my"], "no" => ["text-decoration"], "normal" => ["fvn-normal", "text-transform"], "not" => ["font-style", "sr"], "object" => ["object-fit", "object-position"], "oldstyle" => ["fvn-figure"], "opacity" => ["opacity"], "order" => ["order"], "ordinal" => ["fvn-ordinal"], "origin" => ["transform-origin"], "outline" => ["outline-color", "outline-offset", "outline-style", "outline-w"], "overflow" => ["overflow", "overflow-x", "overflow-y"], "overline" => ["text-decoration"], "overscroll" => ["overscroll", "overscroll-x", "overscroll-y"], "p" => ["p"], "pb" => ["pb"], "pe" => ["pe"], "perspective" => ["perspective", "perspective-origin"], "pl" => ["pl"], "place" => ["place-content", "place-items", "place-self"], "placeholder" => ["placeholder-color"], "pointer" => ["pointer-events"], "pr" => ["pr"], "proportional" => ["fvn-spacing"], "ps" => ["ps"], "pt" => ["pt"], "px" => ["px"], "py" => ["py"], "relative" => ["position"], "resize" => ["resize"], "right" => ["right"], "ring" => ["ring-color", "ring-offset-color", "ring-offset-w", "ring-w", "ring-w-inset"], "rotate" => ["rotate", "rotate-x", "rotate-y", "rotate-z"], "rounded" => [ "rounded", "rounded-b", "rounded-bl", "rounded-br", "rounded-e", "rounded-ee", "rounded-es", "rounded-l", "rounded-r", "rounded-s", "rounded-se", "rounded-ss", "rounded-t", "rounded-tl", "rounded-tr", ], "row" => ["row-end", "row-start", "row-start-end"], "saturate" => ["saturate"], "scale" => ["scale", "scale-3d", "scale-x", "scale-y", "scale-z"], "scheme" => ["color-scheme"], "scroll" => [ "scroll-behavior", "scroll-m", "scroll-mb", "scroll-me", "scroll-ml", "scroll-mr", "scroll-ms", "scroll-mt", "scroll-mx", "scroll-my", "scroll-p", "scroll-pb", "scroll-pe", "scroll-pl", "scroll-pr", "scroll-ps", "scroll-pt", "scroll-px", "scroll-py", ], "select" => ["select"], "self" => ["align-self"], "sepia" => ["sepia"], "shadow" => ["shadow", "shadow-color"], "shrink" => ["shrink"], "size" => ["size"], "skew" => ["skew", "skew-x", "skew-y"], "slashed" => ["fvn-slashed-zero"], "snap" => ["snap-align", "snap-stop", "snap-strictness", "snap-type"], "space" => ["space-x", "space-x-reverse", "space-y", "space-y-reverse"], "sr" => ["sr"], "stacked" => ["fvn-fraction"], "start" => ["start"], "static" => ["position"], "sticky" => ["position"], "stroke" => ["stroke", "stroke-w"], "subpixel" => ["font-smoothing"], "table" => ["display", "table-layout"], "tabular" => ["fvn-spacing"], "text" => [ "font-size", "text-alignment", "text-color", "text-overflow", "text-shadow", "text-shadow-color", "text-wrap", ], "to" => ["gradient-to", "gradient-to-pos"], "top" => ["top"], "touch" => ["touch", "touch-pz", "touch-x", "touch-y"], "tracking" => ["tracking"], "transform" => ["transform", "transform-style"], "transition" => ["transition", "transition-behavior"], "translate" => ["translate", "translate-none", "translate-x", "translate-y", "translate-z"], "truncate" => ["text-overflow"], "underline" => ["text-decoration", "underline-offset"], "uppercase" => ["text-transform"], "via" => ["gradient-via", "gradient-via-pos"], "visible" => ["visibility"], "w" => ["w"], "whitespace" => ["whitespace"], "will" => ["will-change"], "wrap" => ["wrap"], "z" => ["z"], }, result, ) end end
ruby
MIT
83ef21d415234e01c1f7188d64f37ebaec9c21ea
2026-01-04T17:44:23.457574Z
false
gjtorikian/tailwind_merge
https://github.com/gjtorikian/tailwind_merge/blob/83ef21d415234e01c1f7188d64f37ebaec9c21ea/test/test_negative_values.rb
test/test_negative_values.rb
# frozen_string_literal: true require "test_helper" class TestNegativeValues < Minitest::Test def setup @merger = TailwindMerge::Merger.new end def test_handles_negative_value_conflicts_correctly assert_equal("-m-5", @merger.merge("-m-2 -m-5")) assert_equal("-top-2000", @merger.merge("-top-12 -top-2000")) end def test_handles_conflicts_between_positive_and_negative_values_correctly assert_equal("m-auto", @merger.merge("-m-2 m-auto")) assert_equal("-top-69", @merger.merge("top-12 -top-69")) end def test_handles_conflicts_across_groups_with_negative_values_correctly assert_equal("inset-x-1", @merger.merge("-right-1 inset-x-1")) assert_equal("focus:hover:inset-x-1", @merger.merge("hover:focus:-right-1 focus:hover:inset-x-1")) end end
ruby
MIT
83ef21d415234e01c1f7188d64f37ebaec9c21ea
2026-01-04T17:44:23.457574Z
false
gjtorikian/tailwind_merge
https://github.com/gjtorikian/tailwind_merge/blob/83ef21d415234e01c1f7188d64f37ebaec9c21ea/test/test_cache_tampering.rb
test/test_cache_tampering.rb
# frozen_string_literal: true require "test_helper" class TestCacheTampering < Minitest::Test def setup @merger = TailwindMerge::Merger.new end def test_cached_values_are_immutable classes = @merger.merge("font-medium font-bold") assert_raises(FrozenError) do classes << " text-white" end end end
ruby
MIT
83ef21d415234e01c1f7188d64f37ebaec9c21ea
2026-01-04T17:44:23.457574Z
false
gjtorikian/tailwind_merge
https://github.com/gjtorikian/tailwind_merge/blob/83ef21d415234e01c1f7188d64f37ebaec9c21ea/test/test_class_group_conflicts.rb
test/test_class_group_conflicts.rb
# frozen_string_literal: true require "test_helper" class TestClassGroupConflicts < Minitest::Test def setup @merger = TailwindMerge::Merger.new end def test_merge_classes_from_same_group_correctly assert_equal("overflow-x-hidden", @merger.merge("overflow-x-auto overflow-x-hidden")) assert_equal("basis-auto", @merger.merge("basis-full basis-auto")) assert_equal("w-fit", @merger.merge("w-full w-fit")) assert_equal("overflow-x-scroll", @merger.merge("overflow-x-auto overflow-x-hidden overflow-x-scroll")) assert_equal("hover:overflow-x-hidden overflow-x-scroll", @merger.merge("overflow-x-auto hover:overflow-x-hidden overflow-x-scroll")) assert_equal("hover:overflow-x-auto overflow-x-scroll", @merger.merge("overflow-x-auto hover:overflow-x-hidden hover:overflow-x-auto overflow-x-scroll")) assert_equal("col-span-full", @merger.merge("col-span-1 col-span-full")) assert_equal("gap-px basis-3", @merger.merge("gap-2 gap-px basis-px basis-3")) end def test_merges_classes_from_font_variant_numeric_section_correctly assert_equal("lining-nums tabular-nums diagonal-fractions", @merger.merge("lining-nums tabular-nums diagonal-fractions")) assert_equal("tabular-nums diagonal-fractions", @merger.merge("normal-nums tabular-nums diagonal-fractions")) assert_equal("normal-nums", @merger.merge("tabular-nums diagonal-fractions normal-nums")) assert_equal("proportional-nums", @merger.merge("tabular-nums proportional-nums")) end end
ruby
MIT
83ef21d415234e01c1f7188d64f37ebaec9c21ea
2026-01-04T17:44:23.457574Z
false
gjtorikian/tailwind_merge
https://github.com/gjtorikian/tailwind_merge/blob/83ef21d415234e01c1f7188d64f37ebaec9c21ea/lib/tailwind_merge.rb
lib/tailwind_merge.rb
# frozen_string_literal: true require "lru_redux" require_relative "tailwind_merge/version" require_relative "tailwind_merge/validators" require_relative "tailwind_merge/config" require_relative "tailwind_merge/class_group_utils" require_relative "tailwind_merge/sort_modifiers" require_relative "tailwind_merge/parse_class_name" require "strscan" require "set" module TailwindMerge class Merger include Config include ParseClassName include SortModifiers SPLIT_CLASSES_REGEX = /\s+/ def initialize(config: {}) @config = merge_config(config) @config[:important_modifier] = @config[:important_modifier].to_s @class_utils = TailwindMerge::ClassGroupUtils.new(@config) @cache = LruRedux::Cache.new(@config[:cache_size], @config[:ignore_empty_cache]) end def merge(classes) normalized = classes.is_a?(Array) ? classes.compact.join(" ") : classes.to_s @cache.getset(normalized) do merge_class_list(normalized).freeze end end private def merge_class_list(class_list) # Set of class_group_ids in following format: # `{importantModifier}{variantModifiers}{classGroupId}` # @example 'float' # @example 'hover:focus:bg-color' # @example 'md:!pr' trimmed = class_list.strip return "" if trimmed.empty? class_groups_in_conflict = Set.new merged_classes = [] trimmed.split(SPLIT_CLASSES_REGEX).reverse_each do |original_class_name| result = parse_class_name(original_class_name, prefix: @config[:prefix]) is_external = result.is_external modifiers = result.modifiers has_important_modifier = result.has_important_modifier base_class_name = result.base_class_name maybe_postfix_modifier_position = result.maybe_postfix_modifier_position if is_external merged_classes.push(original_class_name) next end has_postfix_modifier = maybe_postfix_modifier_position ? true : false actual_base_class_name = has_postfix_modifier ? base_class_name[0...maybe_postfix_modifier_position] : base_class_name class_group_id = @class_utils.class_group_id(actual_base_class_name) unless class_group_id unless has_postfix_modifier # Not a Tailwind class merged_classes << original_class_name next end class_group_id = @class_utils.class_group_id(base_class_name) unless class_group_id # Not a Tailwind class merged_classes << original_class_name next end has_postfix_modifier = false end variant_modifier = sort_modifiers(modifiers, @config[:order_sensitive_modifiers]).join(":") modifier_id = has_important_modifier ? "#{variant_modifier}#{IMPORTANT_MODIFIER}" : variant_modifier class_id = "#{modifier_id}#{class_group_id}" # Tailwind class omitted due to conflict next if class_groups_in_conflict.include?(class_id) class_groups_in_conflict << class_id @class_utils.get_conflicting_class_group_ids(class_group_id, has_postfix_modifier).each do |conflicting_id| class_groups_in_conflict << "#{modifier_id}#{conflicting_id}" end # Tailwind class not in conflict merged_classes << original_class_name end merged_classes.reverse.join(" ") end end end
ruby
MIT
83ef21d415234e01c1f7188d64f37ebaec9c21ea
2026-01-04T17:44:23.457574Z
false
gjtorikian/tailwind_merge
https://github.com/gjtorikian/tailwind_merge/blob/83ef21d415234e01c1f7188d64f37ebaec9c21ea/lib/tailwind_merge/version.rb
lib/tailwind_merge/version.rb
# frozen_string_literal: true module TailwindMerge VERSION = "1.3.2" end
ruby
MIT
83ef21d415234e01c1f7188d64f37ebaec9c21ea
2026-01-04T17:44:23.457574Z
false
gjtorikian/tailwind_merge
https://github.com/gjtorikian/tailwind_merge/blob/83ef21d415234e01c1f7188d64f37ebaec9c21ea/lib/tailwind_merge/sort_modifiers.rb
lib/tailwind_merge/sort_modifiers.rb
# frozen_string_literal: true module TailwindMerge module SortModifiers # Sorts modifiers according to following schema: # - Predefined modifiers are sorted alphabetically # - When an arbitrary variant appears, it must be preserved which modifiers are before and after it def sort_modifiers(modifiers, order_sensitive_modifiers) return modifiers if modifiers.size <= 1 sorted_modifiers = [] unsorted_modifiers = [] modifiers.each do |modifier| is_position_sensitive = modifier.start_with?("[") || order_sensitive_modifiers.include?(modifier) if is_position_sensitive sorted_modifiers.concat(unsorted_modifiers.sort) sorted_modifiers << modifier unsorted_modifiers.clear else unsorted_modifiers << modifier end end sorted_modifiers.concat(unsorted_modifiers.sort) sorted_modifiers end end end
ruby
MIT
83ef21d415234e01c1f7188d64f37ebaec9c21ea
2026-01-04T17:44:23.457574Z
false
gjtorikian/tailwind_merge
https://github.com/gjtorikian/tailwind_merge/blob/83ef21d415234e01c1f7188d64f37ebaec9c21ea/lib/tailwind_merge/config.rb
lib/tailwind_merge/config.rb
# frozen_string_literal: true require "set" module TailwindMerge module Config include Validators THEME_KEYS = [ "color", "font", "text", "font-weight", "tracking", "leading", "breakpoint", "container", "spacing", "radius", "shadow", "inset-shadow", "text-shadow", "drop-shadow", "blur", "perspective", "aspect", "ease", "animate", ].freeze THEME_KEYS.each do |key| const_set("THEME_#{key.upcase.tr("-", "_")}", ->(config) { config[:theme].fetch(key, nil) }) end VALID_THEME_IDS = Set.new(THEME_KEYS.map { |theme_key| const_get("THEME_#{theme_key.upcase.tr("-", "_")}").object_id }).freeze SCALE_BREAK = -> { ["auto", "avoid", "all", "avoid-page", "page", "left", "right", "column"] } SCALE_POSITION = -> { [ "center", "top", "bottom", "left", "right", "top-left", # Deprecated since Tailwind CSS v4.1.0, see https://github.com/tailwindlabs/tailwindcss/pull/17378 "left-top", "top-right", # Deprecated since Tailwind CSS v4.1.0, see https://github.com/tailwindlabs/tailwindcss/pull/17378 "right-top", "bottom-right", # Deprecated since Tailwind CSS v4.1.0, see https://github.com/tailwindlabs/tailwindcss/pull/17378 "right-bottom", "bottom-left", # Deprecated since Tailwind CSS v4.1.0, see https://github.com/tailwindlabs/tailwindcss/pull/17378 "left-bottom", ] } SCALE_POSITION_WITH_ARBITRARY = -> { [*SCALE_POSITION.call, IS_ARBITRARY_VARIABLE, IS_ARBITRARY_VALUE] } SCALE_OVERFLOW = -> { ["auto", "hidden", "clip", "visible", "scroll"] } SCALE_OVERSCROLL = -> { ["auto", "contain", "none"] } SCALE_UNAMBIGUOUS_SPACING = -> { [IS_ARBITRARY_VARIABLE, IS_ARBITRARY_VALUE, THEME_SPACING] } SCALE_INSET = ->(_config) { [ IS_FRACTION, "full", "auto", *SCALE_UNAMBIGUOUS_SPACING.call, ] } SCALE_GRID_TEMPLATE_COLS_ROWS = -> { [IS_INTEGER, "none", "subgrid", IS_ARBITRARY_VARIABLE, IS_ARBITRARY_VALUE] } SCALE_GRID_COL_ROW_START_AND_END = -> { [ "auto", { "span" => ["full", IS_INTEGER, IS_ARBITRARY_VARIABLE, IS_ARBITRARY_VALUE] }, IS_INTEGER, IS_ARBITRARY_VARIABLE, IS_ARBITRARY_VALUE, ] } SCALE_GRID_COL_ROW_START_OR_END = -> { [IS_INTEGER, "auto", IS_ARBITRARY_VARIABLE, IS_ARBITRARY_VALUE] } SCALE_GRID_AUTO_COLS_ROWS = -> { ["auto", "min", "max", "fr", IS_ARBITRARY_VARIABLE, IS_ARBITRARY_VALUE] } SCALE_ALIGN_PRIMARY_AXIS = -> { ["start", "end", "center", "between", "around", "evenly", "stretch", "baseline", "center-safe", "end-safe"] } SCALE_ALIGN_SECONDARY_AXIS = -> { ["start", "end", "center", "stretch", "center-safe", "end-safe"] } SCALE_MARGIN = -> { ["auto", *SCALE_UNAMBIGUOUS_SPACING.call] } SCALE_SIZING = -> { [ IS_FRACTION, "auto", "full", "dvw", "dvh", "lvw", "lvh", "svw", "svh", "min", "max", "fit", *SCALE_UNAMBIGUOUS_SPACING.call, ] } SCALE_COLOR = -> { [THEME_COLOR, IS_ARBITRARY_VARIABLE, IS_ARBITRARY_VALUE] } SCALE_BG_POSITION = -> { [*SCALE_POSITION.call, IS_ARBITRARY_VARIABLE_POSITION, IS_ARBITRARY_POSITION, "position" => [IS_ARBITRARY_VARIABLE, IS_ARBITRARY_VALUE]] } SCALE_BG_REPEAT = -> { ["no-repeat", "repeat" => ["", "x", "y", "space", "round"]] } SCALE_BG_SIZE = -> { ["auto", "cover", "contain", IS_ARBITRARY_VARIABLE_SIZE, IS_ARBITRARY_SIZE, "size" => [IS_ARBITRARY_VARIABLE, IS_ARBITRARY_VALUE]] } SCALE_GRADIENT_STOP_POSITION = -> { [IS_PERCENT, IS_ARBITRARY_VARIABLE_LENGTH, IS_ARBITRARY_LENGTH] } SCALE_RADIUS = -> { [ # Deprecated since Tailwind CSS v4.0.0 "", "none", "full", THEME_RADIUS, IS_ARBITRARY_VARIABLE, IS_ARBITRARY_VALUE, ] } SCALE_BORDER_WIDTH = -> { ["", IS_NUMBER, IS_ARBITRARY_VARIABLE_LENGTH, IS_ARBITRARY_LENGTH] } SCALE_LINE_STYLE = -> { ["solid", "dashed", "dotted", "double"] } SCALE_BLEND_MODE = -> { [ "normal", "multiply", "screen", "overlay", "darken", "lighten", "color-dodge", "color-burn", "hard-light", "soft-light", "difference", "exclusion", "hue", "saturation", "color", "luminosity", ] } SCALE_MASK_IMAGE_POSITION = -> { [IS_NUMBER, IS_PERCENT, IS_ARBITRARY_VARIABLE_POSITION, IS_ARBITRARY_POSITION] } SCALE_BLUR = -> { [ "", "none", THEME_BLUR, IS_ARBITRARY_VARIABLE, IS_ARBITRARY_VALUE, ] } SCALE_ROTATE = -> { ["none", IS_NUMBER, IS_ARBITRARY_VARIABLE, IS_ARBITRARY_VALUE] } SCALE_SCALE = -> { ["none", IS_NUMBER, IS_ARBITRARY_VARIABLE, IS_ARBITRARY_VALUE] } SCALE_SKEW = -> { [IS_NUMBER, IS_ARBITRARY_VARIABLE, IS_ARBITRARY_VALUE] } SCALE_TRANSLATE = -> { [IS_FRACTION, "full", *SCALE_UNAMBIGUOUS_SPACING.call] } DEFAULTS = { cache_size: 500, prefix: nil, ignore_empty_cache: true, theme: { "animate" => ["spin", "ping", "pulse", "bounce"], "aspect" => ["video"], "blur" => [IS_TSHIRT_SIZE], "breakpoint" => [IS_TSHIRT_SIZE], "color" => [IS_ANY], "container" => [IS_TSHIRT_SIZE], "drop-shadow" => [IS_TSHIRT_SIZE], "ease" => ["in", "out", "in-out"], "font" => [IS_ANY_NON_ARBITRARY], "font-weight" => [ "thin", "extralight", "light", "normal", "medium", "semibold", "bold", "extrabold", "black", ], "inset-shadow" => [IS_TSHIRT_SIZE], "leading" => ["none", "tight", "snug", "normal", "relaxed", "loose"], "perspective" => ["dramatic", "near", "normal", "midrange", "distant", "none"], "radius" => [IS_TSHIRT_SIZE], "shadow" => [IS_TSHIRT_SIZE], "spacing" => ["px", IS_NUMBER], "text" => [IS_TSHIRT_SIZE], "text-shadow" => [IS_TSHIRT_SIZE], "tracking" => ["tighter", "tight", "normal", "wide", "wider", "widest"], }, class_groups: { ########## # Layout ########## ## # Aspect Ratio # @see https://tailwindcss.com/docs/aspect-ratio ## "aspect" => [ { "aspect" => [ "auto", "square", IS_FRACTION, IS_ARBITRARY_VALUE, IS_ARBITRARY_VARIABLE, THEME_ASPECT, ], }, ], ## # Container # @see https://tailwindcss.com/docs/container # @deprecated since Tailwind CSS v4.0.0 ## "container" => ["container"], ## # Columns # @see https://tailwindcss.com/docs/columns ## "columns" => [{ "columns" => [IS_TSHIRT_SIZE] }], ## # Break After # @see https://tailwindcss.com/docs/break-after ## "break-after" => [{ "break-after" => SCALE_BREAK.call }], ## # Break Before # @see https://tailwindcss.com/docs/break-before ## "break-before" => [{ "break-before" => SCALE_BREAK.call }], ## # Break Inside # @see https://tailwindcss.com/docs/break-inside ## "break-inside" => [{ "break-inside" => ["auto", "avoid", "avoid-page", "avoid-column"] }], ## # Box Decoration Break # @see https://tailwindcss.com/docs/box-decoration-break ## "box-decoration" => [{ "box-decoration" => ["slice", "clone"] }], ## # Box Sizing # @see https://tailwindcss.com/docs/box-sizing ## "box" => [{ "box" => ["border", "content"] }], ## # Display # @see https://tailwindcss.com/docs/display ## "display" => [ "block", "inline-block", "inline", "flex", "inline-flex", "table", "inline-table", "table-caption", "table-cell", "table-column", "table-column-group", "table-footer-group", "table-header-group", "table-row-group", "table-row", "flow-root", "grid", "inline-grid", "contents", "list-item", "hidden", ], ## # Screen Reader Only # @see https://tailwindcss.com/docs/display#screen-reader-only ## "sr" => ["sr-only", "not-sr-only"], ## # Floats # @see https://tailwindcss.com/docs/float ## "float" => [{ "float" => ["right", "left", "none", "start", "end"] }], ## # Clear # @see https://tailwindcss.com/docs/clear ## "clear" => [{ "clear" => ["left", "right", "both", "none", "start", "end"] }], ## # Isolation # @see https://tailwindcss.com/docs/isolation ## "isolation" => ["isolate", "isolation-auto"], ## # Object Fit # @see https://tailwindcss.com/docs/object-fit ## "object-fit" => [{ "object" => ["contain", "cover", "fill", "none", "scale-down"] }], ## # Object Position # @see https://tailwindcss.com/docs/object-position ## "object-position" => [{ "object" => SCALE_POSITION_WITH_ARBITRARY.call }], ## # Overflow # @see https://tailwindcss.com/docs/overflow ## "overflow" => [{ "overflow" => SCALE_OVERFLOW.call }], ## # Overflow X # @see https://tailwindcss.com/docs/overflow ## "overflow-x" => [{ "overflow-x" => SCALE_OVERFLOW.call }], ## # Overflow Y # @see https://tailwindcss.com/docs/overflow ## "overflow-y" => [{ "overflow-y" => SCALE_OVERSCROLL.call }], ## # Overscroll Behavior # @see https://tailwindcss.com/docs/overscroll-behavior ## "overscroll" => [{ "overscroll" => SCALE_OVERSCROLL.call }], ## # Overscroll Behavior X # @see https://tailwindcss.com/docs/overscroll-behavior ## "overscroll-x" => [{ "overscroll-x" => SCALE_OVERSCROLL.call }], ## # Overscroll Behavior Y # @see https://tailwindcss.com/docs/overscroll-behavior ## "overscroll-y" => [{ "overscroll-y" => SCALE_OVERSCROLL.call }], ## # Position # @see https://tailwindcss.com/docs/position ## "position" => ["static", "fixed", "absolute", "relative", "sticky"], ## # Top / Right / Bottom / Left # @see https://tailwindcss.com/docs/top-right-bottom-left ## "inset" => [{ "inset" => [SCALE_INSET] }], ## # Right / Left # @see https://tailwindcss.com/docs/top-right-bottom-left ## "inset-x" => [{ "inset-x" => [SCALE_INSET] }], ## # Top / Bottom # @see https://tailwindcss.com/docs/top-right-bottom-left ## "inset-y" => [{ "inset-y" => [SCALE_INSET] }], # # Start # @see https://tailwindcss.com/docs/top-right-bottom-left # "start" => [{ "start" => [SCALE_INSET] }], # # End # @see https://tailwindcss.com/docs/top-right-bottom-left # "end" => [{ "end" => [SCALE_INSET] }], ## # Top # @see https://tailwindcss.com/docs/top-right-bottom-left ## "top" => [{ "top" => [SCALE_INSET] }], ## # Right # @see https://tailwindcss.com/docs/top-right-bottom-left ## "right" => [{ "right" => [SCALE_INSET] }], ## # Bottom # @see https://tailwindcss.com/docs/top-right-bottom-left ## "bottom" => [{ "bottom" => [SCALE_INSET] }], ## # Left # @see https://tailwindcss.com/docs/top-right-bottom-left ## "left" => [{ "left" => [SCALE_INSET] }], ## # Visibility # @see https://tailwindcss.com/docs/visibility ## "visibility" => ["visible", "invisible", "collapse"], ## # Z-Index # @see https://tailwindcss.com/docs/z-index ## "z" => [{ "z" => [IS_INTEGER, "auto", IS_ARBITRARY_VARIABLE, IS_ARBITRARY_VALUE] }], ########## # Flexbox and Grid ########## # Flex Basis # @see https://tailwindcss.com/docs/flex-basis ## "basis" => [{ "basis" => [ IS_FRACTION, "full", "auto", THEME_CONTAINER, *SCALE_UNAMBIGUOUS_SPACING.call, ], }], ## # Flex Direction # @see https://tailwindcss.com/docs/flex-direction ## "flex-direction" => [{ "flex" => ["row", "row-reverse", "col", "col-reverse"] }], ## # Flex Wrap # @see https://tailwindcss.com/docs/flex-wrap ## "flex-wrap" => [{ "flex" => ["nowrap", "wrap", "wrap-reverse"] }], ## # Flex # @see https://tailwindcss.com/docs/flex ## "flex" => [{ "flex" => [IS_NUMBER, IS_FRACTION, "auto", "initial", "none", Validators::IS_ARBITRARY_VALUE] }], ## # Flex Grow # @see https://tailwindcss.com/docs/flex-grow ## "grow" => [{ "grow" => ["", IS_NUMBER, IS_ARBITRARY_VARIABLE, IS_ARBITRARY_VALUE] }], ## # Flex Shrink # @see https://tailwindcss.com/docs/flex-shrink ## "shrink" => [{ "shrink" => ["", IS_NUMBER, IS_ARBITRARY_VARIABLE, IS_ARBITRARY_VALUE] }], ## # Order # @see https://tailwindcss.com/docs/order ## "order" => [{ "order" => [ IS_INTEGER, "first", "last", "none", IS_ARBITRARY_VARIABLE, IS_ARBITRARY_VALUE, ], }], ## # Grid Template Columns # @see https://tailwindcss.com/docs/grid-template-columns ## "grid-cols" => [{ "grid-cols" => SCALE_GRID_TEMPLATE_COLS_ROWS.call }], ## # Grid Column Start / End # @see https://tailwindcss.com/docs/grid-column ## "col-start-end" => [{ "col" => SCALE_GRID_COL_ROW_START_AND_END.call }], ## # Grid Column Start # @see https://tailwindcss.com/docs/grid-column ## "col-start" => [{ "col-start" => SCALE_GRID_COL_ROW_START_OR_END.call }], ## # Grid Column End # @see https://tailwindcss.com/docs/grid-column ## "col-end" => [{ "col-end" => SCALE_GRID_COL_ROW_START_OR_END.call }], ## # Grid Template Rows # @see https://tailwindcss.com/docs/grid-template-rows ## "grid-rows" => [{ "grid-rows" => SCALE_GRID_TEMPLATE_COLS_ROWS.call }], ## # Grid Row Start / End # @see https://tailwindcss.com/docs/grid-row ## "row-start-end" => [{ "row" => SCALE_GRID_COL_ROW_START_AND_END.call }], ## # Grid Row Start # @see https://tailwindcss.com/docs/grid-row ## "row-start" => [{ "row-start" => SCALE_GRID_COL_ROW_START_OR_END.call }], ## # Grid Row End # @see https://tailwindcss.com/docs/grid-row ## "row-end" => [{ "row-end" => SCALE_GRID_COL_ROW_START_OR_END.call }], ## # Grid Auto Flow # @see https://tailwindcss.com/docs/grid-auto-flow ## "grid-flow" => [{ "grid-flow" => ["row", "col", "dense", "row-dense", "col-dense"] }], ## # Grid Auto Columns # @see https://tailwindcss.com/docs/grid-auto-columns ## "auto-cols" => [{ "auto-cols" => SCALE_GRID_AUTO_COLS_ROWS.call }], ## # Grid Auto Rows # @see https://tailwindcss.com/docs/grid-auto-rows ## "auto-rows" => [{ "auto-rows" => SCALE_GRID_AUTO_COLS_ROWS.call }], ## # Gap # @see https://tailwindcss.com/docs/gap ## "gap" => [{ "gap" => SCALE_UNAMBIGUOUS_SPACING.call }], ## # Gap X # @see https://tailwindcss.com/docs/gap ## "gap-x" => [{ "gap-x" => SCALE_UNAMBIGUOUS_SPACING.call }], ## # Gap Y # @see https://tailwindcss.com/docs/gap ## "gap-y" => [{ "gap-y" => SCALE_UNAMBIGUOUS_SPACING.call }], ## # Justify Content # @see https://tailwindcss.com/docs/justify-content ## "justify-content" => [{ "justify" => [*SCALE_ALIGN_PRIMARY_AXIS.call, "normal"] }], ## # Justify Items # @see https://tailwindcss.com/docs/justify-items ## "justify-items" => [{ "justify-items" => [*SCALE_ALIGN_SECONDARY_AXIS.call, "normal"] }], ## # Justify Self # @see https://tailwindcss.com/docs/justify-self ## "justify-self" => [{ "justify-self" => ["auto", *SCALE_ALIGN_SECONDARY_AXIS.call] }], ## # Align Content # @see https://tailwindcss.com/docs/align-content ## "align-content" => [{ "content" => ["normal", *SCALE_ALIGN_PRIMARY_AXIS.call] }], ## # Align Items # @see https://tailwindcss.com/docs/align-items ## "align-items" => [{ "items" => [*SCALE_ALIGN_SECONDARY_AXIS.call, "baseline" => ["", "last"]] }], ## # Align Self # @see https://tailwindcss.com/docs/align-self ## "align-self" => [{ "self" => ["auto", *SCALE_ALIGN_SECONDARY_AXIS.call, { "baseline" => ["", "last"] }] }], ## # Place Content # @see https://tailwindcss.com/docs/place-content ## "place-content" => [{ "place-content" => SCALE_ALIGN_PRIMARY_AXIS.call }], ## # Place Items # @see https://tailwindcss.com/docs/place-items ## "place-items" => [{ "place-items" => [*SCALE_ALIGN_SECONDARY_AXIS.call, "baseline"] }], ## # Place Self # @see https://tailwindcss.com/docs/place-self ## "place-self" => [{ "place-self" => ["auto", *SCALE_ALIGN_SECONDARY_AXIS.call] }], # Spacing ## # Padding # @see https://tailwindcss.com/docs/padding ## "p" => [{ "p" => SCALE_UNAMBIGUOUS_SPACING.call }], ## # Padding X # @see https://tailwindcss.com/docs/padding ## "px" => [{ "px" => SCALE_UNAMBIGUOUS_SPACING.call }], ## # Padding Y # @see https://tailwindcss.com/docs/padding ## "py" => [{ "py" => SCALE_UNAMBIGUOUS_SPACING.call }], # # Padding Start # @see https://tailwindcss.com/docs/padding # "ps" => [{ "ps" => SCALE_UNAMBIGUOUS_SPACING.call }], # # Padding End # @see https://tailwindcss.com/docs/padding # "pe" => [{ "pe" => SCALE_UNAMBIGUOUS_SPACING.call }], ## # Padding Top # @see https://tailwindcss.com/docs/padding ## "pt" => [{ "pt" => SCALE_UNAMBIGUOUS_SPACING.call }], ## # Padding Right # @see https://tailwindcss.com/docs/padding ## "pr" => [{ "pr" => SCALE_UNAMBIGUOUS_SPACING.call }], ## # Padding Bottom # @see https://tailwindcss.com/docs/padding ## "pb" => [{ "pb" => SCALE_UNAMBIGUOUS_SPACING.call }], ## # Padding Left # @see https://tailwindcss.com/docs/padding ## "pl" => [{ "pl" => SCALE_UNAMBIGUOUS_SPACING.call }], ## # Margin # @see https://tailwindcss.com/docs/margin ## "m" => [{ "m" => SCALE_MARGIN.call }], ## # Margin X # @see https://tailwindcss.com/docs/margin ## "mx" => [{ "mx" => SCALE_MARGIN.call }], ## # Margin Y # @see https://tailwindcss.com/docs/margin ## "my" => [{ "my" => SCALE_MARGIN.call }], # # Margin Start # @see https://tailwindcss.com/docs/margin # "ms" => [{ "ms" => SCALE_MARGIN.call }], # # Margin End # @see https://tailwindcss.com/docs/margin # "me" => [{ "me" => SCALE_MARGIN.call }], ## # Margin Top # @see https://tailwindcss.com/docs/margin ## "mt" => [{ "mt" => SCALE_MARGIN.call }], ## # Margin Right # @see https://tailwindcss.com/docs/margin ## "mr" => [{ "mr" => SCALE_MARGIN.call }], ## # Margin Bottom # @see https://tailwindcss.com/docs/margin ## "mb" => [{ "mb" => SCALE_MARGIN.call }], ## # Margin Left # @see https://tailwindcss.com/docs/margin ## "ml" => [{ "ml" => SCALE_MARGIN.call }], ## # Space Between X # @see https://tailwindcss.com/docs/margin#adding-space-between-children ## "space-x" => [{ "space-x" => SCALE_UNAMBIGUOUS_SPACING.call }], ## # Space Between X Reverse # @see https://tailwindcss.com/docs/margin#adding-space-between-children ## "space-x-reverse" => ["space-x-reverse"], ## # Space Between Y # @see https://tailwindcss.com/docs/margin#adding-space-between-children ## "space-y" => [{ "space-y" => SCALE_UNAMBIGUOUS_SPACING.call }], ## # Space Between Y Reverse # @see https://tailwindcss.com/docs/margin#adding-space-between-children ## "space-y-reverse" => ["space-y-reverse"], ########## # Sizing ########## ## # Size # @see https://tailwindcss.com/docs/width#setting-both-width-and-height ## "size" => [{ "size" => SCALE_SIZING.call }], # Width # @see https://tailwindcss.com/docs/width ## "w" => [{ "w" => [ THEME_CONTAINER, "screen", *SCALE_SIZING.call, ], }], ## # Min-Width # @see https://tailwindcss.com/docs/min-width ## "min-w" => [{ "min-w" => [ THEME_CONTAINER, "screen", # Deprecated. @see https://github.com/tailwindlabs/tailwindcss.com/issues/2027#issuecomment-2620152757 ## "none", *SCALE_SIZING.call, ], }], ## # Max-Width # @see https://tailwindcss.com/docs/max-width ## "max-w" => [ { "max-w" => [ THEME_CONTAINER, "screen", "none", # Deprecated since Tailwind CSS v4.0.0. @see https://github.com/tailwindlabs/tailwindcss.com/issues/2027#issuecomment-2620152757 ## "prose", # Deprecated since Tailwind CSS v4.0.0. @see https://github.com/tailwindlabs/tailwindcss.com/issues/2027#issuecomment-2620152757 ## { "screen" => [THEME_BREAKPOINT] }, *SCALE_SIZING.call, ], }, ], ## # Height # @see https://tailwindcss.com/docs/height ## "h" => [{ "h" => ["screen", "lh", *SCALE_SIZING.call] }], ## # Min-Height # @see https://tailwindcss.com/docs/min-height ## "min-h" => [{ "min-h" => ["screen", "none", "lh", *SCALE_SIZING.call] }], ## # Max-Height # @see https://tailwindcss.com/docs/max-height ## "max-h" => [{ "max-h" => ["screen", "lh", *SCALE_SIZING.call] }], ############ # Typography ############ # Font Size # @see https://tailwindcss.com/docs/font-size ## "font-size" => [{ "text" => ["base", THEME_TEXT, IS_ARBITRARY_VARIABLE_LENGTH, IS_ARBITRARY_LENGTH] }], ## # Font Smoothing # @see https://tailwindcss.com/docs/font-smoothing ## "font-smoothing" => ["antialiased", "subpixel-antialiased"], ## # Font Style # @see https://tailwindcss.com/docs/font-style ## "font-style" => ["italic", "not-italic"], ## # Font Weight # @see https://tailwindcss.com/docs/font-weight ## "font-weight" => [ { "font" => [ THEME_FONT_WEIGHT, IS_ARBITRARY_VARIABLE, IS_ARBITRARY_NUMBER, ], }, ], ## # Font Stretch # @see https://tailwindcss.com/docs/font-stretch ## "font-stretch" => [ { "font-stretch" => [ "ultra-condensed", "extra-condensed", "condensed", "semi-condensed", "normal", "semi-expanded", "expanded", "extra-expanded", "ultra-expanded", IS_PERCENT, IS_ARBITRARY_VALUE, ], }, ], ## # Font Family # @see https://tailwindcss.com/docs/font-family ## "font-family" => [{ "font" => [IS_ARBITRARY_VARIABLE_FAMILY_NAME, IS_ARBITRARY_VALUE, THEME_FONT] }], ## # Font Variant Numeric # @see https://tailwindcss.com/docs/font-variant-numeric ## "fvn-normal" => ["normal-nums"], ## # Font Variant Numeric # @see https://tailwindcss.com/docs/font-variant-numeric ## "fvn-ordinal" => ["ordinal"], ## # Font Variant Numeric # @see https://tailwindcss.com/docs/font-variant-numeric ## "fvn-slashed-zero" => ["slashed-zero"], ## # Font Variant Numeric # @see https://tailwindcss.com/docs/font-variant-numeric ## "fvn-figure" => ["lining-nums", "oldstyle-nums"], ## # Font Variant Numeric # @see https://tailwindcss.com/docs/font-variant-numeric ## "fvn-spacing" => ["proportional-nums", "tabular-nums"], ## # Font Variant Numeric # @see https://tailwindcss.com/docs/font-variant-numeric ## "fvn-fraction" => ["diagonal-fractions", "stacked-fractions"], ## # Letter Spacing # @see https://tailwindcss.com/docs/letter-spacing ## "tracking" => [ { "tracking" => [THEME_TRACKING, IS_ARBITRARY_VARIABLE, IS_ARBITRARY_VALUE], }, ], # # Line Clamp # @see https://tailwindcss.com/docs/line-clamp # "line-clamp" => [{ "line-clamp" => [IS_NUMBER, "none", IS_ARBITRARY_VARIABLE, IS_ARBITRARY_NUMBER] }], ## # Line Height # @see https://tailwindcss.com/docs/line-height ## "leading" => [ { "leading" => [ # Deprecated since Tailwind CSS v4.0.0. @see https://github.com/tailwindlabs/tailwindcss.com/issues/2027#issuecomment-2620152757 ## THEME_LEADING, *SCALE_UNAMBIGUOUS_SPACING.call, ], }, ], # # List Style Image # @see https://tailwindcss.com/docs/list-style-image # "list-image" => [{ "list-image" => ["none", IS_ARBITRARY_VARIABLE, IS_ARBITRARY_VALUE] }], # List Style Position # @see https://tailwindcss.com/docs/list-style-position ## "list-style-position" => [{ "list" => ["inside", "outside"] }], ## # List Style Type # @see https://tailwindcss.com/docs/list-style-type ## "list-style-type" => [{ "list" => ["disc", "decimal", "none", IS_ARBITRARY_VARIABLE, IS_ARBITRARY_VALUE] }], ## # Text Alignment # @see https://tailwindcss.com/docs/text-align ## "text-alignment" => [{ "text" => ["left", "center", "right", "justify", "start", "end"] }], ## # Placeholder Color # @deprecated since Tailwind CSS v3.0.0 # @see https://tailwindcss.com/docs/placeholder-color ## "placeholder-color" => [{ "placeholder" => SCALE_COLOR.call }], ## # Text Color # @see https://tailwindcss.com/docs/text-color ## "text-color" => [{ "text" => SCALE_COLOR.call }], ## # Text Decoration # @see https://tailwindcss.com/docs/text-decoration ## "text-decoration" => ["underline", "overline", "line-through", "no-underline"], ## # Text Decoration Style # @see https://tailwindcss.com/docs/text-decoration-style ## "text-decoration-style" => [{ "decoration" => [*SCALE_LINE_STYLE.call, "wavy"] }], ## # Text Decoration Thickness # @see https://tailwindcss.com/docs/text-decoration-thickness ## "text-decoration-thickness" => [{ "decoration" => [IS_NUMBER, "from-font", "auto", IS_ARBITRARY_VARIABLE, IS_ARBITRARY_LENGTH] }], ## # Text Decoration Color # @see https://tailwindcss.com/docs/text-decoration-color ## "text-decoration-color" => [{ "decoration" => SCALE_COLOR.call }], ## # Text Underline Offset # @see https://tailwindcss.com/docs/text-underline-offset ## "underline-offset" => [{ "underline-offset" => [IS_NUMBER, "auto", IS_ARBITRARY_VARIABLE, IS_ARBITRARY_VALUE] }], ## # Text Transform # @see https://tailwindcss.com/docs/text-transform ## "text-transform" => ["uppercase", "lowercase", "capitalize", "normal-case"], ## # Text Overflow # @see https://tailwindcss.com/docs/text-overflow ## "text-overflow" => ["truncate", "text-ellipsis", "text-clip"], ## # Text Wrap # @see https://tailwindcss.com/docs/text-wrap ## "text-wrap" => [{ "text" => ["wrap", "nowrap", "balance", "pretty"] }], ## # Text Indent # @see https://tailwindcss.com/docs/text-indent ## "indent" => [{ "indent" => SCALE_UNAMBIGUOUS_SPACING.call }], ## # Vertical Alignment # @see https://tailwindcss.com/docs/vertical-align ## "vertical-align" => [ { "align" => [ "baseline", "top", "middle", "bottom", "text-top", "text-bottom", "sub", "super", IS_ARBITRARY_VARIABLE, IS_ARBITRARY_VALUE, ], }, ], ## # Whitespace # @see https://tailwindcss.com/docs/whitespace ## "whitespace" => [{ "whitespace" => ["normal", "nowrap", "pre", "pre-line", "pre-wrap", "break-spaces"] }], ## # Word Break # @see https://tailwindcss.com/docs/word-break ## "break" => [{ "break" => ["normal", "words", "all", "keep"] }], ## # Overflow Wrap # @see https://tailwindcss.com/docs/overflow-wrap ## "wrap" => [{ "wrap" => ["break-word", "anywhere", "normal"] }], # # Hyphens # @see https://tailwindcss.com/docs/hyphens # "hyphens" => [{ "hyphens" => ["none", "manual", "auto"] }], ## # Content # @see https://tailwindcss.com/docs/content ## "content" => [{ "content" => ["none", IS_ARBITRARY_VARIABLE, IS_ARBITRARY_VALUE] }], ############# # Backgrounds ############# # Background Attachment # @see https://tailwindcss.com/docs/background-attachment ## "bg-attachment" => [{ "bg" => ["fixed", "local", "scroll"] }], ## # Background Clip # @see https://tailwindcss.com/docs/background-clip ## "bg-clip" => [{ "bg-clip" => ["border", "padding", "content", "text"] }], ## # Background Origin
ruby
MIT
83ef21d415234e01c1f7188d64f37ebaec9c21ea
2026-01-04T17:44:23.457574Z
true
gjtorikian/tailwind_merge
https://github.com/gjtorikian/tailwind_merge/blob/83ef21d415234e01c1f7188d64f37ebaec9c21ea/lib/tailwind_merge/parse_class_name.rb
lib/tailwind_merge/parse_class_name.rb
# frozen_string_literal: true module TailwindMerge class TailwindClass < Struct.new(:is_external, :modifiers, :has_important_modifier, :base_class_name, :maybe_postfix_modifier_position) end module ParseClassName IMPORTANT_MODIFIER = "!" MODIFIER_SEPARATOR = ":" MODIFIER_SEPARATOR_LENGTH = MODIFIER_SEPARATOR.length ## # Parse class name into parts. # # Inspired by `splitAtTopLevelOnly` used in Tailwind CSS # @see https://github.com/tailwindlabs/tailwindcss/blob/v3.2.2/src/util/splitAtTopLevelOnly.js def parse_class_name(class_name, prefix: nil) unless prefix.nil? full_prefix = "#{prefix}#{MODIFIER_SEPARATOR}" if class_name.start_with?(full_prefix) return parse_class_name(class_name[full_prefix.length..]) else return TailwindClass.new( is_external: true, modifiers: [], has_important_modifier: false, base_class_name: class_name, maybe_postfix_modifier_position: nil, ) end end modifiers = [] bracket_depth = 0 paren_depth = 0 modifier_start = 0 postfix_modifier_position = nil class_name.each_char.with_index do |char, index| if bracket_depth.zero? && paren_depth.zero? if char == MODIFIER_SEPARATOR modifiers << class_name[modifier_start...index] modifier_start = index + MODIFIER_SEPARATOR_LENGTH next elsif char == "/" postfix_modifier_position = index next end end bracket_depth += 1 if char == "[" bracket_depth -= 1 if char == "]" paren_depth += 1 if char == "(" paren_depth -= 1 if char == ")" end base_class_name_with_important_modifier = modifiers.empty? ? class_name : class_name[modifier_start..] base_class_name, has_important_modifier = strip_important_modifier(base_class_name_with_important_modifier) maybe_postfix_modifier_position = if postfix_modifier_position && postfix_modifier_position > modifier_start postfix_modifier_position - modifier_start end TailwindClass.new( is_external: false, modifiers:, has_important_modifier:, base_class_name: base_class_name, maybe_postfix_modifier_position:, ) end def strip_important_modifier(base_class_name) if base_class_name.end_with?(IMPORTANT_MODIFIER) return [base_class_name[0...-IMPORTANT_MODIFIER.length], true] end # In Tailwind CSS v3 the important modifier was at the start of the base class name. This is still supported for legacy reasons. # @see https://github.com/dcastil/tailwind-merge/issues/513#issuecomment-2614029864 if base_class_name.start_with?(IMPORTANT_MODIFIER) return [base_class_name[1..], true] end [base_class_name, false] end end end
ruby
MIT
83ef21d415234e01c1f7188d64f37ebaec9c21ea
2026-01-04T17:44:23.457574Z
false
gjtorikian/tailwind_merge
https://github.com/gjtorikian/tailwind_merge/blob/83ef21d415234e01c1f7188d64f37ebaec9c21ea/lib/tailwind_merge/class_group_utils.rb
lib/tailwind_merge/class_group_utils.rb
# frozen_string_literal: true module TailwindMerge class ClassGroupUtils attr_reader :class_map CLASS_PART_SEPARATOR = "-" ARBITRARY_PROPERTY_REGEX = /^\[(.+)\]$/ def initialize(config) @config = config @class_map = create_class_map(config) end def class_group_id(class_name) class_parts = class_name.split(CLASS_PART_SEPARATOR) # Classes like `-inset-1` produce an empty string as first class_part. # Assume that classes for negative values are used correctly and remove it from class_parts. class_parts.shift if class_parts.first == "" && class_parts.length != 1 get_group_recursive(class_parts, @class_map) || get_group_id_for_arbitrary_property(class_name) end def get_group_recursive(class_parts, class_part_object) return class_part_object[:class_group_id] if class_parts.empty? current_class_part = class_parts.first next_class_part_object = class_part_object[:next_part][current_class_part] if next_class_part_object class_group_from_next_class_part = get_group_recursive(class_parts.drop(1), next_class_part_object) return class_group_from_next_class_part if class_group_from_next_class_part end return if class_part_object[:validators].empty? class_rest = class_parts.join(CLASS_PART_SEPARATOR) result = class_part_object[:validators].find do |v| validator = v[:validator] from_theme?(validator) ? validator.call(@config) : validator.call(class_rest) end result&.fetch(:class_group_id, nil) end def get_conflicting_class_group_ids(class_group_id, has_postfix_modifier) conflicts = @config[:conflicting_class_groups][class_group_id] || [] if has_postfix_modifier && @config[:conflicting_class_group_modifiers][class_group_id] return [*conflicts, *@config[:conflicting_class_group_modifiers][class_group_id]] end conflicts end private def create_class_map(config) theme = config[:theme] class_groups = config[:class_groups] class_map = { next_part: {}, validators: [], } class_groups.each do |(class_group_id, class_group)| process_classes_recursively(class_group, class_map, class_group_id, theme) end class_map end private def process_classes_recursively(class_group, class_part_object, class_group_id, theme) class_group.each do |class_definition| if class_definition.is_a?(String) class_part_object_to_edit = class_definition.empty? ? class_part_object : get_class_part(class_part_object, class_definition) class_part_object_to_edit[:class_group_id] = class_group_id elsif class_definition.is_a?(Proc) if from_theme?(class_definition) process_classes_recursively(class_definition.call(@config), class_part_object, class_group_id, theme) else class_part_object[:validators] << { validator: class_definition, class_group_id: class_group_id, } end else class_definition.each do |key, nested_class_group| process_classes_recursively( nested_class_group, get_class_part(class_part_object, key), class_group_id, theme, ) end end end end private def get_class_part(class_part_object, path) current_class_part_object = class_part_object path.to_s.split(CLASS_PART_SEPARATOR).each do |path_part| unless current_class_part_object[:next_part].key?(path_part) current_class_part_object[:next_part][path_part] = { next_part: {}, validators: [], } end current_class_part_object = current_class_part_object[:next_part][path_part] end current_class_part_object end private def get_group_id_for_arbitrary_property(class_name) match = ARBITRARY_PROPERTY_REGEX.match(class_name) return unless match property = match[1].to_s.split(":", 2).first # Use two dots here because one dot is used as prefix for class groups in plugins "arbitrary..#{property}" if property && !property.empty? end private def from_theme?(validator) TailwindMerge::Config::VALID_THEME_IDS.include?(validator.object_id) end end end
ruby
MIT
83ef21d415234e01c1f7188d64f37ebaec9c21ea
2026-01-04T17:44:23.457574Z
false
gjtorikian/tailwind_merge
https://github.com/gjtorikian/tailwind_merge/blob/83ef21d415234e01c1f7188d64f37ebaec9c21ea/lib/tailwind_merge/validators.rb
lib/tailwind_merge/validators.rb
# frozen_string_literal: true require "set" module TailwindMerge module Validators class << self def arbitrary_value?(class_part, test_label, test_value) match = ARBITRARY_VALUE_REGEX.match(class_part) return false unless match return test_label.call(match[1]) unless match[1].nil? test_value.call(match[2]) end def arbitrary_variable?(class_part, test_label, should_match_no_label: false) match = ARBITRARY_VARIABLE_REGEX.match(class_part) return false unless match return test_label.call(match[1]) unless match[1].nil? should_match_no_label end def numeric?(x) Float(x, exception: false).is_a?(Numeric) end def integer?(x) Integer(x, exception: false).is_a?(Integer) end end ARBITRARY_VALUE_REGEX = /^\[(?:(\w[\w-]*):)?(.+)\]$/i ARBITRARY_VARIABLE_REGEX = /^\((?:(\w[\w-]*):)?(.+)\)$/i FRACTION_REGEX = %r{^\d+/\d+$} TSHIRT_UNIT_REGEX = /^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/ LENGTH_UNIT_REGEX = /\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/ COLOR_FUNCTION_REGEX = /^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/ # Shadow always begins with x and y offset separated by underscore optionally prepended by inset SHADOW_REGEX = /^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/ IMAGE_REGEX = /^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/ IS_FRACTION = ->(value) { FRACTION_REGEX.match?(value) } IS_NUMBER = ->(value) { numeric?(value) } IS_INTEGER = ->(value) { integer?(value) } IS_PERCENT = ->(value) { value.end_with?("%") && IS_NUMBER.call(value[0..-2]) } IS_TSHIRT_SIZE = ->(value) { TSHIRT_UNIT_REGEX.match?(value) } IS_ANY = ->(_ = nil) { true } IS_LENGTH_ONLY = ->(value) { # `colorFunctionRegex` check is necessary because color functions can have percentages in them which which would be incorrectly classified as lengths. # For example, `hsl(0 0% 0%)` would be classified as a length without this check. # I could also use lookbehind assertion in `lengthUnitRegex` but that isn't supported widely enough. LENGTH_UNIT_REGEX.match?(value) && !COLOR_FUNCTION_REGEX.match?(value) } IS_NEVER = ->(_) { false } IS_SHADOW = ->(value) { SHADOW_REGEX.match?(value) } IS_IMAGE = ->(value) { IMAGE_REGEX.match?(value) } IS_ANY_NON_ARBITRARY = ->(value) { !IS_ARBITRARY_VALUE.call(value) && !IS_ARBITRARY_VARIABLE.call(value) } IS_ARBITRARY_SIZE = ->(value) { arbitrary_value?(value, IS_LABEL_SIZE, IS_NEVER) } IS_ARBITRARY_VALUE = ->(value) { ARBITRARY_VALUE_REGEX.match(value) } IS_ARBITRARY_LENGTH = ->(value) { arbitrary_value?(value, IS_LABEL_LENGTH, IS_LENGTH_ONLY) } IS_ARBITRARY_NUMBER = ->(value) { arbitrary_value?(value, IS_LABEL_NUMBER, IS_NUMBER) } IS_ARBITRARY_POSITION = ->(value) { arbitrary_value?(value, IS_LABEL_POSITION, IS_NEVER) } IS_ARBITRARY_IMAGE = ->(value) { arbitrary_value?(value, IS_LABEL_IMAGE, IS_IMAGE) } IS_ARBITRARY_SHADOW = ->(value) { arbitrary_value?(value, IS_LABEL_SHADOW, IS_SHADOW) } IS_ARBITRARY_VARIABLE = ->(value) { ARBITRARY_VARIABLE_REGEX.match(value) } IS_ARBITRARY_VARIABLE_LENGTH = ->(value) { arbitrary_variable?(value, IS_LABEL_LENGTH) } IS_ARBITRARY_VARIABLE_FAMILY_NAME = ->(value) { arbitrary_variable?(value, IS_LABEL_FAMILY_NAME) } IS_ARBITRARY_VARIABLE_POSITION = ->(value) { arbitrary_variable?(value, IS_LABEL_POSITION) } IS_ARBITRARY_VARIABLE_SIZE = ->(value) { arbitrary_variable?(value, IS_LABEL_SIZE) } IS_ARBITRARY_VARIABLE_IMAGE = ->(value) { arbitrary_variable?(value, IS_LABEL_IMAGE) } IS_ARBITRARY_VARIABLE_SHADOW = ->(value) { arbitrary_variable?(value, IS_LABEL_SHADOW, should_match_no_label: true) } ############ # Labels ############ IS_LABEL_POSITION = ->(label) { label == "position" || label == "percentage" } IS_LABEL_IMAGE = ->(label) { label == "image" || label == "url" } IS_LABEL_SIZE = ->(label) { label == "length" || label == "size" || label == "bg-size" } IS_LABEL_LENGTH = ->(label) { label == "length" } IS_LABEL_NUMBER = ->(label) { label == "number" } IS_LABEL_FAMILY_NAME = ->(label) { label == "family-name" } IS_LABEL_SHADOW = ->(label) { label == "shadow" } end end
ruby
MIT
83ef21d415234e01c1f7188d64f37ebaec9c21ea
2026-01-04T17:44:23.457574Z
false
damog/feedbag
https://github.com/damog/feedbag/blob/19101d3b8f7e12a0abddaf47339be9e2c080be56/benchmark/rfeedfinder_benchmark.rb
benchmark/rfeedfinder_benchmark.rb
require "benchmark" require "rubygems" sites = [ "log.damog.net", "http://cnn.com", "scripting.com", "mx.planetalinux.org", "http://feedproxy.google.com/UniversoPlanetaLinux", ] Benchmark.bm do |x| sites.each do |site| puts "#{site}:" puts " feedbag" x.report { require 'feedbag' Feedbag.find(site) } puts " rfeedfinder" x.report { require 'rfeedfinder' Rfeedfinder.feed(site) } end end
ruby
MIT
19101d3b8f7e12a0abddaf47339be9e2c080be56
2026-01-04T17:44:28.137218Z
false
damog/feedbag
https://github.com/damog/feedbag/blob/19101d3b8f7e12a0abddaf47339be9e2c080be56/rails/init.rb
rails/init.rb
require File.join File.dirname(__FILE__), "..", "lib", "feedbag"
ruby
MIT
19101d3b8f7e12a0abddaf47339be9e2c080be56
2026-01-04T17:44:28.137218Z
false
damog/feedbag
https://github.com/damog/feedbag/blob/19101d3b8f7e12a0abddaf47339be9e2c080be56/test/logger_test.rb
test/logger_test.rb
#!/usr/bin/env ruby # frozen_string_literal: true # Test for configurable logger (Issue #33) require_relative 'test_helper' require 'stringio' require 'logger' class LoggerTest < Test::Unit::TestCase def setup # Reset logger to default before each test Feedbag.logger = nil end def teardown # Reset logger after each test Feedbag.logger = nil end def test_default_logger_exists assert_not_nil Feedbag.logger assert_kind_of Logger, Feedbag.logger end def test_default_logger_writes_to_stderr output = StringIO.new Feedbag.logger = Logger.new(output) Feedbag.logger.formatter = proc { |severity, _datetime, _progname, msg| "#{msg}\n" } Feedbag.logger.error "test message" assert_match(/test message/, output.string) end def test_custom_logger_can_be_set custom_logger = Logger.new(StringIO.new) Feedbag.logger = custom_logger assert_equal custom_logger, Feedbag.logger end def test_logger_can_be_silenced null_output = StringIO.new Feedbag.logger = Logger.new(null_output) Feedbag.logger.level = Logger::FATAL # Only log fatal errors Feedbag.logger.error "this should not appear" assert_equal "", null_output.string end def test_errors_go_to_custom_logger output = StringIO.new custom_logger = Logger.new(output) custom_logger.formatter = proc { |severity, _datetime, _progname, msg| "#{msg}\n" } Feedbag.logger = custom_logger # Try to find feeds on a non-existent domain # This should log an error Feedbag.find("http://this-domain-does-not-exist-feedbag-test.invalid/feed") # Check that something was logged assert output.string.length > 0, "Expected error to be logged" assert_match(/error occurred with/i, output.string) end def test_errors_can_be_captured captured_messages = [] # Create a custom logger that captures messages custom_logger = Logger.new(StringIO.new) custom_logger.formatter = proc do |severity, _datetime, _progname, msg| captured_messages << msg "" end Feedbag.logger = custom_logger # Trigger an error Feedbag.find("http://this-domain-does-not-exist-feedbag-test.invalid/feed") assert captured_messages.length > 0, "Expected to capture error messages" end def test_logger_works_with_timeout_errors output = StringIO.new custom_logger = Logger.new(output) custom_logger.formatter = proc { |severity, _datetime, _progname, msg| "#{msg}\n" } Feedbag.logger = custom_logger # The error handling should work regardless of error type # Just verify the logger is being used assert_respond_to Feedbag.logger, :error assert_respond_to Feedbag.logger, :warn assert_respond_to Feedbag.logger, :info end def test_logger_reset_to_default custom_logger = Logger.new(StringIO.new) Feedbag.logger = custom_logger assert_equal custom_logger, Feedbag.logger # Reset to default Feedbag.logger = nil # Should get a new default logger assert_not_equal custom_logger, Feedbag.logger assert_kind_of Logger, Feedbag.logger end # Simulate Rails.logger compatibility def test_rails_logger_compatibility # Rails.logger is just a Logger instance, so any Logger should work rails_like_logger = Logger.new(StringIO.new) rails_like_logger.progname = "Rails" Feedbag.logger = rails_like_logger assert_equal rails_like_logger, Feedbag.logger assert_nothing_raised do Feedbag.logger.error "test" Feedbag.logger.warn "test" Feedbag.logger.info "test" Feedbag.logger.debug "test" end end end
ruby
MIT
19101d3b8f7e12a0abddaf47339be9e2c080be56
2026-01-04T17:44:28.137218Z
false
damog/feedbag
https://github.com/damog/feedbag/blob/19101d3b8f7e12a0abddaf47339be9e2c080be56/test/normalize_url_test.rb
test/normalize_url_test.rb
#!/usr/bin/env ruby # frozen_string_literal: true # Test for non-ASCII URL support (Issue #29) require_relative 'test_helper' class NormalizeUrlTest < Test::Unit::TestCase def test_normalize_chinese_characters_in_url_path url = "https://www.rehabsociety.org.hk/zh-hant/主頁/feed/" normalized = Feedbag.normalize_url(url) # Should start with the expected domain assert_match(/^https:\/\/www\.rehabsociety\.org\.hk\/zh-hant\//, normalized) # Should be percent-encoded (主頁 becomes %E4%B8%BB%E9%A0%81) assert_match(/%E4%B8%BB%E9%A0%81/, normalized) # Original non-ASCII characters should be gone refute_match(/主頁/, normalized) end def test_normalize_japanese_characters_in_url_path url = "https://www.example.jp/日本語/rss.xml" normalized = Feedbag.normalize_url(url) assert_match(/^https:\/\/www\.example\.jp\//, normalized) # Should not contain original Japanese characters refute_match(/日本語/, normalized) # Should contain percent-encoded version assert normalized.include?('%'), "URL should contain percent-encoded characters" end def test_normalize_hebrew_characters_in_url_path url = "https://www.example.co.il/עברית/feed/" normalized = Feedbag.normalize_url(url) assert_match(/^https:\/\/www\.example\.co\.il\//, normalized) # Should be percent-encoded refute_match(/עברית/, normalized) end def test_normalize_cyrillic_characters_in_url_path url = "https://www.example.ru/Русский/feed.xml" normalized = Feedbag.normalize_url(url) assert_match(/^https:\/\/www\.example\.ru\//, normalized) refute_match(/Русский/, normalized) end def test_normalize_arabic_characters_in_url_path url = "https://www.example.com/العربية/rss/" normalized = Feedbag.normalize_url(url) assert_match(/^https:\/\/www\.example\.com\//, normalized) refute_match(/العربية/, normalized) end def test_handle_already_ascii_urls_without_modification url = "https://www.example.com/feed/rss.xml" normalized = Feedbag.normalize_url(url) assert_equal url, normalized end def test_handle_already_encoded_urls # Already percent-encoded URL url = "https://www.example.com/path%20with%20spaces/feed.xml" normalized = Feedbag.normalize_url(url) # Should remain valid assert_match(/^https:\/\/www\.example\.com\//, normalized) end def test_handle_empty_url assert_equal "", Feedbag.normalize_url("") end def test_handle_nil_url assert_nil Feedbag.normalize_url(nil) end def test_handle_urls_with_query_parameters_containing_non_ascii url = "https://www.example.com/search?q=日本語&category=テスト" normalized = Feedbag.normalize_url(url) assert_match(/^https:\/\/www\.example\.com\/search\?/, normalized) # Query params should be encoded refute_match(/日本語/, normalized) refute_match(/テスト/, normalized) end def test_handle_urls_with_non_ascii_fragment url = "https://www.example.com/page#セクション" normalized = Feedbag.normalize_url(url) assert_match(/^https:\/\/www\.example\.com\/page/, normalized) end def test_normalized_url_is_valid_for_uri_parse urls = [ "https://www.rehabsociety.org.hk/zh-hant/主頁/feed/", "https://www.example.jp/日本語/rss.xml", "https://www.example.co.il/עברית/feed/", "https://www.example.ru/Русский/feed.xml" ] urls.each do |url| normalized = Feedbag.normalize_url(url) # Should not raise URI::InvalidURIError assert_nothing_raised("URI.parse should work on normalized URL: #{url}") do URI.parse(normalized) end end end def test_find_does_not_raise_on_non_ascii_url # This test verifies that Feedbag.find doesn't raise URI::InvalidURIError # for non-ASCII URLs (the main issue #29) non_ascii_url = "https://www.rehabsociety.org.hk/zh-hant/主頁/feed/" # It should not raise an exception - just return empty or result assert_nothing_raised("Feedbag.find should not raise on non-ASCII URL") do # This will likely fail to connect, but should not raise URI::InvalidURIError begin Feedbag.find(non_ascii_url) rescue SocketError, Timeout::Error, OpenURI::HTTPError # These are expected for fake URLs end end end def test_feed_question_does_not_raise_on_non_ascii_url non_ascii_url = "https://www.example.org/中文/feed.rss" assert_nothing_raised("Feedbag.feed? should not raise on non-ASCII URL") do begin Feedbag.feed?(non_ascii_url) rescue SocketError, Timeout::Error, OpenURI::HTTPError # These are expected for fake URLs end end end end
ruby
MIT
19101d3b8f7e12a0abddaf47339be9e2c080be56
2026-01-04T17:44:28.137218Z
false
damog/feedbag
https://github.com/damog/feedbag/blob/19101d3b8f7e12a0abddaf47339be9e2c080be56/test/test_helper.rb
test/test_helper.rb
require 'rubygems' require 'test/unit' $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) $LOAD_PATH.unshift(File.dirname(__FILE__)) require 'feedbag' # Optional test dependencies - only loaded if available begin require 'shoulda' rescue LoadError # shoulda not available end begin require 'mocha/setup' rescue LoadError # mocha not available end begin require 'webmock/test_unit' WebMock.allow_net_connect! rescue LoadError # webmock not available end
ruby
MIT
19101d3b8f7e12a0abddaf47339be9e2c080be56
2026-01-04T17:44:28.137218Z
false
damog/feedbag
https://github.com/damog/feedbag/blob/19101d3b8f7e12a0abddaf47339be9e2c080be56/test/feedbag_test.rb
test/feedbag_test.rb
require 'test_helper' class FeedbagTest < Test::Unit::TestCase context "Feedbag.feed? should know that an RSS url is a feed" do setup do @rss_url = 'http://example.com/rss/' Feedbag.stubs(:find).with(@rss_url).returns([@rss_url]) end should "return true" do assert Feedbag.feed?(@rss_url) end end context "Feedbag.feed? should know that an RSS url with parameters is a feed" do setup do @rss_url = "http://example.com/data?format=rss" Feedbag.stubs(:find).with(@rss_url).returns([@rss_url]) end should "return true" do assert Feedbag.feed?(@rss_url) end end context "Feedbag find should discover feeds from direct feed URLs" do should "recognize a direct feed URL" do src = 'test/testcases/json1.html' feed_url = 'http://example.com/feed' stub_request(:any, "example.com/feed").to_return( body: '', status: 200, headers: {"Content-Type" => 'application/rss+xml'} ) result = Feedbag.find(feed_url) assert_equal [feed_url], result end end context "Feedbag#looks_like_feed? should assume that url with proper extension is a feed" do setup do @feeds = ['http://feeds.bbci.co.uk/news/rss.xml', 'http://feeds.bbci.co.uk/news/rss.rdf', 'http://feeds.bbci.co.uk/news/rss.rss', 'http://feeds.bbci.co.uk/news/rss.xml?edition=int'] end should "return true" do @feeds.each do |url| assert Feedbag.new.looks_like_feed?(url) end end end context "Feedbag find should discover JSON Feeds" do should "find json feed" do src = 'test/testcases/json1.html' stub_request(:any, "example3.com").to_return(body: File.new(src), status: 200, headers: {"Content-Type" => 'text/html'}) result = Feedbag.find('http://example3.com') assert result.include?('https://blog.booko.com.au/feed/json/') assert result.include?('https://blog.booko.com.au/feed/') assert result.include?('https://blog.booko.com.au/comments/feed/') end end context "Feedbag should follow redirects" do should "follow redirects" do src = 'test/testcases/json1.html' stub_request(:any, "example1.com").to_return(status: 301, headers: {"Location" => "//example2.com", "Content-Type" => "text/html"}) stub_request(:any, "example2.com").to_return(body: File.new(src), status: 200, headers: {"Content-Type" => 'text/html'}) result = Feedbag.find('http://example1.com') assert result.include?('https://blog.booko.com.au/feed/json/') end end context "Feedbag should send the correct User Agent" do should "send correct user agent" do src = 'test/testcases/json1.html' default_user_agent = "Feedbag/#{Feedbag::VERSION}" stub_request(:any, "example3.com").with(headers:{ 'User-Agent' => "Feedbag/#{Feedbag::VERSION}" }).to_return(body: File.new(src), status: 200, headers: {"Content-Type" => 'text/html'}) # This request does match the stub with the default User-Agent and should return a result result = Feedbag.find('http://example3.com') assert result.include?('https://blog.booko.com.au/feed/json/') # This request does not match the stub using the custom User-Agent result = Feedbag.find('http://example3.com', 'User-Agent' => "My Personal Agent/1.0.1") assert result.empty? stub_request(:any, "example4.com").with(headers:{ 'User-Agent' => "My Personal Agent/1.0.1" }).to_return(body: File.new(src), status: 200, headers: {"Content-Type" => 'text/html'}) # This request does not match the stub using the default User-Agent result = Feedbag.find('http://example4.com') assert result.empty? # This request does match the stub with a custom User-Agent and should return a result result = Feedbag.find('http://example4.com', 'User-Agent' => "My Personal Agent/1.0.1") assert result.include?('https://blog.booko.com.au/feed/json/') end end #context "Feedbag should pass other options to open-uri" do # should "pass options to open-uri" do # end #end context "Feedbag should be able to find URLs with ampersands and plus signs" do setup do @feed = 'https://link.springer.com/search.rss?facet-content-type=Article&amp;facet-journal-id=41116&amp;channel-name=Living+Reviews+in+Solar+Physics' end should "return true" do assert Feedbag.new.looks_like_feed?(@feed) end end end
ruby
MIT
19101d3b8f7e12a0abddaf47339be9e2c080be56
2026-01-04T17:44:28.137218Z
false
damog/feedbag
https://github.com/damog/feedbag/blob/19101d3b8f7e12a0abddaf47339be9e2c080be56/lib/feedbag.rb
lib/feedbag.rb
#!/usr/bin/ruby # See COPYING before using this software. require "rubygems" require "nokogiri" require "open-uri" require "net/http" require "logger" require_relative "feedbag/version" begin require "addressable/uri" rescue LoadError # addressable will be loaded after bundle install end class Feedbag # Configurable logger for error output # Default writes to $stderr. Can be set to Rails.logger or any Logger-compatible object. # # @example Silence all output # Feedbag.logger = Logger.new('/dev/null') # # @example Use Rails logger # Feedbag.logger = Rails.logger # class << self attr_writer :logger def logger @logger ||= default_logger end private def default_logger logger = Logger.new($stderr) logger.formatter = proc { |severity, _datetime, _progname, msg| "#{msg}\n" } logger end end CONTENT_TYPES = [ 'application/x.atom+xml', 'application/atom+xml', 'application/xml', 'text/xml', 'application/rss+xml', 'application/rdf+xml', 'application/json', 'application/feed+json' ].freeze def self.feed?(url) new.feed?(url) end def self.find(url, options = {}) new(options: options).find(url, options) end def initialize(options: nil) @feeds = [] @options = options || {} @options["User-Agent"] ||= "Feedbag/#{VERSION}" end # Normalize a URL to handle non-ASCII characters (IRIs) # This converts internationalized URLs to valid ASCII URIs def self.normalize_url(url) return url if url.nil? || url.empty? if defined?(Addressable::URI) Addressable::URI.parse(url).normalize.to_s else url end rescue Addressable::URI::InvalidURIError url end def feed?(url) # Normalize URL to handle non-ASCII characters normalized_url = Feedbag.normalize_url(url) url_uri = URI.parse(normalized_url) url = "#{url_uri.scheme or 'http'}://#{url_uri.host}#{url_uri.path}" url << "?#{url_uri.query}" if url_uri.query # hack: url.sub!(/^feed:\/\//, 'http://') res = Feedbag.find(url) if res.size == 1 and res.first == url return true else return false end end def find(url, options = {}) # Normalize URL to handle non-ASCII characters normalized_url = Feedbag.normalize_url(url) url_uri = URI.parse(normalized_url) url = nil if url_uri.scheme.nil? url = "http://#{url_uri.to_s}" elsif url_uri.scheme == "feed" return self.add_feed(url_uri.to_s.sub(/^feed:\/\//, 'http://'), nil) else url = url_uri.to_s end #url = "#{url_uri.scheme or 'http'}://#{url_uri.host}#{url_uri.path}" # check if feed_valid is avail begin require "feed_validator" v = W3C::FeedValidator.new v.validate_url(url) return self.add_feed(url, nil) if v.valid? rescue LoadError # scoo rescue REXML::ParseException # usually indicates timeout # TODO: actually find out timeout. use Terminator? # $stderr.puts "Feed looked like feed but might not have passed validation or timed out" rescue => ex Feedbag.logger.error "#{ex.class} error occurred with: `#{url}': #{ex.message}" end begin html = URI.open(url, @options) do |f| content_type = f.content_type.downcase if content_type == "application/octet-stream" # open failed content_type = f.meta["content-type"].gsub(/;.*$/, '') end if CONTENT_TYPES.include?(content_type) return self.add_feed(url, nil) end doc = Nokogiri::HTML(f.read) if doc.at("base") and doc.at("base")["href"] @base_uri = doc.at("base")["href"] else @base_uri = nil end # first with links (doc/"atom:link").each do |l| next unless l["rel"] && l["href"].present? if l["type"] and CONTENT_TYPES.include?(l["type"].downcase.strip) and l["rel"].downcase == "self" self.add_feed(l["href"], url, @base_uri) end end doc.xpath("//link[@rel='alternate' or @rel='service.feed'][@href][@type]").each do |l| if CONTENT_TYPES.include?(l['type'].downcase.strip) self.add_feed(l["href"], url, @base_uri) end end doc.xpath("//link[@rel='alternate' and @type='application/json'][@href]").each do |e| self.add_feed(e['href'], url, @base_uri) if self.looks_like_feed?(e['href']) end (doc/"a").each do |a| next unless a["href"] if self.looks_like_feed?(a["href"]) and (a["href"] =~ /\// or a["href"] =~ /#{url_uri.host}/) self.add_feed(a["href"], url, @base_uri) end end (doc/"a").each do |a| next unless a["href"] if self.looks_like_feed?(a["href"]) self.add_feed(a["href"], url, @base_uri) end end # Added support for feeds like http://tabtimes.com/tbfeed/mashable/full.xml if url.match(/.xml$/) and doc.root and doc.root["xml:base"] and doc.root["xml:base"].strip == url.strip self.add_feed(url, nil) end end rescue Timeout::Error => err Feedbag.logger.error "Timeout error occurred with `#{url}: #{err}'" rescue OpenURI::HTTPError => the_error Feedbag.logger.error "Error occurred with `#{url}': #{the_error}" rescue SocketError => err Feedbag.logger.error "Socket error occurred with: `#{url}': #{err}" rescue => ex Feedbag.logger.error "#{ex.class} error occurred with: `#{url}': #{ex.message}" ensure return @feeds end end def looks_like_feed?(url) if url =~ /(\.(rdf|xml|rss)(\?([\w'\-%]?(=[\w'\-%.]*)?(&|#|\+|\;)?)+)?(:[\w'\-%]+)?$|feed=(rss|atom)|(atom|feed)\/?$)/i true else false end end def add_feed(feed_url, orig_url, base_uri = nil) # puts "#{feed_url} - #{orig_url}" url = feed_url.sub(/^feed:/, '').strip # Normalize URL to handle non-ASCII characters url = Feedbag.normalize_url(url) if base_uri # url = base_uri + feed_url normalized_base = Feedbag.normalize_url(base_uri) url = URI.parse(normalized_base).merge(url).to_s end begin uri = URI.parse(url) rescue => ex Feedbag.logger.error "Error parsing URL `#{url}': #{ex.message}" return end unless uri.absolute? normalized_orig = Feedbag.normalize_url(orig_url) orig = URI.parse(normalized_orig) url = orig.merge(url).to_s end # verify url is really valid @feeds.push(url) unless @feeds.include?(url)# if self._is_http_valid(URI.parse(url), orig_url) end # not used. yet. def _is_http_valid(uri, orig_url) req = Net::HTTP.get_response(uri) orig_uri = URI.parse(orig_url) case req when Net::HTTPSuccess then return true else return false end end end if __FILE__ == $0 if ARGV.size == 0 puts 'usage: feedbag url' else puts Feedbag.find ARGV.first end end
ruby
MIT
19101d3b8f7e12a0abddaf47339be9e2c080be56
2026-01-04T17:44:28.137218Z
false
damog/feedbag
https://github.com/damog/feedbag/blob/19101d3b8f7e12a0abddaf47339be9e2c080be56/lib/feedbag/version.rb
lib/feedbag/version.rb
# frozen_string_literal: true class Feedbag VERSION = '1.0.2' end
ruby
MIT
19101d3b8f7e12a0abddaf47339be9e2c080be56
2026-01-04T17:44:28.137218Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/spec/circuitry_spec.rb
spec/circuitry_spec.rb
require 'spec_helper' RSpec.describe Circuitry, type: :model do subject { described_class } shared_examples_for 'a configuration method' do |method| it 'returns a configuration object' do expect(subject.send(method)).to be_a Circuitry::Config::SharedSettings end it 'always returns the same object' do expect(subject.send(method)).to be subject.send(method) end it 'accepts a block' do expect { subject.send(method) { |c| c.access_key = 'foo' } }.to change { subject.send(method).access_key }.to('foo') end end describe '.subscriber_config' do it_behaves_like 'a configuration method', :subscriber_config end describe '.publisher_config' do it_behaves_like 'a configuration method', :publisher_config end describe '.publish' do it 'delegates to a new publisher' do publisher = double('Publisher', publish: true) topic = 'topic-name' object = double('Object') options = { foo: 'bar' } allow(Circuitry::Publisher).to receive(:new).with(options).and_return(publisher) subject.publish(topic, object, options) expect(publisher).to have_received(:publish).with(topic, object) end end describe '.subscribe' do let(:subscriber) { double('Subscriber', subscribe: true) } let(:queue) { 'https://sqs.amazon.com/account/queue' } let(:options) { { foo: 'bar' } } before do allow(Circuitry::Subscriber).to receive(:new).with(options).and_return(subscriber) allow(Circuitry::Provisioning::QueueCreator).to receive(:find_or_create).and_return(double('Queue', url: queue)) end it 'delegates to a new subscriber' do block = -> {} subject.subscribe(options, &block) expect(subscriber).to have_received(:subscribe).with(no_args, &block) end end describe '.flush' do it 'flushes batches' do expect(Circuitry::Processors::Batcher).to receive(:flush) subject.flush end it 'flushes forks' do expect(Circuitry::Processors::Forker).to receive(:flush) subject.flush end it 'flushes threads' do expect(Circuitry::Processors::Threader).to receive(:flush) subject.flush end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/spec/spec_helper.rb
spec/spec_helper.rb
require 'simplecov' SimpleCov.start $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'circuitry' require 'circuitry/cli' require 'circuitry/config/file_loader' require 'rspec/its' require 'redis' require 'mock_redis' require 'dalli' require 'memcache_mock' require 'connection_pool' require 'pry-byebug' require 'securerandom' # Requires supporting ruby files with custom matchers and macros, etc, in # spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are # run as spec files by default. This means that files in spec/support that end # in _spec.rb will both be required and run as specs, causing the specs to be # run twice. It is recommended that you do not name files matching this glob to # end with _spec.rb. You can configure this pattern with the --pattern # option on the command line or in ~/.rspec, .rspec or `.rspec-local`. # # The following line is provided for convenience purposes. It has the downside # of increasing the boot-up time by auto-requiring all files in the support # directory. Alternatively, in the individual `*_spec.rb` files, manually # require only the support files necessary. Dir[File.expand_path('spec/fixtures/**/*.rb')].each { |f| require f } Dir[File.expand_path('spec/support/**/*.rb')].each { |f| require f } RSpec.configure do |config| # rspec-expectations config goes here. You can use an alternate # assertion/expectation library such as wrong or the stdlib/minitest # assertions if you prefer. config.expect_with :rspec do |expectations| # This option will default to `true` in RSpec 4. It makes the `description` # and `failure_message` of custom matchers include text for helper methods # defined using `chain`, e.g.: # be_bigger_than(2).and_smaller_than(4).description # # => "be bigger than 2 and smaller than 4" # ...rather than: # # => "be bigger than 2" expectations.include_chain_clauses_in_custom_matcher_descriptions = true end # rspec-mocks config goes here. You can use an alternate test double # library (such as bogus or mocha) by changing the `mock_with` option here. config.mock_with :rspec do |mocks| # Prevents you from mocking or stubbing a method that does not exist on # a real object. This is generally recommended, and will default to # `true` in RSpec 4. mocks.verify_partial_doubles = true end # These two settings work together to allow you to limit a spec run # to individual examples or groups you care about by tagging them with # `:focus` metadata. When nothing is tagged with `:focus`, all examples # get run. config.filter_run_including focus: true config.run_all_when_everything_filtered = true # Limits the available syntax to the non-monkey patched syntax that is # recommended. For more details, see: # - http://myronmars.to/n/dev-blog/2012/06/rspecs-new-expectation-syntax # - http://teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ # - http://myronmars.to/n/dev-blog/2014/05/notable-changes-in-rspec-3#new__config_option_to_disable_rspeccore_monkey_patching config.disable_monkey_patching! # Many RSpec users commonly either run the entire suite or an individual # file, and it's useful to allow more verbose output when running an # individual spec file. if config.files_to_run.one? # Use the documentation formatter for detailed output, # unless a formatter has already been configured # (e.g. via a command-line flag). config.default_formatter = 'doc' end # Print the 10 slowest examples and example groups at the # end of the spec run, to help surface which specs are running # particularly slow. config.profile_examples = 10 # Run specs in random order to surface order dependencies. If you find an # order dependency and want to debug it, you can fix the order by providing # the seed, which is printed after each run. # --seed 1234 config.order = :random # Seed global randomization in this process using the `--seed` CLI option. # Setting this allows you to use `--seed` to deterministically reproduce # test failures related to randomization by passing the same `--seed` value # as the one that triggered the failure. Kernel.srand config.seed end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/spec/support/examples/async_processor_examples.rb
spec/support/examples/async_processor_examples.rb
RSpec.shared_examples_for 'an asyncronous processor' do context 'when on_async_exit is defined' do let(:block) { -> {} } let(:on_async_exit) { double('Proc', call: true) } before do allow(subject).to receive(:fork) { |&block| block.call } allow(Process).to receive(:detach) allow(Circuitry.subscriber_config).to receive(:on_async_exit).and_return(on_async_exit) end it 'calls the proc' do subject.process(&block) subject.flush expect(on_async_exit).to have_received(:call) end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/spec/support/examples/lock_examples.rb
spec/support/examples/lock_examples.rb
RSpec.shared_examples_for 'a lock' do it { is_expected.to be_a Circuitry::Locks::Base } describe '#soft_lock' do let(:id) { SecureRandom.hex(100) } let(:now) { Time.now } before do allow(Time).to receive(:now).and_return(now) end describe 'when the id is not locked' do it 'returns true' do expect(subject.soft_lock(id)).to be true end it 'locks the message id for the soft ttl duration' do subject.soft_lock(id) allow(Time).to receive(:now).and_return(now + soft_ttl - 1) expect(subject.soft_lock(id)).to be false end it 'unlocks the message id after the soft ttl duration' do subject.soft_lock(id) allow(Time).to receive(:now).and_return(now + soft_ttl) expect(subject.soft_lock(id)).to be true end end describe 'when the id is locked' do before do subject.soft_lock(id) end it 'returns false' do expect(subject.soft_lock(id)).to be false end it 'does not change the existing lock' do allow(Time).to receive(:now).and_return(now + soft_ttl - 1) expect(subject.soft_lock(id)).to be false allow(Time).to receive(:now).and_return(now + soft_ttl) expect(subject.soft_lock(id)).to be true end end end describe '#hard_lock' do let(:id) { SecureRandom.hex(100) } let(:now) { Time.now } before do allow(Time).to receive(:now).and_return(now) end shared_examples_for 'an overwriting lock' do it 'locks the message id for the hard ttl duration' do subject.hard_lock(id) allow(Time).to receive(:now).and_return(now + hard_ttl - 1) expect { allow(Time).to receive(:now).and_return(now + hard_ttl) }.to change { subject.soft_lock(id) }.from(false).to(true) end end describe 'when the id is not locked' do it_behaves_like 'an overwriting lock' end describe 'when the id is locked' do before { subject.soft_lock(id) } it_behaves_like 'an overwriting lock' end end describe '#lock' do let(:id) { SecureRandom.hex(100) } before do subject.hard_lock(id) end it 'deletes the lock' do subject.unlock(id) expect(subject.soft_lock(id)).to be true end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/spec/support/examples/settings_examples.rb
spec/support/examples/settings_examples.rb
RSpec.shared_examples_for 'a validated setting' do |permitted_values, setting_name| def set(value) subject.public_send(:"#{setting}=", value) end def get subject.public_send(setting) end let(:setting) { setting_name } permitted_values.each do |value| describe "with valid value #{value}" do it 'does not raise an error' do expect { set(value) }.to_not raise_error end it 'changes the config value' do set(value) expect(get).to eq value end end end describe 'with invalid value' do it 'raises an error' do expect { set(:fake) }.to raise_error Circuitry::ConfigError end it 'does not change the config value' do expect { set(:fake) rescue nil }.to_not change { get } end end end RSpec.shared_examples_for 'middleware settings' do it 'returns a middleware chain' do expect(subject.middleware).to be_a Circuitry::Middleware::Chain end it 'yields block' do called = false block = ->(_chain) { called = true } expect { subject.middleware(&block) }.to change { called }.to(true) end it 'preserves the middleware chain' do subject.middleware do |chain| chain.add TestMiddleware end expect(subject.middleware.exists?(TestMiddleware)).to be true end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/spec/fixtures/test_middleware.rb
spec/fixtures/test_middleware.rb
class TestMiddleware attr_accessor :log def initialize(log: []) self.log = log end def call(*args) log << 'before' log.concat(args) yield ensure log << 'after' end end class TestMiddleware2 < TestMiddleware end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/spec/circuitry/message_spec.rb
spec/circuitry/message_spec.rb
require 'spec_helper' RSpec.describe Circuitry::Message, type: :model do subject { described_class.new(sqs_message) } let(:sqs_message) { double(message_id: id, receipt_handle: handle, body: context.to_json) } let(:id) { '123' } let(:handle) { '456' } let(:body) { 'foo' } let(:arn) { 'arn:aws:sns:us-east-1:123456789012:test-event-task-changed' } let(:context) { { 'Message' => body.to_json, 'TopicArn' => arn } } its(:sqs_message) { is_expected.to eq sqs_message } its(:id) { is_expected.to eq id } its(:context) { is_expected.to eq context } its(:body) { is_expected.to eq body } its(:topic) { is_expected.to eq Circuitry::Topic.new(arn) } its(:receipt_handle) { is_expected.to eq handle } end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/spec/circuitry/processor_spec.rb
spec/circuitry/processor_spec.rb
require 'spec_helper' processor_class = Class.new do include Circuitry::Processor def process(&block) block.call end def flush pool.clear end end incomplete_processor_class = Class.new do include Circuitry::Processor end RSpec.describe Circuitry::Processor, type: :model do subject { processor_class.new } describe '.process' do let(:block) { ->{ } } describe 'when the class has defined process' do it 'raises an error' do expect { subject.process(&block) }.to_not raise_error end end describe 'when the class has not defined process' do subject { incomplete_processor_class.new } it 'raises an error' do expect { subject.process(&block) }.to raise_error(NotImplementedError) end end end describe '.safely_process' do def process subject.send(:safely_process, &block) end describe 'when the block raises an error' do let(:block) { ->{ raise StandardError } } before do allow(Circuitry.subscriber_config.logger).to receive(:error) end it 'does not re-raise the error' do expect { process }.to_not raise_error end it 'logs an error' do process expect(Circuitry.subscriber_config.logger).to have_received(:error) end describe 'when an error handler is defined' do let(:error_handler) { double('Proc', call: true) } before do allow(Circuitry.subscriber_config).to receive(:error_handler).and_return(error_handler) end it 'handles the error' do process expect(Circuitry.subscriber_config.error_handler).to have_received(:call) end end describe 'when an error handler is not defined' do let(:error_handler) { nil } before do allow_message_expectations_on_nil allow(Circuitry.subscriber_config).to receive(:error_handler).and_return(error_handler) allow(error_handler).to receive(:call) end it 'does not handle the error' do process expect(Circuitry.subscriber_config.error_handler).to_not have_received(:call) end end end describe 'when the block does not raise an error' do let(:block) { ->{ } } it 'does not log an error' do expect(Circuitry.subscriber_config.logger).to_not receive(:error) process end it 'does not handle an error' do allow_message_expectations_on_nil expect(Circuitry.subscriber_config.error_handler).to_not receive(:call) process end end end describe '#flush' do describe 'when the class has defined flush' do it 'does not raise an error' do expect { subject.flush }.to_not raise_error end end describe 'when the class has not defined flush' do subject { incomplete_processor_class.new } it 'raises an error' do expect { subject.flush }.to raise_error(NotImplementedError) end end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/spec/circuitry/queue_spec.rb
spec/circuitry/queue_spec.rb
require 'spec_helper' RSpec.describe Circuitry::Queue, type: :model do subject { described_class.new(url) } let(:url) { 'https://sqs.amazontest.com/123/queue_name' } describe '.find' do subject { described_class } before do allow_any_instance_of(Circuitry::Queue::Finder).to receive(:find).and_return(double('Queue', queue_url: url)) end it 'returns a queue object' do expect(subject.find('queue_name')).to be_instance_of(Circuitry::Queue) end end describe '#name' do it 'returns last segment of url' do expect(subject.name).to eql('queue_name') end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/spec/circuitry/cli_spec.rb
spec/circuitry/cli_spec.rb
require 'spec_helper' RSpec.describe Circuitry::CLI do subject { described_class } describe '#provision' do before do allow(Circuitry::Provisioning::QueueCreator).to receive(:find_or_create).and_return(queue) allow(Circuitry::Provisioning::TopicCreator).to receive(:find_or_create).and_return(topic) allow(Circuitry::Provisioning::SubscriptionCreator).to receive(:subscribe_all).and_return(true) subject.start(command.split) end let(:queue) { Circuitry::Queue.new('http://sqs.amazontest.com/example') } let(:topic) { Circuitry::Topic.new('arn:aws:sns:us-east-1:123456789012:some-topic-name') } describe 'vanilla command' do let(:command) { 'provision example -t topic1 topic2 -a 123 -s 123 -r us-east-1 -n 7' } it 'creates primary and dead letter queues' do expect(Circuitry::Provisioning::QueueCreator).to have_received(:find_or_create).once.with('example', hash_including(dead_letter_queue_name: 'example-failures')) end it 'creates each topic' do expect(Circuitry::Provisioning::TopicCreator).to have_received(:find_or_create).twice end it 'subscribes to all topics' do expect(Circuitry::Provisioning::SubscriptionCreator).to have_received(:subscribe_all).once.with(queue, [topic, topic]) end it 'configures max_receive_count' do expect(Circuitry.subscriber_config.max_receive_count).to eql(7) end end describe 'no queue given' do let(:command) { 'provision' } it 'does nothing' do expect(Circuitry::Provisioning::QueueCreator).to_not have_received(:find_or_create) end end describe 'no topics given' do let(:command) { 'provision example' } it 'does not create queue' do expect(Circuitry::Provisioning::QueueCreator).to_not have_received(:find_or_create) end it 'does not create topics' do expect(Circuitry::Provisioning::TopicCreator).to_not have_received(:find_or_create) end end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/spec/circuitry/subscriber_spec.rb
spec/circuitry/subscriber_spec.rb
require 'spec_helper' RSpec.describe Circuitry::Subscriber, type: :model do subject { described_class.new(options) } let(:queue) { 'https://sqs.amazon.com/account/queue' } let(:options) { {} } it { is_expected.to be_a Circuitry::Concerns::Async } before do allow(Circuitry::Queue).to receive(:find).and_return(double('Queue', url: queue)) end describe '.new' do subject { described_class } describe 'when lock' do subject { described_class } let(:options) { { lock: lock } } shared_examples_for 'a valid lock strategy' do |lock_class| it 'does not raise an error' do expect { subject.new(options) }.to_not raise_error end it 'sets the lock strategy' do subscriber = subject.new(options) expect(subscriber.lock).to be_a lock_class end end describe 'is true' do let(:lock) { true } it_behaves_like 'a valid lock strategy', Circuitry::Locks::Memory end describe 'is false' do let(:lock) { false } it_behaves_like 'a valid lock strategy', Circuitry::Locks::NOOP end describe 'is a specific strategy' do let(:lock) { Circuitry::Locks::Redis.new(client: MockRedis.new) } it_behaves_like 'a valid lock strategy', Circuitry::Locks::Redis end describe 'is invalid' do let(:lock) { 'invalid' } it 'raises an error' do expect { subject.new(options) }.to raise_error(ArgumentError) end end end end describe '#subscribe' do before do Circuitry::Locks::Memory.store.clear end describe 'when a block is not given' do it 'raises an error' do expect { subject.subscribe(queue) }.to raise_error(ArgumentError) end end describe 'when a block is given' do let(:block) { ->(_, _) { } } let(:logger) { double('Logger', info: nil, warn: nil, error: nil) } let(:mock_sqs) { double('Aws::SQS::Client', delete_message: true) } let(:mock_poller) { double('Aws::SQS::QueuePoller', before_request: true) } let(:messages) { [] } before do allow(Circuitry.subscriber_config).to receive(:logger).and_return(logger) allow(logger).to receive(:debug) allow(subject).to receive(:sqs).and_return(mock_sqs) allow(Aws::SQS::QueuePoller).to receive(:new).with(queue, client: mock_sqs).and_return(mock_poller) allow(mock_poller).to receive(:poll) do |&block| block.call(messages) end end describe 'when AWS credentials are set' do before do allow(Circuitry.subscriber_config).to receive(:aws_options).and_return(access_key_id: 'key', secret_access_key: 'secret', region: 'region') end it 'subscribes to SQS' do subject.subscribe(&block) expect(mock_poller).to have_received(:poll) end describe 'when a connection error is raised' do before do allow(subject).to receive(:process_messages).and_raise(error) end let(:error) { described_class::CONNECTION_ERRORS.first.new(double('Seahorse::Client::RequestContext'), 'Queue does not exist') } it 'raises a wrapped error' do expect { subject.subscribe(&block) }.to raise_error(Circuitry::SubscribeError) end it 'logs an error' do subject.subscribe(&block) rescue nil expect(logger).to have_received(:error) end end shared_examples_for 'a valid subscribe request' do describe 'when the batch_size is 1 and messages is not an Array' do let(:messages) do double('Aws::SQS::Types::Message', message_id: 'one', receipt_handle: 'delete-one', body: { 'Message' => 'Foo'.to_json, 'TopicArn' => 'arn:aws:sns:us-east-1:123456789012:test-event-task-changed' }.to_json) end let(:options) { { batch_size: 1 } } it 'processes the message' do expect(block).to receive(:call).with('Foo', 'test-event-task-changed') subject.subscribe(&block) end it 'deletes the message' do subject.subscribe(&block) expect(mock_sqs).to have_received(:delete_message).with(queue_url: queue, receipt_handle: 'delete-one') end end describe 'when the batch_size is greater than 1' do let(:messages) do [ double('Aws::SQS::Types::Message', message_id: 'one', receipt_handle: 'delete-one', body: { 'Message' => 'Foo'.to_json, 'TopicArn' => 'arn:aws:sns:us-east-1:123456789012:test-event-task-changed' }.to_json), double('Aws::SQS::Types::Message', message_id: 'two', receipt_handle: 'delete-two', body: { 'Message' => 'Bar'.to_json, 'TopicArn' => 'arn:aws:sns:us-east-1:123456789012:test-event-comment' }.to_json), ] end it 'processes each message' do expect(block).to receive(:call).with('Foo', 'test-event-task-changed') expect(block).to receive(:call).with('Bar', 'test-event-comment') subject.subscribe(&block) end it 'deletes each message' do subject.subscribe(&block) expect(mock_sqs).to have_received(:delete_message).with(queue_url: queue, receipt_handle: 'delete-one') expect(mock_sqs).to have_received(:delete_message).with(queue_url: queue, receipt_handle: 'delete-two') end describe 'when a duplicate message is received' do let(:options) { { async: async, lock: lock } } let(:messages) do 2.times.map do double('Aws::SQS::Types::Message', message_id: 'one', receipt_handle: 'delete-one', body: { 'Message' => 'Foo'.to_json, 'TopicArn' => 'arn:aws:sns:us-east-1:123456789012:test-event-task-changed' }.to_json) end end describe 'when locking is disabled' do let(:lock) { false } it 'processes the duplicate' do expect(block).to receive(:call).with('Foo', 'test-event-task-changed').twice subject.subscribe(&block) end it 'deletes each message' do subject.subscribe(&block) expect(mock_sqs).to have_received(:delete_message).with(queue_url: queue, receipt_handle: 'delete-one').twice end end describe 'when locking is enabled' do let(:lock) { true } it 'does not process the duplicate' do expect(block).to receive(:call).with('Foo', 'test-event-task-changed').once subject.subscribe(&block) end it 'deletes each message' do subject.subscribe(&block) expect(mock_sqs).to have_received(:delete_message).with(queue_url: queue, receipt_handle: 'delete-one').once end end end describe 'when processing fails' do let(:block) { ->(message, topic) { raise error if message == 'Foo' } } let(:error) { StandardError.new('test error') } it 'does not raise the error' do expect { subject.subscribe(&block) }.to_not raise_error end it 'logs error for failing messages' do subject.subscribe(&block) expect(logger).to have_received(:error).with('Error handling message one: test error') end it 'does not log error for successful messages' do subject.subscribe(&block) expect(logger).to_not have_received(:error).with('Error handling message two: test error') end it 'deletes successful messages' do subject.subscribe(&block) expect(mock_sqs).to have_received(:delete_message).with(queue_url: queue, receipt_handle: 'delete-two') end it 'does not delete failing messages' do subject.subscribe(&block) expect(mock_sqs).to_not have_received(:delete_message).with(queue_url: queue, receipt_handle: 'delete-one') end it 'unlocks failing messages' do expect(subject.lock).to receive(:unlock).with('one') subject.subscribe(&block) end describe 'when error logger is configured' do let(:error_handler) { ->(_) { } } before do allow(subject).to receive(:error_handler).and_return(error_handler) end it 'calls error handler' do expect(error_handler).to receive(:call).with(error) subject.subscribe(&block) end end end end end describe 'synchronously' do let(:async) { false } let(:options) { { async: async } } it 'does not process asynchronously' do expect(subject).to_not receive(:process_asynchronously) subject.subscribe(&block) end it_behaves_like 'a valid subscribe request' end describe 'asynchronously' do before do allow(subject).to receive(:process_asynchronously) { |&block| block.call } end let(:async) { true } let(:options) { { async: async } } let(:messages) do [ double('Aws::SQS::Types::Message', message_id: 'one', receipt_handle: 'delete-one', body: { 'Message' => 'Foo'.to_json, 'TopicArn' => 'arn:aws:sns:us-east-1:123456789012:test-event-task-changed' }.to_json), double('Aws::SQS::Types::Message', message_id: 'two', receipt_handle: 'delete-two', body: { 'Message' => 'Bar'.to_json, 'TopicArn' => 'arn:aws:sns:us-east-1:123456789012:test-event-comment' }.to_json), ] end it 'processes asynchronously' do subject.subscribe(&block) expect(subject).to have_received(:process_asynchronously).twice end it_behaves_like 'a valid subscribe request' end end describe 'when AWS credentials are not set' do before do allow(Circuitry.subscriber_config).to receive(:aws_options).and_return(access_key_id: '', secret_access_key: '', region: 'region') end it 'does not subscribe to SNS' do subject.subscribe(&block) rescue nil expect(mock_poller).to_not have_received(:poll) end it 'raises an error' do expect { subject.subscribe(&block) }.to raise_error(Circuitry::SubscribeError) end end end end describe '#queue' do it 'returns the initializer value' do expect(subject.queue).to eq queue end end describe '#wait_time' do let(:options) { { wait_time: 123 } } it 'returns the initializer value' do expect(subject.wait_time).to eq 123 end end describe '#batch_size' do let(:options) { { batch_size: 321 } } it 'returns the initializer value' do expect(subject.batch_size).to eq 321 end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/spec/circuitry/topic_spec.rb
spec/circuitry/topic_spec.rb
require 'spec_helper' RSpec.describe Circuitry::Topic, type: :model do subject { described_class.new(arn) } let(:arn) { 'arn:aws:sqs:us-east-1:123456789012:some-topic-name' } describe '.find' do subject { described_class } before do allow_any_instance_of(Circuitry::Topic::Finder).to receive(:find).and_return(double('Topic', topic_arn: arn)) end it 'returns a queue object' do expect(subject.find('queue_name')).to be_instance_of(Circuitry::Topic) end end describe '#arn' do it 'returns the ARN' do expect(subject.arn).to eq arn end end describe '#name' do it 'returns the last section of the ARN' do expect(subject.name).to eq 'some-topic-name' end end describe '#==' do it 'returns true for two equal topics' do expect(subject).to eq subject.dup end it 'returns false for unequal topics' do other_object = described_class.new(arn.reverse) expect(subject).to_not eq other_object end it 'returns false for different objects with the same ARN' do other_class = Struct.new(:arn) expect(subject).to_not eq other_class.new(arn) end end describe '#hash' do it 'returns true for two equal topics' do expect(subject.hash).to eq subject.dup.hash end it 'returns false for unequal topics' do other_object = described_class.new(arn.reverse) expect(subject.hash).to_not eq other_object.hash end it 'returns false for different objects with the same ARN' do other_class = Struct.new(:arn) expect(subject.hash).to_not eq other_class.new(arn).hash end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/spec/circuitry/provisioning_spec.rb
spec/circuitry/provisioning_spec.rb
require 'spec_helper' RSpec.describe Circuitry::Provisioning do subject { described_class } describe '.provision' do before do allow(Circuitry::Provisioning::Provisioner).to receive(:new).with(logger).and_return(provisioner) end let(:logger) { double('Logger') } let(:provisioner) { double('Provisioning::Provisioner', run: true) } it 'delegates to provisioner' do subject.provision(logger: logger) expect(provisioner).to have_received(:run) end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/spec/circuitry/publisher_spec.rb
spec/circuitry/publisher_spec.rb
require 'spec_helper' RSpec.describe Circuitry::Publisher, type: :model do subject { described_class.new(options) } let(:options) { {} } it { is_expected.to be_a Circuitry::Concerns::Async } describe '#publish' do describe 'when topic name is not set' do let(:topic_name) { nil } let(:object) { double('Object') } it 'raises an error' do expect { subject.publish(topic_name, object) }.to raise_error(ArgumentError) end end describe 'when object is not set' do let(:topic_name) { 'topic' } let(:object) { nil } it 'raises an error' do expect { subject.publish(topic_name, object) }.to raise_error(ArgumentError) end end describe 'when topic name and object are set' do let(:topic_name) { 'topic' } let(:object) { double('Object', to_json: '{"foo":"bar"}') } let(:topic) { double('Topic', arn: 'arn:aws:sns:us-east-1:123456789012:some-topic-name') } let(:logger) { double('Logger', info: nil, warn: nil, error: nil) } let(:mock_sns) { double('SNS', publish: true) } before do allow(Circuitry.publisher_config).to receive(:logger).and_return(logger) allow(Circuitry::Topic).to receive(:find).with(topic_name).and_return(topic) allow(subject).to receive(:sns).and_return(mock_sns) end describe 'when AWS credentials are set' do before do allow(Circuitry.publisher_config).to receive(:aws_options).and_return(access_key_id: 'key', secret_access_key: 'secret', region: 'region') allow(logger).to receive(:debug) end shared_examples_for 'a valid publish request' do it 'publishes to SNS' do subject.publish(topic_name, object) expect(mock_sns).to have_received(:publish).with(topic_arn: topic.arn, message: object.to_json) end describe 'when a connection error occurs' do let(:error) { Seahorse::Client::NetworkingError.new(StandardError.new('test error')) } describe 'on the first try' do before do attempts = 0 allow(mock_sns).to receive(:publish) do attempts += 1 raise error if attempts == 1 end end it 'logs a warning' do subject.publish(topic_name, object) expect(logger).to have_received(:warn).with("Error publishing attempt #1: #{error.class} (test error); retrying...") end it 'retries' do subject.publish(topic_name, object) expect(mock_sns).to have_received(:publish).with(topic_arn: topic.arn, message: object.to_json).twice end it 'does not raise the error' do expect { subject.publish(topic_name, object) }.to_not raise_error end end describe 'repeatedly' do before do allow(mock_sns).to receive(:publish).and_raise(error) end it 'logs 2 warnings' do subject.publish(topic_name, object) rescue nil expect(logger).to have_received(:warn).with("Error publishing attempt #1: #{error.class} (test error); retrying...") expect(logger).to have_received(:warn).with("Error publishing attempt #2: #{error.class} (test error); retrying...") end it 'gives up after 3 tries' do subject.publish(topic_name, object) rescue nil expect(mock_sns).to have_received(:publish).with(topic_arn: topic.arn, message: object.to_json).thrice end it 'raises the error' do expect { subject.publish(topic_name, object) }.to raise_error(error.class) end end end describe 'when the message is invalid' do before do mock_error = Aws::SNS::Errors::InvalidParameter.new({}, "Invalid parameter: Message too long") allow(mock_sns).to receive(:publish).and_raise(mock_error) end it 'raises the error' do expect { subject.publish(topic_name, object) }.to raise_error do |ex| expect(ex).to be_a(Circuitry::SnsPublishError) error_message = JSON.parse(ex.message) message = JSON.parse(error_message["message"]) expect(error_message["error"]).to eq("Aws::SNS::Errors::InvalidParameter: Invalid parameter: Message too long") expect(error_message["topic_arn"]).to eq("arn:aws:sns:us-east-1:123456789012:some-topic-name") expect(message).to eq("foo" => "bar") end end end end describe 'synchonously' do let(:options) { { async: false } } it 'does not process asynchronously' do expect(subject).to_not receive(:process_asynchronously) subject.publish(topic_name, object) end it_behaves_like 'a valid publish request' end describe 'asynchronously' do before do allow(subject).to receive(:process_asynchronously) { |&block| block.call } end let(:options) { { async: true } } it 'processes asynchronously' do subject.publish(topic_name, object) expect(subject).to have_received(:process_asynchronously) end it_behaves_like 'a valid publish request' end end describe 'when AWS credentials are not set' do before do allow(Circuitry.publisher_config).to receive(:aws_options).and_return(access_key_id: '', secret_access_key: '', region: 'region') end it 'does not publish to SNS' do subject.publish(topic_name, object) rescue nil expect(mock_sns).to_not have_received(:publish).with(topic_arn: topic.arn, message: object.to_json) end it 'logs a warning' do expect { subject.publish(topic_name, object) }.to raise_error(Circuitry::PublishError) end end end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/spec/circuitry/services/sqs_spec.rb
spec/circuitry/services/sqs_spec.rb
require 'spec_helper' sqs_class = Class.new do include Circuitry::Services::SQS end RSpec.describe sqs_class, type: :model do describe '#sqs' do before do allow(Circuitry.subscriber_config).to receive(:aws_options).and_return(aws_options) end let(:aws_options) { { access_key_id: 'foo', secret_access_key: 'bar', region: 'us-east-1' } } it 'returns an SQS instance' do expect(subject.sqs).to be_an Aws::SQS::Client end it 'uses the AWS configuration options' do expect(Aws::SQS::Client).to receive(:new).with(aws_options) subject.sqs end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/spec/circuitry/services/sns_spec.rb
spec/circuitry/services/sns_spec.rb
require 'spec_helper' sns_class = Class.new do include Circuitry::Services::SNS end RSpec.describe sns_class, type: :model do describe '#sns' do before do allow(Circuitry.publisher_config).to receive(:aws_options).and_return(aws_options) end let(:aws_options) { { access_key_id: 'foo', secret_access_key: 'bar', region: 'us-east-1' } } it 'returns an SNS instance' do expect(subject.sns).to be_an Aws::SNS::Client end it 'uses the AWS configuration options' do expect(Aws::SNS::Client).to receive(:new).with(aws_options) subject.sns end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/spec/circuitry/concerns/async_spec.rb
spec/circuitry/concerns/async_spec.rb
require 'spec_helper' async_class = Class.new do include Circuitry::Concerns::Async def self.default_async_strategy :thread end def self.async_strategies [:fork, :thread, :batch] end end incomplete_async_class = Class.new do include Circuitry::Concerns::Async end RSpec.describe Circuitry::Concerns::Async, type: :model do subject { async_class.new } describe '#async=' do describe 'with an invalid symbol' do it 'raises an error' do expect { subject.async = :foo }.to raise_error(ArgumentError) end end describe 'with a valid symbol' do it 'sets async to the provided symbol' do expect { subject.async = :thread }.to change { subject.async }.to(:thread) end end describe 'with :fork when forking is not supported' do it 'raises an error' do allow(subject).to receive(:platform_supports_forking?).and_return(false) expect { subject.async = :fork }.to raise_error(Circuitry::NotSupportedError) end end describe 'with true' do describe 'when the class has defined a default async strategy' do it 'sets async to the default value' do expect(subject.class).to receive(:default_async_strategy).at_least(:once).and_call_original subject.async = true expect(subject.async).to eq subject.class.default_async_strategy end end describe 'when the class has not defined a default async strategy' do subject { incomplete_async_class.new } it 'raises an error' do expect { subject.async = true }.to raise_error(NotImplementedError) end end end describe 'with false' do it 'sets async to false' do expect { subject.async = false }.to change { subject.async }.to(false) end end end describe '#async?' do describe 'when async is a symbol' do before do subject.async = :thread end it 'returns true' do expect(subject).to be_async end end describe 'when async is false' do before do subject.async = false end it 'returns false' do expect(subject).to_not be_async end end end describe '#process_asynchronously' do let(:block) { ->{ } } describe 'via forking' do before do allow(subject).to receive(:async).and_return(:fork) end it 'delegates to fork processor' do expect(Circuitry::Processors::Forker).to receive(:process).with(no_args, &block) subject.process_asynchronously(&block) end end describe 'via threading' do before do allow(subject).to receive(:async).and_return(:thread) end it 'delegates to thread processor' do expect(Circuitry::Processors::Threader).to receive(:process).with(no_args, &block) subject.process_asynchronously(&block) end end describe 'via batching' do before do allow(subject).to receive(:async).and_return(:batch) end it 'delegates to batch processor' do expect(Circuitry::Processors::Batcher).to receive(:process).with(no_args, &block) subject.process_asynchronously(&block) end end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/spec/circuitry/provisioning/queue_creator_spec.rb
spec/circuitry/provisioning/queue_creator_spec.rb
require 'spec_helper' RSpec.describe Circuitry::Provisioning::QueueCreator, type: :model do describe '.find_or_create' do subject { described_class } before do allow_any_instance_of(subject).to receive(:sqs).and_return(mock_sqs) end let(:queue_url) { 'http://sqs.amazontest.com/howdy' } let(:queue_arn) { 'amazon:test:howdy' } let(:queue_attributes) { OpenStruct.new(attributes: { 'QueueArn' => queue_arn }) } let(:create_queue_response) { OpenStruct.new(queue_url: queue_url) } let(:mock_sqs) { double('SQS', create_queue: create_queue_response, set_queue_attributes: true, get_queue_attributes: queue_attributes) } it 'creates and returns primary queue' do queue = subject.find_or_create('howdy') expect(queue.name).to eql('howdy') end context 'when dead letter queue name option is given' do it 'creates dead letter' do subject.find_or_create('howdy', dead_letter_queue_name: 'howdy-failures') expect(mock_sqs).to have_received(:create_queue).with(hash_including(queue_name: 'howdy-failures')) end it 'sets redrive policy on primary queue' do subject.find_or_create('howdy', dead_letter_queue_name: 'howdy-failures') expect(mock_sqs).to have_received(:set_queue_attributes).with(hash_including(queue_url: queue_url, attributes: { 'RedrivePolicy' => "{\"maxReceiveCount\":\"8\", \"deadLetterTargetArn\":\"#{queue_arn}\"}"})) end end it 'creates queue with visibility timeout' do subject.find_or_create('howdy') expect(mock_sqs).to have_received(:create_queue).with(hash_including(queue_name: 'howdy', attributes: { 'VisibilityTimeout' => '1800' })) end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/spec/circuitry/provisioning/topic_creator_spec.rb
spec/circuitry/provisioning/topic_creator_spec.rb
require 'spec_helper' RSpec.describe Circuitry::Provisioning::TopicCreator, type: :model do describe '.find_or_create' do subject { described_class } let(:topic_name) { 'topic' } let(:topic) { double('Topic') } let(:instance) { double('TopicCreator', topic: topic) } before do allow(subject).to receive(:new).with(topic_name).and_return(instance) end it 'delegates to a new instance' do subject.find_or_create(topic_name) expect(instance).to have_received(:topic) end it 'returns a topic' do expect(subject.find_or_create(topic_name)).to eq topic end end describe '#topic' do subject { described_class.new(topic_name) } let(:topic_name) { 'topic' } let(:mock_sns) { double('SNS') } let(:response) { double('Aws::SNS::Types::CreateTopicResponse', topic_arn: arn) } let(:arn) { 'arn:aws:sns:us-east-1:123456789012:some-topic-name' } before do allow(subject).to receive(:sns).and_return(mock_sns) allow(mock_sns).to receive(:create_topic).with(name: topic_name).and_return(response) end it 'returns the topic' do expect(subject.topic).to be_a Circuitry::Topic end it 'sets the topic ARN' do expect(subject.topic.arn).to eq arn end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/spec/circuitry/provisioning/provisioner_spec.rb
spec/circuitry/provisioning/provisioner_spec.rb
require 'spec_helper' RSpec.describe Circuitry::Provisioning::Provisioner do subject { described_class.new(logger) } let(:logger) { double('Logger', info: nil, fatal: nil) } describe '#run' do let(:queue) { Circuitry::Queue.new('my_queue_name') } let(:topic) { Circuitry::Topic.new('my_topic_arn') } before do Circuitry.subscriber_config.topic_names = %w[my_topic_name1 my_topic_name2] Circuitry.publisher_config.topic_names = %w[my_sub_topic_name] allow(Circuitry::Provisioning::QueueCreator).to receive(:find_or_create).and_return(queue) allow(Circuitry::Provisioning::TopicCreator).to receive(:find_or_create).and_return(topic) allow(Circuitry::Provisioning::SubscriptionCreator).to receive(:subscribe_all).and_return(true) end describe 'when queue name is set' do before do Circuitry.subscriber_config.queue_name = 'my_queue_name' subject.run end it 'creates a queue' do expect(Circuitry::Provisioning::QueueCreator).to have_received(:find_or_create).once.with(Circuitry.subscriber_config.queue_name, dead_letter_queue_name: 'my_queue_name-failures', visibility_timeout: Circuitry.subscriber_config.visibility_timeout, max_receive_count: Circuitry.subscriber_config.max_receive_count ) end it 'creates publisher topics' do expect(Circuitry::Provisioning::TopicCreator).to have_received(:find_or_create).once.with('my_sub_topic_name') end it 'creates subscriber topics' do expect(Circuitry::Provisioning::TopicCreator).to have_received(:find_or_create).once.with('my_topic_name1') expect(Circuitry::Provisioning::TopicCreator).to have_received(:find_or_create).once.with('my_topic_name2') end it 'subscribes subscriber topics to queue' do expect(Circuitry::Provisioning::SubscriptionCreator).to have_received(:subscribe_all).once.with(queue, [topic, topic]) end end describe 'when queue name is not set' do before do Circuitry.subscriber_config.queue_name = nil subject.run end it 'does not create a queue' do expect(Circuitry::Provisioning::QueueCreator).to_not have_received(:find_or_create) end it 'creates publisher topics' do expect(Circuitry::Provisioning::TopicCreator).to have_received(:find_or_create).once.with('my_sub_topic_name') end it 'does not create subscriber topics' do expect(Circuitry::Provisioning::TopicCreator).to_not have_received(:find_or_create).with('my_topic_name1') expect(Circuitry::Provisioning::TopicCreator).to_not have_received(:find_or_create).with('my_topic_name2') end it 'does not subscribe subscriber topics to queue' do expect(Circuitry::Provisioning::SubscriptionCreator).to_not have_received(:subscribe_all) end end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/spec/circuitry/provisioning/subscription_creator_spec.rb
spec/circuitry/provisioning/subscription_creator_spec.rb
require 'json' require 'spec_helper' RSpec::Matchers.define :policy_statement_count do |count| match do |actual| JSON.parse(actual[:attributes]['Policy'])['Statement'].length == count end end RSpec::Matchers.define :policy_statement_arn_condition_count do |statement_position:, count:| match do |actual| statement = JSON.parse(actual[:attributes]['Policy'])['Statement'][statement_position] statement.dig('Condition', 'ForAnyValue:ArnEquals', 'aws:SourceArn').length == count end end RSpec.describe Circuitry::Provisioning::SubscriptionCreator do describe '.subscribe_all' do subject { described_class } before do allow_any_instance_of(subject).to receive(:sqs).and_return(mock_sqs) allow_any_instance_of(subject).to receive(:sns).and_return(mock_sns) allow(queue).to receive(:arn).and_return(queue_arn) end let(:mock_sns) { double('SNS', subscribe: true) } let(:mock_sqs) { double('SQS', set_queue_attributes: true) } let(:topics) { (1..3).map { |index| Circuitry::Topic.new("arn:aws:sns:us-east-1:123456789012:some-topic-name#{index + 1}") } } let(:queue) { Circuitry::Queue.new('http://amazontest.com/howdy') } let(:queue_arn) { 'arn:aws:sqs:us-east-1:123456789012:howdy' } it 'subscribes each topic to the queue' do subject.subscribe_all(queue, topics) expect(mock_sns).to have_received(:subscribe).thrice.with(hash_including(endpoint: queue_arn, protocol: 'sqs')) end it 'sets policy attribute on sqs queue' do subject.subscribe_all(queue, topics) expect(mock_sqs).to have_received(:set_queue_attributes).once.with(policy_statement_count(1)) end it 'sets the policy statement condition on sqs que for topics' do subject.subscribe_all(queue, topics) expect(mock_sqs).to have_received(:set_queue_attributes).once .with(policy_statement_arn_condition_count(statement_position: 0, count: 3)) end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/spec/circuitry/middleware/entry_spec.rb
spec/circuitry/middleware/entry_spec.rb
require 'spec_helper' class TestEntry attr_accessor :value def initialize(value) self.value = value end end RSpec.describe Circuitry::Middleware::Entry do subject { described_class.new(klass, value) } let(:klass) { TestEntry } let(:value) { 'foo' } its(:klass) { is_expected.to be klass } its(:args) { is_expected.to eq [value] } describe '#build' do it 'returns returns an instance with args passed in' do instance = subject.build expect(instance).to be_a TestEntry expect(instance.value).to eq value end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/spec/circuitry/middleware/chain_spec.rb
spec/circuitry/middleware/chain_spec.rb
require 'spec_helper' RSpec.describe Circuitry::Middleware::Chain do def entry subject.detect { |entry| entry.klass == TestMiddleware } end describe '#entries' do it 'returns an array' do expect(subject.entries).to be_an Array end end describe '#add' do def add!(log: []) subject.add TestMiddleware, log: log end before do subject.add TestMiddleware2 end describe 'when the middleware does not exist' do it 'adds an entry' do expect { add! }.to change { subject.entries.size }.by(1) end it 'adds it to the end' do add! expect(entry).to be subject.entries.last end it 'sets the entry properly' do add! expect(entry.klass).to be TestMiddleware expect(entry.args).to eq [log: []] end end describe 'when the middleware exists' do before do add!(log: %w[foo]) end it 'replaces the existing entry' do expect { add! }.to_not change { subject.entries.size } end it 'updates the arguments' do add! expect(subject.entries.last.klass).to be TestMiddleware expect(entry.args).to eq [log: []] end end end describe '#remove' do def remove! subject.remove TestMiddleware end before do subject.add TestMiddleware2 end describe 'when the middleware does not exist' do it 'does not remove an entry' do expect { remove! }.to_not change { subject.entries.size } end end describe 'when the middleware exists' do before do subject.add TestMiddleware end it 'removes an entry' do expect { remove! }.to change { subject.entries.size }.by(-1) end it 'removes the correct entry' do remove! expect(subject.entries.map(&:klass)).to_not include TestMiddleware end end end describe '#prepend' do def prepend!(log: []) subject.prepend TestMiddleware, log: log end before do subject.add TestMiddleware2 end describe 'when the middleware does not exist' do it 'adds an entry' do expect { prepend! }.to change { subject.entries.size }.by(1) end it 'adds it to the beginning' do prepend! expect(entry).to be subject.entries.first end it 'sets the entry properly' do prepend! expect(entry.klass).to be TestMiddleware expect(entry.args).to eq [log: []] end end describe 'when the middleware exists' do before do subject.add TestMiddleware, log: %w[foo] end it 'replaces the existing entry' do expect { prepend! }.to_not change { subject.entries.size } end it 'moves it to the beginning' do prepend! expect(entry).to be subject.entries.first end it 'updates the arguments' do prepend! expect(entry.klass).to be TestMiddleware expect(entry.args).to eq [log: []] end end end describe '#insert_before' do def insert!(log: []) subject.insert_before TestMiddleware2, TestMiddleware, log: log end describe 'when the new middleware does not exist' do shared_examples_for 'an added entry' do it 'adds an entry' do expect { insert! }.to change { subject.entries.size }.by(1) end it 'adds it to the beginning' do insert! expect(entry).to be subject.entries.first end it 'sets the entry properly' do insert! expect(entry.klass).to be TestMiddleware expect(entry.args).to eq [log: []] end end describe 'when the old middleware does not exist' do it_behaves_like 'an added entry' end describe 'when the old middleware exists' do before do subject.add TestMiddleware2 end it_behaves_like 'an added entry' end end describe 'when the new middleware exists' do before do subject.add TestMiddleware, log: %w[foo] end shared_examples_for 'a replaced entry' do it 'replaces the existing entry' do expect { insert! }.to_not change { subject.entries.size } end it 'adds it to the beginning' do insert! expect(entry).to be subject.entries.first end it 'updates the arguments' do insert! expect(entry.klass).to be TestMiddleware expect(entry.args).to eq [log: []] end end describe 'when the old middleware does not exist' do it_behaves_like 'a replaced entry' end describe 'when the old middleware exists' do before do subject.prepend TestMiddleware2 end it_behaves_like 'a replaced entry' end end end describe '#insert_after' do def insert!(log: []) subject.insert_after TestMiddleware2, TestMiddleware, log: log end describe 'when the new middleware does not exist' do shared_examples_for 'an added entry' do it 'adds an entry' do expect { insert! }.to change { subject.entries.size }.by(1) end it 'adds it to the end' do insert! expect(entry).to be subject.entries.last end it 'sets the entry properly' do insert! expect(entry.klass).to be TestMiddleware expect(entry.args).to eq [log: []] end end describe 'when the old middleware does not exist' do it_behaves_like 'an added entry' end describe 'when the old middleware exists' do before do subject.add TestMiddleware2 end it_behaves_like 'an added entry' end end describe 'when the new middleware exists' do before do subject.add TestMiddleware, log: %w[foo] end shared_examples_for 'a replaced entry' do it 'replaces the existing entry' do expect { insert! }.to_not change { subject.entries.size } end it 'adds it to the end' do insert! expect(entry).to be subject.entries.last end it 'updates the arguments' do insert! expect(entry.klass).to be TestMiddleware expect(entry.args).to eq [log: []] end end describe 'when the old middleware does not exist' do it_behaves_like 'a replaced entry' end describe 'when the old middleware exists' do before do subject.add TestMiddleware2 end it_behaves_like 'a replaced entry' end end end describe '#exists?' do describe 'when the middleware does not exist' do it 'returns false' do expect(subject.exists?(TestMiddleware)).to be false end end describe 'when the middleware exists' do before do subject.add TestMiddleware end it 'returns true' do expect(subject.exists?(TestMiddleware)).to be true end end end describe '#build' do let(:chain) { subject.build } before do subject.add TestMiddleware, log: %w[foo] subject.add TestMiddleware2, log: %w[bar] end it 'returns an array of instantiated entries' do expect(chain[0]).to be_a TestMiddleware expect(chain[0].log).to eq %w[foo] expect(chain[1]).to be_a TestMiddleware2 expect(chain[1].log).to eq %w[bar] end end describe '#clear' do before do subject.add TestMiddleware subject.add TestMiddleware2 end it 'removes all entries' do expect { subject.clear }.to change { subject.entries.size }.to(0) end end describe '#invoke' do def invoke! subject.invoke('topic', 'message', &block) end before do subject.add TestMiddleware, log: log1 subject.add TestMiddleware2, log: log2 end let(:log1) { [] } let(:log2) { [] } let(:block) { ->{ processor.process } } let(:processor) { double('Object', process: true) } it 'runs through the first middleware' do expect { invoke! }.to change { log1 }.to(%w[before topic message after]) end it 'runs through the last middleware' do expect { invoke! }.to change { log2 }.to(%w[before topic message after]) end it 'runs the block' do invoke! expect(processor).to have_received(:process) end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/spec/circuitry/locks/noop_spec.rb
spec/circuitry/locks/noop_spec.rb
require 'spec_helper' RSpec.describe Circuitry::Locks::NOOP, type: :model do subject { described_class.new } let(:id) { SecureRandom.hex(100) } describe '#soft_lock' do it 'returns true' do expect(subject.soft_lock(id)).to be true end end describe '#lock!' do it 'returns nil' do expect(subject.hard_lock(id)).to be nil end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/spec/circuitry/locks/redis_spec.rb
spec/circuitry/locks/redis_spec.rb
require 'spec_helper' RSpec.describe Circuitry::Locks::Redis, type: :model do subject { described_class.new(soft_ttl: soft_ttl, hard_ttl: hard_ttl, client: client) } let(:soft_ttl) { 30 } let(:hard_ttl) { 60 } let(:client) { MockRedis.new } before do client.respond_to?(:flushdb) ? client.flushdb : client.with(&:flushdb) end describe 'with redis connection' do it_behaves_like 'a lock' end describe 'with redis connection pool' do let(:client) { ConnectionPool.new(size: 1) { MockRedis.new } } it_behaves_like 'a lock' end describe '.new' do subject { described_class } describe 'when client is provided' do let(:options) { { soft_ttl: soft_ttl, hard_ttl: hard_ttl, client: client } } it 'does not create a new client' do expect(Redis).to_not receive(:new) subject.new(options) end end describe 'when client is not provided' do let(:options) { { soft_ttl: soft_ttl, hard_ttl: hard_ttl } } it 'creates a new client' do expect(Redis).to receive(:new).with(options) subject.new(options) end end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/spec/circuitry/locks/base_spec.rb
spec/circuitry/locks/base_spec.rb
require 'spec_helper' lock_class = Class.new do include Circuitry::Locks::Base def lock(key, ttl) end def lock!(key, ttl) end def unlock!(key) end end incomplete_lock_class = Class.new do include Circuitry::Locks::Base end RSpec.describe Circuitry::Locks::Base, type: :model do subject { lock_class.new } describe '#soft_lock' do let(:id) { SecureRandom.hex(100) } describe 'when the class has defined #lock' do it 'delegates to the #lock method' do expect(subject).to receive(:lock).with("circuitry:lock:#{id}", described_class::DEFAULT_SOFT_TTL) subject.soft_lock(id) end it 'does not raise an error' do expect { subject.soft_lock(id) }.to_not raise_error end end describe 'when the class has not defined #lock' do subject { incomplete_lock_class.new } it 'raises an error' do expect { subject.soft_lock(id) }.to raise_error(NotImplementedError) end end end describe '#hard_lock' do let(:id) { SecureRandom.hex(100) } describe 'when the class has defined #lock!' do it 'delegates to the #lock! method' do expect(subject).to receive(:lock!).with("circuitry:lock:#{id}", described_class::DEFAULT_HARD_TTL) subject.hard_lock(id) end it 'does not raise an error' do expect { subject.hard_lock(id) }.to_not raise_error end end describe 'when the class has not defined #lock!' do subject { incomplete_lock_class.new } it 'raises an error' do expect { subject.hard_lock(id) }.to raise_error(NotImplementedError) end end end describe '#unlock' do let(:id) { SecureRandom.hex(100) } describe 'when the class has defined #unlock!' do it 'delegates to the #unlock method' do expect(subject).to receive(:unlock!).with("circuitry:lock:#{id}") subject.unlock(id) end it 'does not raise an error' do expect { subject.unlock(id) }.to_not raise_error end end describe 'when the class has not defined #unlock!' do subject { incomplete_lock_class.new } it 'raises an error' do expect { subject.unlock(id) }.to raise_error(NotImplementedError) end end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/spec/circuitry/locks/memcache_spec.rb
spec/circuitry/locks/memcache_spec.rb
require 'spec_helper' RSpec.describe Circuitry::Locks::Memcache, type: :model do subject { described_class.new(soft_ttl: soft_ttl, hard_ttl: hard_ttl, client: client) } let(:soft_ttl) { 30 } let(:hard_ttl) { 60 } let(:client) { MemcacheMock.new } before do client.flush end it_behaves_like 'a lock' describe '.new' do subject { described_class } describe 'when client is provided' do let(:options) { { soft_ttl: soft_ttl, hard_ttl: hard_ttl, client: client } } it 'does not create a new client' do expect(Dalli::Client).to_not receive(:new) subject.new(options) end end describe 'when client is not provided' do let(:options) { { soft_ttl: soft_ttl, hard_ttl: hard_ttl, host: host } } let(:host) { 'localhost:11211' } it 'creates a new client' do expect(Dalli::Client).to receive(:new).with(host, options) subject.new(options) end end end end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false
kapost/circuitry
https://github.com/kapost/circuitry/blob/d49325462ab43c98af6af18c98dbfa609fba1851/spec/circuitry/locks/memory_spec.rb
spec/circuitry/locks/memory_spec.rb
require 'spec_helper' RSpec.describe Circuitry::Locks::Memory, type: :model do subject { described_class.new(soft_ttl: soft_ttl, hard_ttl: hard_ttl) } let(:soft_ttl) { 30 } let(:hard_ttl) { 60 } before do described_class.store.clear end it_behaves_like 'a lock' end
ruby
MIT
d49325462ab43c98af6af18c98dbfa609fba1851
2026-01-04T17:44:26.741626Z
false