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
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/test/dummy/config/initializers/pagy.rb
test/dummy/config/initializers/pagy.rb
# copy https://github.com/ddnexus/pagy/blob/3.8.1/lib/config/pagy.rb here and customize if needed
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/test/dummy/config/initializers/wrap_parameters.rb
test/dummy/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
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/test/dummy/config/initializers/inflections.rb
test/dummy/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
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/test/dummy/config/initializers/cookies_serializer.rb
test/dummy/config/initializers/cookies_serializer.rb
# Be sure to restart your server when you modify this file. # Specify a serializer for the signed and encrypted cookie jars. # Valid options are :json, :marshal, and :hybrid. Rails.application.config.action_dispatch.cookies_serializer = :json
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/test/dummy/config/initializers/assets.rb
test/dummy/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 # Add Yarn node_modules folder to the asset load path. Rails.application.config.assets.paths << Rails.root.join('node_modules') # Precompile additional assets. # application.js, application.css, and all non-JS/CSS in the app/assets # folder are already added. # Rails.application.config.assets.precompile += %w( admin.js admin.css )
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/test/dummy/config/initializers/backtrace_silencers.rb
test/dummy/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| line =~ /my_noisy_library/ } # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. # Rails.backtrace_cleaner.remove_silencers!
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/test/dummy/config/initializers/mime_types.rb
test/dummy/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
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/test/dummy/config/environments/test.rb
test/dummy/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. config.cache_classes = false config.action_view.cache_template_loading = true # Do not eager load code on boot. This avoids loading your whole application # just for the purpose of running a single test. If you are using a tool that # preloads Rails for running tests, you may have to set it to true. config.eager_load = false # Configure public file server for tests with Cache-Control for performance. config.public_file_server.enabled = true config.public_file_server.headers = { 'Cache-Control' => "public, max-age=#{1.hour.to_i}" } # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false config.cache_store = :null_store # Raise exceptions instead of rendering exception templates. config.action_dispatch.show_exceptions = false # Disable request forgery protection in test environment. config.action_controller.allow_forgery_protection = false # Store uploaded files on the local file system in a temporary directory. config.active_storage.service = :test config.action_mailer.perform_caching = false # Tell Action Mailer not to deliver emails to the real world. # The :test delivery method accumulates sent emails in the # ActionMailer::Base.deliveries array. config.action_mailer.delivery_method = :test # Print deprecation notices to the stderr. config.active_support.deprecation = :stderr # Raises error for missing translations. # config.action_view.raise_on_missing_translations = true end
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/test/dummy/config/environments/development.rb
test/dummy/config/environments/development.rb
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Do not eager load code on boot. config.eager_load = false # Show full error reports. config.consider_all_requests_local = true # Enable/disable caching. By default caching is disabled. # Run rails dev:cache to toggle 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.cache_store = :memory_store config.public_file_server.headers = { 'Cache-Control' => "public, max-age=#{2.days.to_i}" } else config.action_controller.perform_caching = false config.cache_store = :null_store end # Store uploaded files on the local file system (see config/storage.yml for options). config.active_storage.service = :local # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = false config.action_mailer.perform_caching = false # 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 # 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.action_view.raise_on_missing_translations = true # Use an evented file watcher to asynchronously detect changes in source code, # routes, locales, etc. This feature depends on the listen gem. config.file_watcher = ActiveSupport::EventedFileUpdateChecker end
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/test/dummy/config/environments/production.rb
test/dummy/config/environments/production.rb
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # Code is not reloaded between requests. config.cache_classes = true # Eager load code on boot. This eager loads most of Rails and # your application in memory, allowing both threaded web servers # and those relying on copy on write to perform better. # Rake tasks automatically ignore this option for performance. config.eager_load = true # Full error reports are disabled and caching is turned on. config.consider_all_requests_local = false config.action_controller.perform_caching = true # Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"] # or in config/master.key. This key is used to decrypt credentials (and other encrypted files). # config.require_master_key = true # Disable serving static files from the `/public` folder by default since # Apache or NGINX already handles this. config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? # Compress CSS using a preprocessor. # config.assets.css_compressor = :sass # Do not fallback 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.action_controller.asset_host = 'http://assets.example.com' # Specifies the header that your server uses for sending files. # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX # Store uploaded files on the local file system (see config/storage.yml for options). config.active_storage.service = :local # Mount Action Cable outside main process or domain. # config.action_cable.mount_path = nil # config.action_cable.url = 'wss://example.com/cable' # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # Use the lowest log level to ensure availability of diagnostic information # when problems arise. config.log_level = :debug # Prepend all log lines with the following tags. config.log_tags = [ :request_id ] # Use a different cache store in production. # config.cache_store = :mem_cache_store # Use a real queuing backend for Active Job (and separate queues per environment). # config.active_job.queue_adapter = :resque # config.active_job.queue_name_prefix = "dummy_production" config.action_mailer.perform_caching = false # Ignore bad email addresses and do not raise email delivery errors. # Set this to true and configure the email server for immediate delivery to raise delivery errors. # config.action_mailer.raise_delivery_errors = false # 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 # Send deprecation notices to registered listeners. config.active_support.deprecation = :notify # Use default logging formatter so that PID and timestamp are not suppressed. config.log_formatter = ::Logger::Formatter.new # Use a different logger for distributed setups. # require 'syslog/logger' # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') if ENV["RAILS_LOG_TO_STDOUT"].present? logger = ActiveSupport::Logger.new(STDOUT) logger.formatter = config.log_formatter config.logger = ActiveSupport::TaggedLogging.new(logger) end # Do not dump schema after migrations. config.active_record.dump_schema_after_migration = false # Inserts middleware to perform automatic connection switching. # The `database_selector` hash is used to pass options to the DatabaseSelector # middleware. The `delay` is used to determine how long to wait after a write # to send a subsequent read to the primary. # # The `database_resolver` class is used by the middleware to determine which # database is appropriate to use based on the time delay. # # The `database_resolver_context` class is used by the middleware to set # timestamps for the last write to the primary. The resolver uses the context # class timestamps to determine how long to wait before reading from the # replica. # # By default Rails will store a last write timestamp in the session. The # DatabaseSelector middleware is designed as such you can define your own # strategy for connection switching and pass that into the middleware through # these configuration options. # config.active_record.database_selector = { delay: 2.seconds } # config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver # config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session end
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/test/lib/rails_stats/json_formatter_test.rb
test/lib/rails_stats/json_formatter_test.rb
# frozen_string_literal: true require "test_helper" describe RailsStats::JSONFormatter do describe "#result" do JSON_STRING = <<~EOS [{ "summary": { "declared": 9, "unpinned": 6, "total": 18, "github": 0 }, "gems": [ { "name": "simplecov-console", "total_dependencies": 8, "first_level_dependencies": 3, "top_level_dependencies": {}, "transitive_dependencies": [ "ansi (>= 0)", "simplecov (>= 0)", "terminal-table (>= 0)", "docile (~> 1.1)", "simplecov-html (~> 0.11)", "simplecov_json_formatter (~> 0.1)", "unicode-display_width (>= 1.1.1, < 4)", "unicode-emoji (~> 4.0, >= 4.0.4)" ] }, { "name": "codecov", "total_dependencies": 4, "first_level_dependencies": 1, "top_level_dependencies": {}, "transitive_dependencies": [ "simplecov (>= 0.15, < 0.22)", "docile (~> 1.1)", "simplecov-html (~> 0.11)", "simplecov_json_formatter (~> 0.1)" ] }, { "name": "rails_stats", "total_dependencies": 4, "first_level_dependencies": 2, "top_level_dependencies": {}, "transitive_dependencies": [ "bundler-stats (>= 2.1)", "rake (>= 0)", "bundler (>= 1.9, < 3)", "thor (>= 0.19.0, < 2.0)" ] }, { "name": "simplecov", "total_dependencies": 3, "first_level_dependencies": 3, "top_level_dependencies": { "codecov": "codecov (0.6.0)", "simplecov-console": "simplecov-console (0.9.3)" }, "transitive_dependencies": [ "docile (~> 1.1)", "simplecov-html (~> 0.11)", "simplecov_json_formatter (~> 0.1)" ] }, { "name": "minitest-around", "total_dependencies": 1, "first_level_dependencies": 1, "top_level_dependencies": {}, "transitive_dependencies": [ "minitest (~> 5.0)" ] }, { "name": "bundler", "total_dependencies": 0, "first_level_dependencies": 0, "top_level_dependencies": { "bundler-stats": "bundler-stats (2.4.0)", "rails_stats": "rails_stats (2.0.1)" }, "transitive_dependencies": [] }, { "name": "byebug", "total_dependencies": 0, "first_level_dependencies": 0, "top_level_dependencies": {}, "transitive_dependencies": [] }, { "name": "minitest", "total_dependencies": 0, "first_level_dependencies": 0, "top_level_dependencies": { "minitest-around": "minitest-around (0.5.0)" }, "transitive_dependencies": [] }, { "name": "minitest-spec-context", "total_dependencies": 0, "first_level_dependencies": 0, "top_level_dependencies": {}, "transitive_dependencies": [] } ] },{ "name": "Mailers", "files": "1", "lines": "4", "loc": "4", "classes": "1", "methods": "0", "m_over_c": "0", "loc_over_m": "0" }, { "name": "Helpers", "files": "1", "lines": "3", "loc": "3", "classes": "0", "methods": "0", "m_over_c": "0", "loc_over_m": "0" }, { "name": "Jobs", "files": "1", "lines": "7", "loc": "2", "classes": "1", "methods": "0", "m_over_c": "0", "loc_over_m": "0" }, { "name": "Controllers", "files": "1", "lines": "7", "loc": "6", "classes": "1", "methods": "1", "m_over_c": "1", "loc_over_m": "4" }, { "name": "Models", "files": "4", "lines": "10", "loc": "10", "classes": "4", "methods": "0", "m_over_c": "0", "loc_over_m": "0" }, { "name": "Channels", "files": "2", "lines": "8", "loc": "8", "classes": "2", "methods": "0", "m_over_c": "0", "loc_over_m": "0" }, { "name": "Javascripts", "files": "3", "lines": "27", "loc": "7", "classes": "0", "methods": "0", "m_over_c": "0", "loc_over_m": "0" }, { "name": "Libraries", "files": "1", "lines": "1", "loc": "1", "classes": "0", "methods": "0", "m_over_c": "0", "loc_over_m": "0" }, { "name": "Configuration", "files": "19", "lines": "417", "loc": "111", "classes": "1", "methods": "0", "m_over_c": "0", "loc_over_m": "0" }, { "name": "Model Tests", "files": "2", "lines": "5", "loc": "4", "classes": "2", "methods": "0", "m_over_c": "0", "loc_over_m": "0" }, { "name": "Spec Support", "files": "1", "lines": "1", "loc": "1", "classes": "0", "methods": "0", "m_over_c": "0", "loc_over_m": "0" }, { "name": "Test Support", "files": "1", "lines": "1", "loc": "1", "classes": "0", "methods": "0", "m_over_c": "0", "loc_over_m": "0" }, { "name": "Code", "files": "33", "lines": "484", "loc": "152", "classes": "10", "methods": "1", "m_over_c": "0", "loc_over_m": "150", "code_to_test_ratio": "0.0", "total": true }, { "name": "Tests", "files": "4", "lines": "7", "loc": "6", "classes": "2", "methods": "0", "m_over_c": "0", "loc_over_m": "0", "code_to_test_ratio": "0.0", "total": true }, { "name": "Total", "files": "37", "lines": "491", "loc": "158", "classes": "12", "methods": "1", "m_over_c": "0", "loc_over_m": "156", "code_to_test_ratio": "0.0", "total": true}, {"schema_stats": {"schema_path": "#{Dir.pwd}/test/dummy/db/schema.rb", "create_table calls count": 2}}, {"polymorphic_stats": {"polymorphic_models_count": 1} } ] EOS it "outputs useful stats for a Rails project" do root_directory = File.absolute_path("./test/dummy") calculator = RailsStats::StatsCalculator.new(root_directory) formatter = RailsStats::JSONFormatter.new(calculator) expectation = JSON.parse(JSON_STRING) result = formatter.result [expectation, result].each do |data| data.each do |hash| next unless hash["gems"] hash["gems"].each do |gem| next unless gem["transitive_dependencies"] gem["transitive_dependencies"].map! do |dep| name, constraints = dep.split(/[()]/) next dep unless constraints normalized_constraints = constraints.split(/,\s*/).sort.join(', ') "#{name}(#{normalized_constraints})" end.sort! end end end assert_equal expectation, result end end end
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/test/lib/rails_stats/code_statistics_test.rb
test/lib/rails_stats/code_statistics_test.rb
# frozen_string_literal: true require "test_helper" Minitest::Test.make_my_diffs_pretty! describe RailsStats::CodeStatistics do describe "#to_s" do it "outputs useful stats for a Rails project" do root_directory = File.expand_path('../../../test/dummy', File.dirname(__FILE__)) table = File.read(File.expand_path('../../../fixtures/console-output.txt', __FILE__)) out, err = capture_io do RailsStats::CodeStatistics.new(root_directory).to_s end assert_equal( table.lines.map(&:rstrip).join, out.lines.map(&:rstrip).join ) end end end
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/lib/rails_stats.rb
lib/rails_stats.rb
require "rails_stats/version" module RailsStats end require 'rake' require 'rails_stats/tasks'
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/lib/rails_stats/console_formatter.rb
lib/rails_stats/console_formatter.rb
require "bundler/stats/cli" module RailsStats class ConsoleFormatter < StatsFormatter def to_s Bundler::Stats::CLI.start print_header sorted_keys = @statistics.keys.sort sorted_keys.each { |key| print_line(key, @statistics[key]) } print_splitter if @grand_total print_line("Code", @code_total) print_line("Tests", @tests_total) print_line("Total", @grand_total) print_splitter end print_code_test_stats print_polymorphic_stats print_schema_stats end private def print_header print_splitter puts "| Name | Files | Lines | LOC | Classes | Methods | M/C | LOC/M |" print_splitter end def print_splitter puts "+----------------------+---------+---------+---------+---------+---------+-----+-------+" end def print_line(name, statistics) m_over_c = (statistics.methods / statistics.classes) rescue m_over_c = 0 loc_over_m = (statistics.code_lines / statistics.methods) - 2 rescue loc_over_m = 0 puts "| #{name.ljust(20)} " \ "| #{statistics.files_total.to_s.rjust(7)} " \ "| #{statistics.lines.to_s.rjust(7)} " \ "| #{statistics.code_lines.to_s.rjust(7)} " \ "| #{statistics.classes.to_s.rjust(7)} " \ "| #{statistics.methods.to_s.rjust(7)} " \ "| #{m_over_c.to_s.rjust(3)} " \ "| #{loc_over_m.to_s.rjust(5)} |" end def print_code_test_stats code = calculator.code_loc tests = calculator.test_loc puts " Code LOC: #{code} Test LOC: #{tests} Code to Test Ratio: 1:#{sprintf("%.1f", tests.to_f/code)} Files: #{calculator.files_total}" puts "" end def print_polymorphic_stats puts " Polymorphic models count: #{calculator.polymorphic} polymorphic associations" end def print_schema_stats if File.exist?(calculator.schema_path) puts " Schema Stats: #{calculator.schema} `create_table` calls in schema.rb" elsif File.exist?(calculator.structure_path) puts " Schema Stats: #{calculator.schema} `CREATE TABLE` calls in structure.sql" else puts " Schema Stats: No schema.rb or structure.sql file found" end end end end
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/lib/rails_stats/spec_statistics.rb
lib/rails_stats/spec_statistics.rb
module RailsStats class SpecStatistics attr_reader :statistics, :total, :test SPEC_FOLDERS = ['controllers', 'features', 'helpers', 'models', 'requests', 'routing', 'integrations', 'integration', 'mailers', 'lib', 'acceptance', 'factories'] def initialize(directory, key_concepts) @test = true @directory = directory @key_concepts = key_concepts @statistics = calculate_statistics @total = calculate_total end private def calculate_total out = CodeStatisticsCalculator.new(true) @statistics.each do |key, stats| out.add(stats) end out end def calculate_statistics out = {} categorize_files.each do |key, list| out[key] = Util.calculate_file_statistics(list) end out end def categorize_files out = {} Dir[File.join(@directory, "**", "*.rb")].each do |file_path| if file_path =~ /.*_spec.rb$/ key = categorize_file(file_path) else key = "Spec Support" end out[key] ||= [] out[key] << file_path end out end def categorize_file(file_path) types = (@key_concepts + SPEC_FOLDERS).uniq types.each do |folder| if file_path =~ /\/#{folder}\// folder = Inflector.humanize(folder) folder = Inflector.titleize(folder) folder = Inflector.singularize(folder) return "#{folder} Tests" end end # something else return "Other Tests" end end end
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/lib/rails_stats/version.rb
lib/rails_stats/version.rb
# frozen_string_literal: true module RailsStats VERSION = "2.0.1" end
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/lib/rails_stats/json_formatter.rb
lib/rails_stats/json_formatter.rb
require "json" module RailsStats class JSONFormatter < StatsFormatter def result @result = [] old_stdout = $stdout $stdout = StringIO.new Bundler::Stats::CLI.start(["-f", "json"]) bundler_stats_cli_json_result = $stdout.string $stdout = old_stdout @result << JSON.parse(bundler_stats_cli_json_result) unless bundler_stats_cli_json_result.strip.empty? @result += @statistics.map { |key, stats| stat_hash(key, stats) } @result << stat_hash("Code", @code_total).merge(code_test_hash) if @code_total @result << stat_hash("Tests", @tests_total).merge(code_test_hash) if @tests_total @result << stat_hash("Total", @grand_total).merge(code_test_hash) if @grand_total @result << { "schema_stats" => schema_info } @result << { "polymorphic_stats" => print_polymorphic_stats } @result end def to_s puts JSON.generate(result, ascii_only: false) end private def code_test_hash code = calculator.code_loc tests = calculator.test_loc { "code_to_test_ratio" => "#{sprintf("%.1f", tests.to_f/code)}", "total" => true } end def stat_hash(name, statistics) m_over_c = (statistics.methods / statistics.classes) rescue m_over_c = 0 loc_over_m = (statistics.code_lines / statistics.methods) - 2 rescue loc_over_m = 0 { "name" => name, "files" => statistics.files_total.to_s, "lines" => statistics.lines.to_s, "loc" => statistics.code_lines.to_s, "classes" => statistics.classes.to_s, "methods" => statistics.methods.to_s, "m_over_c" => m_over_c.to_s, "loc_over_m" => loc_over_m.to_s } end def print_polymorphic_stats if calculator.polymorphic { "polymorphic_models_count" => calculator.polymorphic, } end end def schema_info if File.exist?(calculator.schema_path) { "schema_path" => calculator.schema_path, "create_table calls count" => calculator.schema, } elsif File.exist?(calculator.structure_path) { "structure_path" => calculator.structure_path, "create_table calls count" => calculator.schema } else { "schema_stats" => "No schema.rb or structure.sql file found" } end end end end
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/lib/rails_stats/gem_statistics.rb
lib/rails_stats/gem_statistics.rb
module RailsStats class GemStatistics attr_reader :statistics, :total, :test def initialize(directory) @test = false @directory = directory @statistics = calculate_statistics @total = calculate_total end private def calculate_total out = CodeStatisticsCalculator.new @statistics.each do |key, stats| out.add(stats) end out end def calculate_statistics # ignore gem/app so as to not double-count engines lib = File.join(@directory, "lib") Util.calculate_statistics([lib]) do |path| "Gems" end end end end
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/lib/rails_stats/code_statistics.rb
lib/rails_stats/code_statistics.rb
# railties/lib/rails/code_statistics.rb module RailsStats class CodeStatistics def initialize(root_directory, opts = {}) @calculator = RailsStats::StatsCalculator.new(root_directory) @formatter = load_formatter(opts) end def to_s @formatter.to_s end private def load_formatter(opts = {}) if opts[:format] == "json" RailsStats::JSONFormatter.new(@calculator, opts) else RailsStats::ConsoleFormatter.new(@calculator, opts) end end end end
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/lib/rails_stats/root_statistics.rb
lib/rails_stats/root_statistics.rb
module RailsStats class RootStatistics attr_reader :statistics, :total, :test ROOT_FOLDERS = { "lib" => "Libraries", "config" => "Configuration" } def initialize(directory) @test = false @directory = directory @statistics = calculate_statistics @total = calculate_total end private def calculate_total out = CodeStatisticsCalculator.new @statistics.each do |key, stats| out.add(stats) end out end def calculate_statistics Util.calculate_statistics(directories) do |folder| ROOT_FOLDERS[File.basename(folder)] end end def directories out = [] ROOT_FOLDERS.each do |folder, name| out << File.join(@directory, folder) end out end end end
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/lib/rails_stats/inflector.rb
lib/rails_stats/inflector.rb
# encoding: utf-8 module RailsStats # The Inflector transforms words from singular to plural, class names to table # names, modularized class names to ones without, and class names to foreign # keys. The default inflections for pluralization, singularization, and # uncountable words are kept in inflections.rb. # # The Rails core team has stated patches for the inflections library will not # be accepted in order to avoid breaking legacy applications which may be # relying on errant inflections. If you discover an incorrect inflection and # require it for your application or wish to define rules for languages other # than English, please correct or add them yourself (explained below). module Inflector extend self # A singleton instance of this class is yielded by Inflector.inflections, # which can then be used to specify additional inflection rules. If passed # an optional locale, rules for other languages can be specified. The # default locale is <tt>:en</tt>. Only rules for English are provided. # # ActiveSupport::Inflector.inflections(:en) do |inflect| # inflect.plural /^(ox)$/i, '\1\2en' # inflect.singular /^(ox)en/i, '\1' # # inflect.irregular 'octopus', 'octopi' # # inflect.uncountable 'equipment' # end # # New rules are added at the top. So in the example above, the irregular # rule for octopus will now be the first of the pluralization and # singularization rules that is runs. This guarantees that your rules run # before any of the rules that may already have been loaded. class Inflections def self.instance(locale = :en) @__instance__ ||= new end attr_reader :plurals, :singulars, :uncountables, :humans, :acronyms, :acronym_regex def initialize @plurals, @singulars, @uncountables, @humans, @acronyms, @acronym_regex = [], [], [], [], {}, /(?=a)b/ end # Private, for the test suite. def initialize_dup(orig) # :nodoc: %w(plurals singulars uncountables humans acronyms acronym_regex).each do |scope| instance_variable_set("@#{scope}", orig.send(scope).dup) end end # Specifies a new acronym. An acronym must be specified as it will appear # in a camelized string. An underscore string that contains the acronym # will retain the acronym when passed to +camelize+, +humanize+, or # +titleize+. A camelized string that contains the acronym will maintain # the acronym when titleized or humanized, and will convert the acronym # into a non-delimited single lowercase word when passed to +underscore+. # # acronym 'HTML' # titleize 'html' #=> 'HTML' # camelize 'html' #=> 'HTML' # underscore 'MyHTML' #=> 'my_html' # # The acronym, however, must occur as a delimited unit and not be part of # another word for conversions to recognize it: # # acronym 'HTTP' # camelize 'my_http_delimited' #=> 'MyHTTPDelimited' # camelize 'https' #=> 'Https', not 'HTTPs' # underscore 'HTTPS' #=> 'http_s', not 'https' # # acronym 'HTTPS' # camelize 'https' #=> 'HTTPS' # underscore 'HTTPS' #=> 'https' # # Note: Acronyms that are passed to +pluralize+ will no longer be # recognized, since the acronym will not occur as a delimited unit in the # pluralized result. To work around this, you must specify the pluralized # form as an acronym as well: # # acronym 'API' # camelize(pluralize('api')) #=> 'Apis' # # acronym 'APIs' # camelize(pluralize('api')) #=> 'APIs' # # +acronym+ may be used to specify any word that contains an acronym or # otherwise needs to maintain a non-standard capitalization. The only # restriction is that the word must begin with a capital letter. # # acronym 'RESTful' # underscore 'RESTful' #=> 'restful' # underscore 'RESTfulController' #=> 'restful_controller' # titleize 'RESTfulController' #=> 'RESTful Controller' # camelize 'restful' #=> 'RESTful' # camelize 'restful_controller' #=> 'RESTfulController' # # acronym 'McDonald' # underscore 'McDonald' #=> 'mcdonald' # camelize 'mcdonald' #=> 'McDonald' def acronym(word) @acronyms[word.downcase] = word @acronym_regex = /#{@acronyms.values.join("|")}/ end # Specifies a new pluralization rule and its replacement. The rule can # either be a string or a regular expression. The replacement should # always be a string that may include references to the matched data from # the rule. def plural(rule, replacement) @uncountables.delete(rule) if rule.is_a?(String) @uncountables.delete(replacement) @plurals.unshift([rule, replacement]) end # Specifies a new singularization rule and its replacement. The rule can # either be a string or a regular expression. The replacement should # always be a string that may include references to the matched data from # the rule. def singular(rule, replacement) @uncountables.delete(rule) if rule.is_a?(String) @uncountables.delete(replacement) @singulars.unshift([rule, replacement]) end # Specifies a new irregular that applies to both pluralization and # singularization at the same time. This can only be used for strings, not # regular expressions. You simply pass the irregular in singular and # plural form. # # irregular 'octopus', 'octopi' # irregular 'person', 'people' def irregular(singular, plural) @uncountables.delete(singular) @uncountables.delete(plural) s0 = singular[0] srest = singular[1..-1] p0 = plural[0] prest = plural[1..-1] if s0.upcase == p0.upcase plural(/(#{s0})#{srest}$/i, '\1' + prest) plural(/(#{p0})#{prest}$/i, '\1' + prest) singular(/(#{s0})#{srest}$/i, '\1' + srest) singular(/(#{p0})#{prest}$/i, '\1' + srest) else plural(/#{s0.upcase}(?i)#{srest}$/, p0.upcase + prest) plural(/#{s0.downcase}(?i)#{srest}$/, p0.downcase + prest) plural(/#{p0.upcase}(?i)#{prest}$/, p0.upcase + prest) plural(/#{p0.downcase}(?i)#{prest}$/, p0.downcase + prest) singular(/#{s0.upcase}(?i)#{srest}$/, s0.upcase + srest) singular(/#{s0.downcase}(?i)#{srest}$/, s0.downcase + srest) singular(/#{p0.upcase}(?i)#{prest}$/, s0.upcase + srest) singular(/#{p0.downcase}(?i)#{prest}$/, s0.downcase + srest) end end # Add uncountable words that shouldn't be attempted inflected. # # uncountable 'money' # uncountable 'money', 'information' # uncountable %w( money information rice ) def uncountable(*words) (@uncountables << words).flatten! end # Specifies a humanized form of a string by a regular expression rule or # by a string mapping. When using a regular expression based replacement, # the normal humanize formatting is called after the replacement. When a # string is used, the human form should be specified as desired (example: # 'The name', not 'the_name'). # # human /_cnt$/i, '\1_count' # human 'legacy_col_person_name', 'Name' def human(rule, replacement) @humans.unshift([rule, replacement]) end # Clears the loaded inflections within a given scope (default is # <tt>:all</tt>). Give the scope as a symbol of the inflection type, the # options are: <tt>:plurals</tt>, <tt>:singulars</tt>, <tt>:uncountables</tt>, # <tt>:humans</tt>. # # clear :all # clear :plurals def clear(scope = :all) case scope when :all @plurals, @singulars, @uncountables, @humans = [], [], [], [] else instance_variable_set "@#{scope}", [] end end end # Yields a singleton instance of Inflector::Inflections so you can specify # additional inflector rules. If passed an optional locale, rules for other # languages can be specified. If not specified, defaults to <tt>:en</tt>. # Only rules for English are provided. # # ActiveSupport::Inflector.inflections(:en) do |inflect| # inflect.uncountable 'rails' # end def inflections(locale = :en) if block_given? yield Inflections.instance(locale) else Inflections.instance(locale) end end # Returns the plural form of the word in the string. # # If passed an optional +locale+ parameter, the word will be # pluralized using rules defined for that language. By default, # this parameter is set to <tt>:en</tt>. # # 'post'.pluralize # => "posts" # 'octopus'.pluralize # => "octopi" # 'sheep'.pluralize # => "sheep" # 'words'.pluralize # => "words" # 'CamelOctopus'.pluralize # => "CamelOctopi" # 'ley'.pluralize(:es) # => "leyes" def pluralize(word, locale = :en) apply_inflections(word, inflections(locale).plurals) end # The reverse of +pluralize+, returns the singular form of a word in a # string. # # If passed an optional +locale+ parameter, the word will be # pluralized using rules defined for that language. By default, # this parameter is set to <tt>:en</tt>. # # 'posts'.singularize # => "post" # 'octopi'.singularize # => "octopus" # 'sheep'.singularize # => "sheep" # 'word'.singularize # => "word" # 'CamelOctopi'.singularize # => "CamelOctopus" # 'leyes'.singularize(:es) # => "ley" def singularize(word, locale = :en) apply_inflections(word, inflections(locale).singulars) end # By default, +camelize+ converts strings to UpperCamelCase. If the argument # to +camelize+ is set to <tt>:lower</tt> then +camelize+ produces # lowerCamelCase. # # +camelize+ will also convert '/' to '::' which is useful for converting # paths to namespaces. # # 'active_model'.camelize # => "ActiveModel" # 'active_model'.camelize(:lower) # => "activeModel" # 'active_model/errors'.camelize # => "ActiveModel::Errors" # 'active_model/errors'.camelize(:lower) # => "activeModel::Errors" # # As a rule of thumb you can think of +camelize+ as the inverse of # +underscore+, though there are cases where that does not hold: # # 'SSLError'.underscore.camelize # => "SslError" def camelize(term, uppercase_first_letter = true) string = term.to_s if uppercase_first_letter string = string.sub(/^[a-z\d]*/) { inflections.acronyms[$&] || $&.capitalize } else string = string.sub(/^(?:#{inflections.acronym_regex}(?=\b|[A-Z_])|\w)/) { $&.downcase } end string.gsub(/(?:_|(\/))([a-z\d]*)/i) { "#{$1}#{inflections.acronyms[$2] || $2.capitalize}" }.gsub('/', '::') end # Makes an underscored, lowercase form from the expression in the string. # # Changes '::' to '/' to convert namespaces to paths. # # 'ActiveModel'.underscore # => "active_model" # 'ActiveModel::Errors'.underscore # => "active_model/errors" # # As a rule of thumb you can think of +underscore+ as the inverse of # +camelize+, though there are cases where that does not hold: # # 'SSLError'.underscore.camelize # => "SslError" def underscore(camel_cased_word) word = camel_cased_word.to_s.dup word.gsub!('::', '/') word.gsub!(/(?:([A-Za-z\d])|^)(#{inflections.acronym_regex})(?=\b|[^a-z])/) { "#{$1}#{$1 && '_'}#{$2.downcase}" } word.gsub!(/([A-Z\d]+)([A-Z][a-z])/,'\1_\2') word.gsub!(/([a-z\d])([A-Z])/,'\1_\2') word.tr!("-", "_") word.downcase! word end # Capitalizes the first word and turns underscores into spaces and strips a # trailing "_id", if any. Like +titleize+, this is meant for creating pretty # output. # # 'employee_salary'.humanize # => "Employee salary" # 'author_id'.humanize # => "Author" def humanize(lower_case_and_underscored_word) result = lower_case_and_underscored_word.to_s.dup inflections.humans.each { |(rule, replacement)| break if result.sub!(rule, replacement) } result.gsub!(/_id$/, "") result.tr!('_', ' ') result.gsub(/([a-z\d]*)/i) { |match| "#{inflections.acronyms[match] || match.downcase}" }.gsub(/^\w/) { $&.upcase } end # Capitalizes all the words and replaces some characters in the string to # create a nicer looking title. +titleize+ is meant for creating pretty # output. It is not used in the Rails internals. # # +titleize+ is also aliased as +titlecase+. # # 'man from the boondocks'.titleize # => "Man From The Boondocks" # 'x-men: the last stand'.titleize # => "X Men: The Last Stand" # 'TheManWithoutAPast'.titleize # => "The Man Without A Past" # 'raiders_of_the_lost_ark'.titleize # => "Raiders Of The Lost Ark" def titleize(word) humanize(underscore(word)).gsub(/\b(?<!['’`])[a-z]/) { $&.capitalize } end # Create the name of a table like Rails does for models to table names. This # method uses the +pluralize+ method on the last word in the string. # # 'RawScaledScorer'.tableize # => "raw_scaled_scorers" # 'egg_and_ham'.tableize # => "egg_and_hams" # 'fancyCategory'.tableize # => "fancy_categories" def tableize(class_name) pluralize(underscore(class_name)) end # Create a class name from a plural table name like Rails does for table # names to models. Note that this returns a string and not a Class (To # convert to an actual class follow +classify+ with +constantize+). # # 'egg_and_hams'.classify # => "EggAndHam" # 'posts'.classify # => "Post" # # Singular names are not handled correctly: # # 'business'.classify # => "Busines" def classify(table_name) # strip out any leading schema name camelize(singularize(table_name.to_s.sub(/.*\./, ''))) end # Replaces underscores with dashes in the string. # # 'puni_puni'.dasherize # => "puni-puni" def dasherize(underscored_word) underscored_word.tr('_', '-') end # Removes the module part from the expression in the string. # # 'ActiveRecord::CoreExtensions::String::Inflections'.demodulize # => "Inflections" # 'Inflections'.demodulize # => "Inflections" # # See also +deconstantize+. def demodulize(path) path = path.to_s if i = path.rindex('::') path[(i+2)..-1] else path end end # Removes the rightmost segment from the constant expression in the string. # # 'Net::HTTP'.deconstantize # => "Net" # '::Net::HTTP'.deconstantize # => "::Net" # 'String'.deconstantize # => "" # '::String'.deconstantize # => "" # ''.deconstantize # => "" # # See also +demodulize+. def deconstantize(path) path.to_s[0...(path.rindex('::') || 0)] # implementation based on the one in facets' Module#spacename end # Creates a foreign key name from a class name. # +separate_class_name_and_id_with_underscore+ sets whether # the method should put '_' between the name and 'id'. # # 'Message'.foreign_key # => "message_id" # 'Message'.foreign_key(false) # => "messageid" # 'Admin::Post'.foreign_key # => "post_id" def foreign_key(class_name, separate_class_name_and_id_with_underscore = true) underscore(demodulize(class_name)) + (separate_class_name_and_id_with_underscore ? "_id" : "id") end # Tries to find a constant with the name specified in the argument string. # # 'Module'.constantize # => Module # 'Test::Unit'.constantize # => Test::Unit # # The name is assumed to be the one of a top-level constant, no matter # whether it starts with "::" or not. No lexical context is taken into # account: # # C = 'outside' # module M # C = 'inside' # C # => 'inside' # 'C'.constantize # => 'outside', same as ::C # end # # NameError is raised when the name is not in CamelCase or the constant is # unknown. def constantize(camel_cased_word) names = camel_cased_word.split('::') names.shift if names.empty? || names.first.empty? names.inject(Object) do |constant, name| if constant == Object constant.const_get(name) else candidate = constant.const_get(name) next candidate if constant.const_defined?(name, false) next candidate unless Object.const_defined?(name) # Go down the ancestors to check it it's owned # directly before we reach Object or the end of ancestors. constant = constant.ancestors.inject do |const, ancestor| break const if ancestor == Object break ancestor if ancestor.const_defined?(name, false) const end # owner is in Object, so raise constant.const_get(name, false) end end end # Tries to find a constant with the name specified in the argument string. # # 'Module'.safe_constantize # => Module # 'Test::Unit'.safe_constantize # => Test::Unit # # The name is assumed to be the one of a top-level constant, no matter # whether it starts with "::" or not. No lexical context is taken into # account: # # C = 'outside' # module M # C = 'inside' # C # => 'inside' # 'C'.safe_constantize # => 'outside', same as ::C # end # # +nil+ is returned when the name is not in CamelCase or the constant (or # part of it) is unknown. # # 'blargle'.safe_constantize # => nil # 'UnknownModule'.safe_constantize # => nil # 'UnknownModule::Foo::Bar'.safe_constantize # => nil def safe_constantize(camel_cased_word) constantize(camel_cased_word) rescue NameError => e raise unless e.message =~ /(uninitialized constant|wrong constant name) #{const_regexp(camel_cased_word)}$/ || e.name.to_s == camel_cased_word.to_s rescue ArgumentError => e raise unless e.message =~ /not missing constant #{const_regexp(camel_cased_word)}\!$/ end # Returns the suffix that should be added to a number to denote the position # in an ordered sequence such as 1st, 2nd, 3rd, 4th. # # ordinal(1) # => "st" # ordinal(2) # => "nd" # ordinal(1002) # => "nd" # ordinal(1003) # => "rd" # ordinal(-11) # => "th" # ordinal(-1021) # => "st" def ordinal(number) abs_number = number.to_i.abs if (11..13).include?(abs_number % 100) "th" else case abs_number % 10 when 1; "st" when 2; "nd" when 3; "rd" else "th" end end end # Turns a number into an ordinal string used to denote the position in an # ordered sequence such as 1st, 2nd, 3rd, 4th. # # ordinalize(1) # => "1st" # ordinalize(2) # => "2nd" # ordinalize(1002) # => "1002nd" # ordinalize(1003) # => "1003rd" # ordinalize(-11) # => "-11th" # ordinalize(-1021) # => "-1021st" def ordinalize(number) "#{number}#{ordinal(number)}" end private # Mount a regular expression that will match part by part of the constant. # For instance, Foo::Bar::Baz will generate Foo(::Bar(::Baz)?)? def const_regexp(camel_cased_word) #:nodoc: parts = camel_cased_word.split("::") last = parts.pop parts.reverse.inject(last) do |acc, part| part.empty? ? acc : "#{part}(::#{acc})?" end end # Applies inflection rules for +singularize+ and +pluralize+. # # apply_inflections('post', inflections.plurals) # => "posts" # apply_inflections('posts', inflections.singulars) # => "post" def apply_inflections(word, rules) result = word.to_s.dup if word.empty? || inflections.uncountables.include?(result.downcase[/\b\w+\Z/]) result else rules.each { |(rule, replacement)| break if result.sub!(rule, replacement) } result end end end end RailsStats::Inflector.inflections(:en) do |inflect| inflect.plural(/$/, 's') inflect.plural(/s$/i, 's') inflect.plural(/^(ax|test)is$/i, '\1es') inflect.plural(/(octop|vir)us$/i, '\1i') inflect.plural(/(octop|vir)i$/i, '\1i') inflect.plural(/(alias|status)$/i, '\1es') inflect.plural(/(bu)s$/i, '\1ses') inflect.plural(/(buffal|tomat)o$/i, '\1oes') inflect.plural(/([ti])um$/i, '\1a') inflect.plural(/([ti])a$/i, '\1a') inflect.plural(/sis$/i, 'ses') inflect.plural(/(?:([^f])fe|([lr])f)$/i, '\1\2ves') inflect.plural(/(hive)$/i, '\1s') inflect.plural(/([^aeiouy]|qu)y$/i, '\1ies') inflect.plural(/(x|ch|ss|sh)$/i, '\1es') inflect.plural(/(matr|vert|ind)(?:ix|ex)$/i, '\1ices') inflect.plural(/^(m|l)ouse$/i, '\1ice') inflect.plural(/^(m|l)ice$/i, '\1ice') inflect.plural(/^(ox)$/i, '\1en') inflect.plural(/^(oxen)$/i, '\1') inflect.plural(/(quiz)$/i, '\1zes') inflect.singular(/s$/i, '') inflect.singular(/(ss)$/i, '\1') inflect.singular(/(n)ews$/i, '\1ews') inflect.singular(/([ti])a$/i, '\1um') inflect.singular(/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)(sis|ses)$/i, '\1sis') inflect.singular(/(^analy)(sis|ses)$/i, '\1sis') inflect.singular(/([^f])ves$/i, '\1fe') inflect.singular(/(hive)s$/i, '\1') inflect.singular(/(tive)s$/i, '\1') inflect.singular(/([lr])ves$/i, '\1f') inflect.singular(/([^aeiouy]|qu)ies$/i, '\1y') inflect.singular(/(s)eries$/i, '\1eries') inflect.singular(/(m)ovies$/i, '\1ovie') inflect.singular(/(x|ch|ss|sh)es$/i, '\1') inflect.singular(/^(m|l)ice$/i, '\1ouse') inflect.singular(/(bus)(es)?$/i, '\1') inflect.singular(/(o)es$/i, '\1') inflect.singular(/(shoe)s$/i, '\1') inflect.singular(/(cris|test)(is|es)$/i, '\1is') inflect.singular(/^(a)x[ie]s$/i, '\1xis') inflect.singular(/(octop|vir)(us|i)$/i, '\1us') inflect.singular(/(alias|status)(es)?$/i, '\1') inflect.singular(/^(ox)en/i, '\1') inflect.singular(/(vert|ind)ices$/i, '\1ex') inflect.singular(/(matr)ices$/i, '\1ix') inflect.singular(/(quiz)zes$/i, '\1') inflect.singular(/(database)s$/i, '\1') inflect.irregular('person', 'people') inflect.irregular('man', 'men') inflect.irregular('child', 'children') inflect.irregular('sex', 'sexes') inflect.irregular('move', 'moves') inflect.irregular('cow', 'kine') inflect.irregular('zombie', 'zombies') inflect.uncountable(%w(equipment information rice money species series fish sheep jeans police)) end
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/lib/rails_stats/code_statistics_calculator.rb
lib/rails_stats/code_statistics_calculator.rb
# railties/lib/rails/code_statistics_calculator.rb module RailsStats class CodeStatisticsCalculator #:nodoc: attr_reader :files_total, :lines, :code_lines, :classes, :methods, :test PATTERNS = { rb: { line_comment: /^\s*#/, begin_block_comment: /^=begin/, end_block_comment: /^=end/, class: /^\s*class\s+[_A-Z]/, method: /^\s*def\s+[_a-z]/, }, js: { line_comment: %r{^\s*//}, begin_block_comment: %r{^\s*/\*}, end_block_comment: %r{\*/}, method: /function(\s+[_a-zA-Z][\da-zA-Z]*)?\s*\(/, }, coffee: { line_comment: /^\s*#/, begin_block_comment: /^\s*###/, end_block_comment: /^\s*###/, class: /^\s*class\s+[_A-Z]/, method: /[-=]>/, }, feature: { class: /^\s*Feature:/, method: /^\s*Scenario:/, } } def initialize(test=false) @test = test @files_total = 0 @lines = 0 @code_lines = 0 @classes = 0 @methods = 0 end def add(code_statistics_calculator) @files_total += code_statistics_calculator.files_total @lines += code_statistics_calculator.lines @code_lines += code_statistics_calculator.code_lines @classes += code_statistics_calculator.classes @methods += code_statistics_calculator.methods end def add_by_file_path(file_path) @files_total += 1 File.open(file_path) do |f| self.add_by_io(f, file_type(file_path)) end end def add_by_io(io, file_type) patterns = PATTERNS[file_type] || {} comment_started = false while line = io.gets @lines += 1 if comment_started if patterns[:end_block_comment] && line =~ patterns[:end_block_comment] comment_started = false end next else if patterns[:begin_block_comment] && line =~ patterns[:begin_block_comment] comment_started = true next end end @classes += 1 if patterns[:class] && line =~ patterns[:class] @methods += 1 if patterns[:method] && line =~ patterns[:method] if line !~ /^\s*$/ && (patterns[:line_comment].nil? || line !~ patterns[:line_comment]) @code_lines += 1 end end end private def file_type(file_path) File.extname(file_path).sub(/\A\./, '').downcase.to_sym end end end
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/lib/rails_stats/stats_formatter.rb
lib/rails_stats/stats_formatter.rb
module RailsStats class StatsFormatter def initialize(calculator, opts = {}) @calculator = calculator @statistics = calculator.statistics @code_total = calculator.code_total @tests_total = calculator.tests_total @grand_total = calculator.grand_total end attr_reader :calculator end end
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/lib/rails_stats/stats_calculator.rb
lib/rails_stats/stats_calculator.rb
module RailsStats class StatsCalculator RAILS_APP_FOLDERS = ['models', 'controllers', 'helpers', 'mailers', 'views', 'assets'] def initialize(root_directory) @root_directory = root_directory @schema_path = File.join(@root_directory, "db", "schema.rb") @structure_path = File.join(@root_directory, "db", "structure.sql") @key_concepts = calculate_key_concepts @projects = calculate_projects @statistics = calculate_statistics @code_loc = calculate_code @test_loc = calculate_tests @schema = calculate_create_table_calls @polymorphic = calculate_polymorphic @files_total, @code_total, @tests_total, @grand_total = calculate_totals end attr_reader :code_loc, :code_total, :files_total, :grand_total, :statistics, :test_loc, :tests_total, :schema, :schema_path, :structure_path, :polymorphic private def calculate_key_concepts # returns names of main things like models, controllers, services, etc concepts = {} app_projects.each do |project| project.key_concepts.each do |key| concepts[key] = true end end # TODO: maybe gem names? concepts.keys end def calculate_projects out = [] out += app_projects out += calculate_root_projects out += calculate_gem_projects out += calculate_spec_projects out += calculate_test_projects out += calculate_cucumber_projects out end def app_projects @app_projects ||= calculate_app_projects end def calculate_app_projects apps = Util.calculate_projects(@root_directory, "**", "app", RAILS_APP_FOLDERS) apps.collect do |root_path| AppStatistics.new(root_path) end end def calculate_gem_projects gems = Util.calculate_projects(@root_directory, "*", "**", "*.gemspec") gems.collect do |root_path| GemStatistics.new(root_path) end end def calculate_spec_projects specs = Util.calculate_shared_projects("spec", @root_directory, "**", "spec", "**", "*_spec.rb") specs.collect do |root_path| SpecStatistics.new(root_path, @key_concepts) end end def calculate_test_projects tests = Util.calculate_shared_projects("test", @root_directory, "**", "test", "**", "*_test.rb") tests.collect do |root_path| TestStatistics.new(root_path, @key_concepts) end end def calculate_root_projects [RootStatistics.new(@root_directory)] end def calculate_cucumber_projects cukes = Util.calculate_projects(@root_directory, "**", "*.feature") cukes.collect do |root_path| CucumberStatistics.new(root_path) end end def calculate_statistics out = {} @projects.each do |project| project.statistics.each do |key, stats| out[key] ||= CodeStatisticsCalculator.new(project.test) out[key].add(stats) end end out end def calculate_totals files_total = @statistics.sum do |k,value| value.files_total end code_total = @statistics.each_with_object(CodeStatisticsCalculator.new) do |pair, code_total| code_total.add(pair.last) unless pair.last.test end tests_total = @statistics.each_with_object(CodeStatisticsCalculator.new) do |pair, tests_total| tests_total.add(pair.last) if pair.last.test end grand_total = @statistics.each_with_object(CodeStatisticsCalculator.new) do |pair, total| total.add(pair.last) end [files_total, code_total, tests_total, grand_total] end def calculate_code @code_loc = 0 @statistics.each { |k, v| @code_loc += v.code_lines unless v.test } @code_loc end def calculate_tests @test_loc = 0 @statistics.each { |k, v| @test_loc += v.code_lines if v.test } @test_loc end def calculate_create_table_calls if @schema_path && File.exist?(@schema_path) count_create_table_calls(schema_path, "create_table") elsif @structure_path && File.exist?(@structure_path) count_create_table_calls(structure_path, "CREATE TABLE") else 0 end end def count_create_table_calls(file_path, keyword) create_table_count = 0 File.foreach(file_path) do |line| create_table_count += 1 if line.strip.start_with?(keyword) end create_table_count end def calculate_polymorphic polymorphic_count = 0 Dir.glob(File.join(@root_directory, "app", "models", "*.rb")).each do |file| File.foreach(file) do |line| if line =~ /belongs_to\s+:\w+,\s+polymorphic:\s+true/ polymorphic_count += 1 end end end polymorphic_count end end end
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/lib/rails_stats/app_statistics.rb
lib/rails_stats/app_statistics.rb
module RailsStats class AppStatistics attr_reader :statistics, :total, :test def initialize(directory) @directories = [] @test = false @directory = directory @statistics = calculate_statistics @total = calculate_total end def key_concepts directories.collect{ |path| File.basename(path) } end private def calculate_total out = CodeStatisticsCalculator.new @statistics.each do |key, stats| out.add(stats) end out end def calculate_statistics Util.calculate_statistics(directories) end def directories return @directories if @directories.any? Dir.foreach(@directory) do |file_name| path = File.join(@directory, file_name) next unless File.directory?(path) next if (/^\./ =~ file_name) next if file_name == "assets" # doing separately next if file_name == "views" # TODO @directories << path end assets = File.join(@directory, "assets") if File.directory?(assets) Dir.foreach(assets) do |file_name| path = File.join(assets, file_name) next unless File.directory?(path) next if (/^\./ =~ file_name) case file_name when "javascripts" @directories << path # TODO when "css" end end end @directories end end end
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/lib/rails_stats/tasks.rb
lib/rails_stats/tasks.rb
desc "Report code statistics (KLOCs, etc) from the current (or given) application" task :stats, [:path, :format] do |t, args| Rake::Task["stats"].clear # clear out normal one if there require 'rails_stats/all' path = args[:path] path = Rails.root.to_s if defined?(Rails) fmt = args[:format] || "" raise "no path given for stats" unless path root_directory = File.absolute_path(path) puts "\nDirectory: #{root_directory}\n\n" if args[:path] RailsStats::CodeStatistics.new(root_directory, format: fmt).to_s end
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/lib/rails_stats/cucumber_statistics.rb
lib/rails_stats/cucumber_statistics.rb
module RailsStats class CucumberStatistics attr_reader :statistics, :total, :test def initialize(directory) @test = true @directory = directory @statistics = calculate_statistics @total = calculate_total end private def calculate_total out = CodeStatisticsCalculator.new(true) @statistics.each do |key, stats| out.add(stats) end out end def calculate_statistics out = {} categorize_files.each do |key, list| out[key] = Util.calculate_file_statistics(list) end out end def categorize_files out = {} Dir[File.join(@directory, "**", "*.rb")].each do |file_path| out["Cucumber Support"] ||= [] out["Cucumber Support"] << file_path end Dir[File.join(@directory, "**", "*.feature")].each do |file_path| out["Cucumber Features"] ||= [] out["Cucumber Features"] << file_path end out end end end
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/lib/rails_stats/util.rb
lib/rails_stats/util.rb
module RailsStats module Util extend self def calculate_projects(*args) projects = {} children = [args.pop].flatten parent = args.flatten children.each do |dirname| child_folder_pattern = File.join(*(parent.dup + [dirname])) Dir[child_folder_pattern].each do |marker_path| next if marker_path =~ /\/vendor\// projects[File.absolute_path(File.dirname(marker_path))] = true end end out = projects.keys # TODO: make sure none are children of other ones in there out end def calculate_shared_projects(shared, *args) projects = {} calculate_projects(*args).each do |path| if path =~ /(^.*\/#{shared}\/).*/ projects[$1] = true end end out = projects.keys # TODO: make sure none are children of other ones in there out end def calculate_file_statistics(file, type = :code, &block) stats = CodeStatisticsCalculator.new files = [file].flatten files.each do |path| stats.add_by_file_path(path) end stats end def calculate_statistics(directories, type = :code, &block) out = {} directories = [directories].flatten is_test = (type.to_s == "test") directories.each do |dir_path| next unless File.directory?(dir_path) key = nil if block_given? key = yield(dir_path) end key = path_to_name(dir_path, is_test) if !key || key.length == 0 out[key] ||= CodeStatisticsCalculator.new(is_test) out[key].add(calculate_directory_statistics(dir_path)) end out.keys.each do |key| out.delete(key) if out[key].lines == 0 end out end def calculate_directory_statistics(directory, pattern = /.*\.(rb|js|coffee|feature)$/) stats = CodeStatisticsCalculator.new Dir.foreach(directory) do |file_name| path = "#{directory}/#{file_name}" if File.directory?(path) && (/^\./ !~ file_name) stats.add(calculate_directory_statistics(path, pattern)) end next unless file_name =~ pattern stats.add_by_file_path(path) end stats end def path_to_name(path, is_test) folder = File.basename(path) folder = Inflector.humanize(folder) folder = Inflector.titleize(folder) if is_test folder = Inflector.singularize(folder) folder = "#{folder} Tests" else folder = Inflector.pluralize(folder) end folder end end end
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/lib/rails_stats/test_statistics.rb
lib/rails_stats/test_statistics.rb
module RailsStats class TestStatistics attr_reader :statistics, :total, :test SPEC_FOLDERS = ['controllers', 'functional', 'helpers', 'models', 'requests', 'unit', 'integrations', 'integration', 'mailers', 'lib'] def initialize(directory, key_concepts) @test = true @directory = directory @key_concepts = key_concepts @statistics = calculate_statistics @total = calculate_total end private def calculate_total out = CodeStatisticsCalculator.new(true) @statistics.each do |key, stats| out.add(stats) end out end def calculate_statistics out = {} categorize_files.each do |key, list| out[key] = Util.calculate_file_statistics(list) end out end def categorize_files out = {} Dir[File.join(@directory, "**", "*.rb")].each do |file_path| if file_path =~ /.*_test.rb$/ key = categorize_file(file_path) else key = "Test Support" end out[key] ||= [] out[key] << file_path end out end def categorize_file(file_path) types = (@key_concepts + SPEC_FOLDERS).uniq types.each do |folder| if file_path =~ /\/#{folder}\// folder = Inflector.humanize(folder) folder = Inflector.titleize(folder) folder = Inflector.singularize(folder) return "#{folder} Tests" end end # something else return "Other Tests" end end end
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
fastruby/rails_stats
https://github.com/fastruby/rails_stats/blob/805b022b27464b5767ccbf8bf053c03b6d693aa7/lib/rails_stats/all.rb
lib/rails_stats/all.rb
require 'rails_stats/stats_calculator' require 'rails_stats/stats_formatter' require 'rails_stats/json_formatter' require 'rails_stats/console_formatter' require 'rails_stats/inflector' require 'rails_stats/code_statistics_calculator' require 'rails_stats/util' require 'rails_stats/app_statistics' require 'rails_stats/test_statistics' require 'rails_stats/spec_statistics' require 'rails_stats/cucumber_statistics' require 'rails_stats/root_statistics' require 'rails_stats/gem_statistics' require 'rails_stats/code_statistics'
ruby
MIT
805b022b27464b5767ccbf8bf053c03b6d693aa7
2026-01-04T17:54:07.356535Z
false
dry-rb/dry-events
https://github.com/dry-rb/dry-events/blob/719370eb3e259cc2762998b076ceb18beeae9ce7/spec/spec_helper.rb
spec/spec_helper.rb
# frozen_string_literal: true require_relative "support/coverage" begin require "pry" require "pry-byebug" rescue LoadError; end require "dry-events" SPEC_ROOT = Pathname(__dir__) Dir[SPEC_ROOT.join("shared/**/*.rb")].each(&method(:require)) Dir[SPEC_ROOT.join("support/**/*.rb")].each(&method(:require)) RSpec.configure do |config| config.after(:example) do Dry::Events::Publisher.instance_variable_set(:@__registry__, Concurrent::Map.new) end end
ruby
MIT
719370eb3e259cc2762998b076ceb18beeae9ce7
2026-01-04T17:54:09.241488Z
false
dry-rb/dry-events
https://github.com/dry-rb/dry-events/blob/719370eb3e259cc2762998b076ceb18beeae9ce7/spec/support/warnings.rb
spec/support/warnings.rb
# frozen_string_literal: true # This file is synced from hanakai-rb/repo-sync require "warning" Warning.ignore(%r{rspec/core}) Warning.ignore(%r{rspec/mocks}) Warning.ignore(/codacy/) Warning[:experimental] = false if Warning.respond_to?(:[])
ruby
MIT
719370eb3e259cc2762998b076ceb18beeae9ce7
2026-01-04T17:54:09.241488Z
false
dry-rb/dry-events
https://github.com/dry-rb/dry-events/blob/719370eb3e259cc2762998b076ceb18beeae9ce7/spec/support/coverage.rb
spec/support/coverage.rb
# frozen_string_literal: true # This file is synced from hanakai-rb/repo-sync if ENV["COVERAGE"] == "true" require "simplecov" require "simplecov-cobertura" SimpleCov.formatter = SimpleCov::Formatter::CoberturaFormatter SimpleCov.start do add_filter "/spec/" enable_coverage :branch end end
ruby
MIT
719370eb3e259cc2762998b076ceb18beeae9ce7
2026-01-04T17:54:09.241488Z
false
dry-rb/dry-events
https://github.com/dry-rb/dry-events/blob/719370eb3e259cc2762998b076ceb18beeae9ce7/spec/support/rspec.rb
spec/support/rspec.rb
# frozen_string_literal: true # This file is synced from hanakai-rb/repo-sync RSpec.configure do |config| # When no filter given, search and run focused tests config.filter_run_when_matching :focus # Disables rspec monkey patches (no reason for their existence tbh) config.disable_monkey_patching! # Run ruby in verbose mode config.warnings = true # Collect all failing expectations automatically, # without calling aggregate_failures everywhere config.define_derived_metadata do |meta| meta[:aggregate_failures] = true end if ENV['CI'] # No focused specs should be committed. This ensures # builds fail when this happens. config.before(:each, :focus) do raise StandardError, "You've committed a focused spec!" end end end
ruby
MIT
719370eb3e259cc2762998b076ceb18beeae9ce7
2026-01-04T17:54:09.241488Z
false
dry-rb/dry-events
https://github.com/dry-rb/dry-events/blob/719370eb3e259cc2762998b076ceb18beeae9ce7/spec/unit/dry/events/listener_spec.rb
spec/unit/dry/events/listener_spec.rb
# frozen_string_literal: true require "dry/events/listener" RSpec.describe Dry::Events::Listener do subject(:listener) do Class.new { include Dry::Events::Listener[:test_publisher] } end let!(:publisher) do Class.new { include Dry::Events::Publisher[:test_publisher] register_event :test_event }.new end describe ".subscribe" do let(:captured) { [] } it "subscribes a listener at class level" do listener.subscribe(:test_event) do |event| captured << event.id end publisher.publish(:test_event) expect(captured).to eql([:test_event]) end describe "filters" do it "filters events" do listener.subscribe(:test_event, level: :info) do |event| captured << event.payload end publisher.publish(:test_event) publisher.publish(:test_event, level: :debug) publisher.publish(:test_event, level: :info) expect(captured).to eql([level: :info]) end end end end
ruby
MIT
719370eb3e259cc2762998b076ceb18beeae9ce7
2026-01-04T17:54:09.241488Z
false
dry-rb/dry-events
https://github.com/dry-rb/dry-events/blob/719370eb3e259cc2762998b076ceb18beeae9ce7/spec/unit/dry/events/filter_spec.rb
spec/unit/dry/events/filter_spec.rb
# frozen_string_literal: true RSpec.describe Dry::Events::Filter do subject(:filter) { described_class.new(query) } context "nested hash" do let(:query) do {logger: {level: :info}} end specify do expect(filter.()).to be false expect(filter.(logger: {level: :info, output: :stdin})).to be true expect(filter.(logger: {level: :debug})).to be false expect(filter.(logger: :debug)).to be false end end context "multi-value check" do let(:query) do {logger: {level: :info, output: :stdin}} end specify do expect(filter.()).to be false expect(filter.(logger: {level: :info, output: :stdin})).to be true expect(filter.(logger: {level: :info})).to be false end end context "top-level array" do let(:query) { %i[error fatal] } specify do expect(filter.()).to be false expect(filter.(random: :hash)).to be false expect(filter.(:error)).to be true end end context "nested array" do let(:query) do {logger: {level: %i[info warn error fatal]}} end specify do expect(filter.()).to be false expect(filter.(logger: {level: :info, output: :stdin})).to be true expect(filter.(logger: {level: :fatal})).to be true expect(filter.(logger: {level: :debug})).to be false expect(filter.(level: :debug)).to be false end end context "nested proc" do let(:query) do {logger: {level: -> level { %i[error fatal].include?(level) }}} end specify do expect(filter.()).to be false expect(filter.(logger: {level: :error, output: :stdin})).to be true end end context "top-level proc" do let(:query) do -> ev { %i[error fatal].include?(ev.fetch(:level, :debug)) } end specify do expect(filter.()).to be false expect(filter.(level: :error, output: :stdin)).to be true end end end
ruby
MIT
719370eb3e259cc2762998b076ceb18beeae9ce7
2026-01-04T17:54:09.241488Z
false
dry-rb/dry-events
https://github.com/dry-rb/dry-events/blob/719370eb3e259cc2762998b076ceb18beeae9ce7/spec/unit/dry/events/event_spec.rb
spec/unit/dry/events/event_spec.rb
# frozen_string_literal: true require "dry/events/event" RSpec.describe Dry::Events::Event do subject(:event) do described_class.new(event_id, payload) end let(:payload) { {} } describe "invalid event name" do let(:event_id) { nil } it "raises InvalidEventNameError" do expect { event }.to raise_error(Dry::Events::Event::InvalidEventNameError) end end describe "#[]" do let(:event_id) { :test } let(:payload) { {test: :foo} } it "fetches payload key" do expect(event[:test]).to eq :foo end it "raises KeyError when no key found" do expect { event[:fake] }.to raise_error(KeyError) end end describe "#payload" do let(:event_id) { :test } let(:payload) { {test: :foo} } it "returns payload if no argument" do expect(event.payload).to eq payload end it "returns new event with payload payload" do new_event = event.payload({bar: :baz}) expect(new_event).to_not eq event expect(new_event.payload).to eq({test: :foo, bar: :baz}) end end describe "#to_h" do let(:event_id) { :test } let(:payload) { {test: :foo} } it "returns payload" do expect(event.to_h).to eq payload end end describe "#listener_method" do let(:event_id) { :test } it "returns listener method name" do expect(event.listener_method).to eq :on_test end it "replaces dots for underscores" do ev = Dry::Events::Event.new("hello.world") expect(ev.listener_method).to eq :on_hello_world end end end
ruby
MIT
719370eb3e259cc2762998b076ceb18beeae9ce7
2026-01-04T17:54:09.241488Z
false
dry-rb/dry-events
https://github.com/dry-rb/dry-events/blob/719370eb3e259cc2762998b076ceb18beeae9ce7/spec/unit/dry/events/publisher_spec.rb
spec/unit/dry/events/publisher_spec.rb
# frozen_string_literal: true require "dry/events/publisher" RSpec.describe Dry::Events::Publisher do subject(:publisher) do Class.new { include Dry::Events::Publisher[:test_publisher] register_event :test_event }.new end describe ".[]" do it "creates a publisher extension with provided id" do publisher = Class.new do include Dry::Events::Publisher[:my_publisher] end expect(Dry::Events::Publisher.registry[:my_publisher]).to be(publisher) end it "does not allow same id to be used for than once" do create_publisher = -> do Class.new do include Dry::Events::Publisher[:my_publisher] end end create_publisher.() expect { create_publisher.() }.to raise_error(Dry::Events::PublisherAlreadyRegisteredError, /my_publisher/) end end describe ".subscribe" do it "subscribes a listener at class level" do listener = -> * {} publisher.class.subscribe(:test_event, &listener) expect(publisher.subscribed?(listener)).to be(true) end it "raises an exception when subscribing to an unregister event" do listener = -> * {} expect { publisher.subscribe(:not_register, &listener) }.to raise_error(Dry::Events::InvalidSubscriberError, /not_register/) end end describe "#register_event" do it "registers a new event at instance level" do listener = -> * {} publisher.register_event(:test_another_event).subscribe(:test_another_event, &listener) expect(publisher.subscribed?(listener)).to be(true) end end describe "#subscribe" do it "subscribes a listener function" do listener = -> * {} publisher.subscribe(:test_event, &listener) expect(publisher.subscribed?(listener)).to be(true) end it "subscribes a listener object" do listener = Class.new do attr_reader :captured def initialize @captured = [] end def on_test_event(event) captured << event[:message] end end.new publisher.subscribe(listener).publish(:test_event, message: "it works") expect(listener.captured).to eql(["it works"]) publisher.unsubscribe(listener) publisher.publish(:test_event, message: "it works") expect(listener.captured).to eql(["it works"]) end it "raises an exception when subscribing with no methods to execute" do listener = Object.new expect { publisher.subscribe(listener) }.to raise_error(Dry::Events::InvalidSubscriberError, /never be executed/) end it "does not raise an exception when subscriber has methods for notification" do listener = Object.new def listener.on_test_event; nil; end expect { publisher.subscribe(listener) }.not_to raise_error end end describe "#unsubscribe" do it "unsubscribes a listener" do listener = Class.new do attr_reader :captured def initialize @captured = [] end def on_test_event(event) captured << event[:message] end end.new captured_by_block = [] publisher.subscribe(:test_event) do |event| captured_by_block << event[:message] end publisher.subscribe(listener) publisher.publish(:test_event, message: "it works") expect(listener.captured).to eql(["it works"]) expect(captured_by_block).to eql(["it works"]) publisher.unsubscribe(listener) publisher.publish(:test_event, message: "it works") expect(listener.captured).to eql(["it works"]) expect(captured_by_block).to eql(["it works", "it works"]) end end describe "#publish" do it "publishes an event" do result = [] listener = -> event { result << event[:message] } publisher.subscribe(:test_event, &listener).publish(:test_event, message: "it works") expect(result).to eql(["it works"]) end it "publishes an event filtered by a query" do result = [] listener = -> e { result << e[:test] } publisher .subscribe(:test_event, test: true, &listener) .publish(:test_event, test: false) .publish(:test_event, test: true) expect(result).to eql([true]) end it "raises an exception when publishing an unregistered event" do expect { publisher.publish(:unregistered_event, {}) }.to raise_error(Dry::Events::UnregisteredEventError, /unregistered_event/) end end describe "#process" do it "yields event and its listeners" do result = [] listener = -> event { result << event.id } publisher.subscribe(:test_event, &listener) publisher.process(:test_event) do |event, list| list.(event) end expect(result).to eql([:test_event]) end end describe "#subscribed?" do it "returns true when checking for previously subscribed instance methods" do listener = Object.new def listener.on_test_event nil end def listener.on_another_test_event nil end subject.register_event(:another_test_event) subject.subscribe(listener) expect(publisher.subscribed?(listener.method(:on_test_event))).to be(true) expect(publisher.subscribed?(listener.method(:on_another_test_event))).to be(true) end end end
ruby
MIT
719370eb3e259cc2762998b076ceb18beeae9ce7
2026-01-04T17:54:09.241488Z
false
dry-rb/dry-events
https://github.com/dry-rb/dry-events/blob/719370eb3e259cc2762998b076ceb18beeae9ce7/lib/dry-events.rb
lib/dry-events.rb
# frozen_string_literal: true require "dry/events"
ruby
MIT
719370eb3e259cc2762998b076ceb18beeae9ce7
2026-01-04T17:54:09.241488Z
false
dry-rb/dry-events
https://github.com/dry-rb/dry-events/blob/719370eb3e259cc2762998b076ceb18beeae9ce7/lib/dry/events.rb
lib/dry/events.rb
# frozen_string_literal: true require "dry/events/publisher"
ruby
MIT
719370eb3e259cc2762998b076ceb18beeae9ce7
2026-01-04T17:54:09.241488Z
false
dry-rb/dry-events
https://github.com/dry-rb/dry-events/blob/719370eb3e259cc2762998b076ceb18beeae9ce7/lib/dry/events/version.rb
lib/dry/events/version.rb
# frozen_string_literal: true module Dry module Events VERSION = "1.1.0" end end
ruby
MIT
719370eb3e259cc2762998b076ceb18beeae9ce7
2026-01-04T17:54:09.241488Z
false
dry-rb/dry-events
https://github.com/dry-rb/dry-events/blob/719370eb3e259cc2762998b076ceb18beeae9ce7/lib/dry/events/event.rb
lib/dry/events/event.rb
# frozen_string_literal: true require "dry/events/constants" module Dry module Events # Event object # # @api public class Event include ::Dry::Equalizer(:id, :payload) InvalidEventNameError = ::Class.new(::StandardError) do # @api private def initialize super("please provide a valid event name, it could be either String or Symbol") end end DOT = "." UNDERSCORE = "_" # @!attribute [r] id # @return [Symbol, String] The event identifier attr_reader :id # @api private def self.new(id, payload = EMPTY_HASH) return super if (id.is_a?(::String) || id.is_a?(::Symbol)) && !id.empty? raise InvalidEventNameError end # Initialize a new event # # @param [Symbol, String] id The event identifier # @param [Hash] payload # # @return [Event] # # @api private def initialize(id, payload) @id = id @payload = payload end # Get data from the payload # # @param [String,Symbol] name # # @api public def [](name) @payload.fetch(name) end # Coerce an event to a hash # # @return [Hash] # # @api public def to_h @payload end alias_method :to_hash, :to_h # Get or set a payload # # @overload # @return [Hash] payload # # @overload payload(data) # @param [Hash] data A new payload # @return [Event] A copy of the event with the provided payload # # @api public def payload(data = nil) if data self.class.new(id, @payload.merge(data)) else @payload end end # @api private def listener_method @listener_method ||= :"on_#{id.to_s.gsub(DOT, UNDERSCORE)}" end end end end
ruby
MIT
719370eb3e259cc2762998b076ceb18beeae9ce7
2026-01-04T17:54:09.241488Z
false
dry-rb/dry-events
https://github.com/dry-rb/dry-events/blob/719370eb3e259cc2762998b076ceb18beeae9ce7/lib/dry/events/filter.rb
lib/dry/events/filter.rb
# frozen_string_literal: true module Dry module Events # Event filter # # A filter cherry-picks probes payload of events. # Events not matching the predicates don't fire callbacks. # # @api private class Filter NO_MATCH = ::Object.new.freeze # @!attribute [r] events # @return [Array] A list of lambdas checking payloads attr_reader :checks # Create a new filter # # @param [Hash] filter Source filter # # @api private def initialize(filter) @checks = build_checks(filter) end # Test event payload against the checks # # @param [Hash] payload Event payload # # @api private def call(payload = EMPTY_HASH) checks.all? { |check| check.(payload) } end # Recursively build checks # # @api private def build_checks(filter, checks = EMPTY_ARRAY, keys = EMPTY_ARRAY) if filter.is_a?(::Hash) filter.reduce(checks) do |cs, (key, value)| build_checks(value, cs, [*keys, key]) end else [*checks, method(:compare).curry.(keys, predicate(filter))] end end # @api private def compare(path, predicate, payload) value = path.reduce(payload) do |acc, key| if acc.is_a?(::Hash) && acc.key?(key) acc[key] else break NO_MATCH end end predicate.(value) end # @api private def predicate(value) case value when ::Proc then value when ::Array then value.method(:include?) else value.method(:==) end end end end end
ruby
MIT
719370eb3e259cc2762998b076ceb18beeae9ce7
2026-01-04T17:54:09.241488Z
false
dry-rb/dry-events
https://github.com/dry-rb/dry-events/blob/719370eb3e259cc2762998b076ceb18beeae9ce7/lib/dry/events/publisher.rb
lib/dry/events/publisher.rb
# frozen_string_literal: true require "dry/core" require "dry/events/constants" require "dry/events/event" require "dry/events/bus" require "dry/events/filter" module Dry module Events # Exception raised when the same publisher is registered more than once # # @api public PublisherAlreadyRegisteredError = ::Class.new(::StandardError) do # @api private def initialize(id) super("publisher with id #{id.inspect} already registered as: #{Publisher.registry[id]}") end end # @api public InvalidSubscriberError = ::Class.new(::StandardError) do # @api private def initialize(object_or_event_id) case object_or_event_id when ::String, ::Symbol super( "you are trying to subscribe to an event: `#{object_or_event_id}` " \ "that has not been registered" ) else super("you try use subscriber object that will never be executed") end end end UnregisteredEventError = ::Class.new(::StandardError) do def initialize(object_or_event_id) case object_or_event_id when ::String, ::Symbol super("You are trying to publish an unregistered event: `#{object_or_event_id}`") else super("You are trying to publish an unregistered event") end end end # Extension used for classes that can publish events # # @example # class AppEvents # include Dry::Events::Publisher[:app] # # register_event('users.created') # end # # class CreateUser # attr_reader :events # # def initialize(events) # @events = events # end # # def call(user) # # do your thing # events.publish('users.created', user: user, time: Time.now) # end # end # # app_events = AppEvents.new # create_user = CreateUser.new(app_events) # # # this will publish "users.created" event with its payload # create_user.call(name: "Jane") # # @api public class Publisher < ::Module include ::Dry::Equalizer(:id) # Internal publisher registry, which is used to identify them globally # # This allows us to have listener classes that can subscribe to events # without having access to instances of publishers yet. # # @api private def self.registry @__registry__ ||= ::Concurrent::Map.new end # @!attribute [r] :id # @return [Symbol,String] the publisher identifier # @api private attr_reader :id # Create a publisher extension with the provided identifier # # @param [Symbol,String] id The identifier # # @return [Publisher] # # @raise PublisherAlreadyRegisteredError # # @api public def self.[](id) raise PublisherAlreadyRegisteredError, id if registry.key?(id) new(id) end # @api private def initialize(id) super() @id = id end # Hook for inclusions/extensions # # It registers the publisher class under global registry using the id # # @api private def included(klass) klass.extend(ClassMethods) klass.include(InstanceMethods) self.class.registry[id] = klass super end # Class interface for publisher classes # # @api public module ClassMethods # Register an event # # @param [String] event_id The event identifier # @param [Hash] payload Optional default payload # # @api public def register_event(event_id, payload = EMPTY_HASH) events[event_id] = Event.new(event_id, payload) self end # Subscribe to an event # # @param [Symbol,String] event_id The event identifier # @param [Hash] filter_hash An optional filter for conditional listeners # # @return [Class] publisher class # # @api public def subscribe(event_id, filter_hash = EMPTY_HASH, &block) listeners[event_id] << [block, Filter.new(filter_hash)] self end # Sets up event bus for publisher instances # # @return [Bus] # # @api private def new_bus Bus.new(events: events.dup, listeners: listeners.dup) end # Global registry with events # # @api private def events @__events__ ||= ::Concurrent::Map.new end # Global registry with listeners # # @api private def listeners @__listeners__ ||= LISTENERS_HASH.dup end end # Instance interface for publishers # # @api public module InstanceMethods # Register a new event type at instance level # # @param [Symbol,String] event_id The event identifier # @param [Hash] payload Optional default payload # # @return [self] # # @api public def register_event(event_id, payload = EMPTY_HASH) __bus__.events[event_id] = Event.new(event_id, payload) self end # Publish an event # # @param [String] event_id The event identifier # @param [Hash] payload An optional payload # # @api public def publish(event_id, payload = EMPTY_HASH) if __bus__.can_handle?(event_id) __bus__.publish(event_id, payload) self else raise UnregisteredEventError, event_id end end alias_method :trigger, :publish # Subscribe to events. # # If the filter parameter is provided, filters events by payload. # # @param [Symbol,String,Object] object_or_event_id The event identifier or a listener object # @param [Hash] filter_hash An optional event filter # # @return [Object] self # # @api public def subscribe(object_or_event_id, filter_hash = EMPTY_HASH, &block) if __bus__.can_handle?(object_or_event_id) filter = Filter.new(filter_hash) if block __bus__.subscribe(object_or_event_id, filter, &block) else __bus__.attach(object_or_event_id, filter) end self else raise InvalidSubscriberError, object_or_event_id end end # Unsubscribe a listener # # @param [Object] listener The listener object # # @return [self] # # @api public def unsubscribe(listener) __bus__.detach(listener) end # Return true if a given listener has been subscribed to any event # # @api public def subscribed?(listener) __bus__.subscribed?(listener) end # Utility method which yields event with each of its listeners # # Listeners are already filtered out when filter was provided during # subscription # # @param [Symbol,String] event_id The event identifier # param [Hash] payload An optional payload # # @api public def process(event_id, payload = EMPTY_HASH, &) __bus__.process(event_id, payload, &) end # Internal event bus # # @return [Bus] # # @api private def __bus__ @__bus__ ||= self.class.new_bus end end end end end
ruby
MIT
719370eb3e259cc2762998b076ceb18beeae9ce7
2026-01-04T17:54:09.241488Z
false
dry-rb/dry-events
https://github.com/dry-rb/dry-events/blob/719370eb3e259cc2762998b076ceb18beeae9ce7/lib/dry/events/constants.rb
lib/dry/events/constants.rb
# frozen_string_literal: true require "concurrent/map" module Dry module Events include ::Dry::Core::Constants LISTENERS_HASH = ::Concurrent::Map.new do |h, k| h.compute_if_absent(k) { [] } end end end
ruby
MIT
719370eb3e259cc2762998b076ceb18beeae9ce7
2026-01-04T17:54:09.241488Z
false
dry-rb/dry-events
https://github.com/dry-rb/dry-events/blob/719370eb3e259cc2762998b076ceb18beeae9ce7/lib/dry/events/bus.rb
lib/dry/events/bus.rb
# frozen_string_literal: true require "dry/events/constants" module Dry module Events # Event bus # # An event bus stores listeners (callbacks) and events # # @api private class Bus # @!attribute [r] events # @return [Hash] A hash with events registered within a bus attr_reader :events # @!attribute [r] listeners # @return [Hash] A hash with event listeners registered within a bus attr_reader :listeners # Initialize a new event bus # # @param [Hash] events A hash with events # @param [Hash] listeners A hash with listeners # # @api private def initialize(events: EMPTY_HASH, listeners: LISTENERS_HASH.dup) @listeners = listeners @events = events end # @api private def process(event_id, payload) listeners[event_id].each do |listener, filter| event = events[event_id].payload(payload) if filter.(payload) yield(event, listener) end end end # @api private def publish(event_id, payload) process(event_id, payload) do |event, listener| listener.(event) end end # @api private def attach(listener, filter) events.each do |id, event| meth = event.listener_method if listener.respond_to?(meth) listeners[id] << [listener.method(meth), filter] end end end # @api private def detach(listener) listeners.each do |id, memo| memo.each do |tuple| current_listener, _ = tuple next unless current_listener.is_a?(Method) listeners[id].delete(tuple) if current_listener.receiver.equal?(listener) end end end # @api private def subscribe(event_id, filter, &block) listeners[event_id] << [block, filter] self end # @api private def subscribed?(listener) listeners.values.any? do |value| value.any? do |block, _| case listener when ::Proc then block.equal?(listener) when ::Method then listener.owner == block.owner && listener.name == block.name end end end end # @api private def can_handle?(object_or_event_id) case object_or_event_id when ::String, ::Symbol events.key?(object_or_event_id) else events .values .map(&:listener_method) .any?(&object_or_event_id.method(:respond_to?)) end end end end end
ruby
MIT
719370eb3e259cc2762998b076ceb18beeae9ce7
2026-01-04T17:54:09.241488Z
false
dry-rb/dry-events
https://github.com/dry-rb/dry-events/blob/719370eb3e259cc2762998b076ceb18beeae9ce7/lib/dry/events/listener.rb
lib/dry/events/listener.rb
# frozen_string_literal: true require "dry/events/publisher" module Dry module Events # Extension for objects that can listen to events # # @example # class AppEvents # include Dry::Events::Publisher[:app] # # register_event("users.created") # end # # class MyListener # include Dry::Events::Listener[:app] # # subscribe("users.created") do |event| # # do something # end # end # # @api public class Listener < ::Module include ::Dry::Equalizer(:id) # @!attribute [r] :id # @return [Symbol,String] The publisher identifier # @api private attr_reader :id # Create a listener extension for a specific publisher # # @return [Module] # # @api public def self.[](id) new(id) end # @api private def initialize(id) super() @id = id define_method(:subscribe) do |event_id, query = EMPTY_HASH, &block| Publisher.registry[id].subscribe(event_id, query, &block) end end # @api private def included(klass) klass.extend(self) super end end end end
ruby
MIT
719370eb3e259cc2762998b076ceb18beeae9ce7
2026-01-04T17:54:09.241488Z
false
soveran/scrivener
https://github.com/soveran/scrivener/blob/0695419ab75a608669741d873c5fa047371b65e0/test/scrivener_test.rb
test/scrivener_test.rb
require File.expand_path("../lib/scrivener", File.dirname(__FILE__)) class A < Scrivener attr_accessor :a attr_accessor :b end scope do test "ignore extra fields" do atts = { :a => 1, :b => 2, :c => 3 } filter = A.new(atts) atts.delete(:c) assert_equal atts, filter.attributes end test "not raise when there are less fields" do atts = { :a => 1 } assert filter = A.new(atts) end test "return attributes" do atts = { :a => 1, :b => 2 } filter = A.new(atts) assert_equal atts, filter.attributes end test "return only the required attributes" do atts = { :a => 1, :b => 2 } filter = A.new(atts) assert_equal filter.slice(:a), { :a => 1 } end end class B < Scrivener attr_accessor :a attr_accessor :b def validate assert_present :a assert_present :b end end scope do test "validations" do atts = { :a => 1, :b => 2 } filter = B.new(atts) assert filter.valid? end test "validation errors" do atts = { :a => 1 } filter = B.new(atts) assert_equal false, filter.valid? assert_equal [], filter.errors[:a] assert_equal [:not_present], filter.errors[:b] end test "attributes without @errors" do atts = { :a => 1, :b => 2 } filter = B.new(atts) filter.valid? assert_equal atts, filter.attributes end end class C include Scrivener::Validations attr_accessor :a def validate assert_present :a end end scope do test "validations without Scrivener" do filter = C.new filter.a = 1 assert filter.valid? filter = C.new assert_equal false, filter.valid? assert_equal [:not_present], filter.errors[:a] end end class D < Scrivener attr_accessor :url, :email def validate assert_url :url assert_email :email end end scope do test "email & url" do filter = D.new({}) assert ! filter.valid? assert_equal [:not_url], filter.errors[:url] assert_equal [:not_email], filter.errors[:email] filter = D.new(url: "google.com", email: "egoogle.com") assert ! filter.valid? assert_equal [:not_url], filter.errors[:url] assert_equal [:not_email], filter.errors[:email] filter = D.new(url: "http://google.com", email: "me@google.com") assert filter.valid? filter = D.new(url: "http://example.versicherung", email: "me@example.versicherung") assert filter.valid? end end class E < Scrivener attr_accessor :a def validate assert_length :a, 3..10 end end scope do test "length validation" do filter = E.new({}) assert ! filter.valid? assert filter.errors[:a].include?(:not_in_range) filter = E.new(a: "fo") assert ! filter.valid? assert filter.errors[:a].include?(:not_in_range) filter = E.new(a: "foofoofoofo") assert ! filter.valid? assert filter.errors[:a].include?(:not_in_range) filter = E.new(a: "foo") assert filter.valid? end end class F < Scrivener attr_accessor :status def validate assert_member :status, %w{pending paid delivered} end end scope do test "member validation" do filter = F.new({}) assert ! filter.valid? assert_equal [:not_valid], filter.errors[:status] filter = F.new(status: "foo") assert ! filter.valid? assert_equal [:not_valid], filter.errors[:status] %w{pending paid delivered}.each do |status| filter = F.new(status: status) assert filter.valid? end end end class G < Scrivener attr_accessor :a def validate assert_decimal :a end end scope do test "decimal validation" do filter = G.new({}) assert ! filter.valid? assert_equal [:not_decimal], filter.errors[:a] %w{10 10.1 10.100000 0.100000 .1000 -10}.each do |a| filter = G.new(a: a) assert filter.valid? end end end class H < Scrivener attr_accessor :a attr_accessor :b def validate assert_equal :a, "foo" assert_equal :b, Integer end end scope do test "equality validation" do filter = H.new({}) assert ! filter.valid? assert filter.errors[:a].include?(:not_equal) assert filter.errors[:b].include?(:not_equal) filter = H.new(a: "foo", b: "bar") assert ! filter.valid? filter = H.new(a: "foo") assert ! filter.valid? assert filter.errors[:a].empty? assert filter.errors[:b].include?(:not_equal) filter = H.new(a: "foo", b: 42) filter.valid? assert filter.valid? end end class Scrivener def assert_filter(att, filter, error = nil) filter = filter.new(send(att)) unless filter.valid? assert(false, error || [att, filter.errors]) end end end class I < Scrivener attr_accessor :name def validate assert_equal :name, "I" end end class J < Scrivener attr_accessor :name attr_accessor :i def validate assert_equal :name, "J" assert_filter :i, I end end scope do test "nested filters" do j1 = J.new(name: "J", i: { name: "I" }) j2 = J.new(name: "J", i: { name: "H" }) assert_equal true, j1.valid? assert_equal false, j2.valid? errors = { i: [{ name: [:not_equal] }] } assert_equal errors, j2.errors end end class K < Scrivener def validate(argument) assert argument == "K", [:k, :not_valid] end end scope do test "passing arguments" do k = K.new({}) assert_equal true, k.valid?("K") assert_equal false, k.valid?("L") errors = { k: [:not_valid] } assert_equal errors, k.errors end end class L < Scrivener def validate(argument, key:) assert argument == "L" && key == "L", [:l, :not_valid] end end scope do test "passing keyword arguments" do l = L.new({}) assert_equal true, l.valid?("L", key: "L") assert_equal false, l.valid?("M", key: "M") errors = { l: [:not_valid] } assert_equal errors, l.errors end end
ruby
MIT
0695419ab75a608669741d873c5fa047371b65e0
2026-01-04T17:54:11.403060Z
false
soveran/scrivener
https://github.com/soveran/scrivener/blob/0695419ab75a608669741d873c5fa047371b65e0/lib/scrivener.rb
lib/scrivener.rb
require_relative "scrivener/validations" class Scrivener VERSION = "1.1.1" include Validations # Initialize with a hash of attributes and values. # Extra attributes are discarded. # # @example # # class EditPost < Scrivener # attr_accessor :title # attr_accessor :body # # def validate # assert_present :title # assert_present :body # end # end # # edit = EditPost.new(title: "Software Tools") # # edit.valid? #=> false # # edit.errors[:title] #=> [] # edit.errors[:body] #=> [:not_present] # # edit.body = "Recommended reading..." # # edit.valid? #=> true # # # Now it's safe to initialize the model. # post = Post.new(edit.attributes) # post.save def initialize(atts) atts.each do |key, val| accessor = "#{key}=" if respond_to?(accessor) send(accessor, val) end end end def _accessors public_methods(false).select do |name| name[-1] == "=" end end # Return hash of attributes and values. def attributes Hash.new.tap do |atts| _accessors.each do |accessor| att = accessor[0..-2].to_sym atts[att] = send(att) end end end def slice(*keys) Hash.new.tap do |atts| keys.each do |att| atts[att] = send(att) end end end end
ruby
MIT
0695419ab75a608669741d873c5fa047371b65e0
2026-01-04T17:54:11.403060Z
false
soveran/scrivener
https://github.com/soveran/scrivener/blob/0695419ab75a608669741d873c5fa047371b65e0/lib/scrivener/validations.rb
lib/scrivener/validations.rb
class Scrivener # Provides a base implementation for extensible validation routines. # {Scrivener::Validations} currently only provides the following assertions: # # * assert # * assert_present # * assert_format # * assert_numeric # * assert_url # * assert_email # * assert_member # * assert_length # * assert_decimal # * assert_equal # # The core tenets that Scrivener::Validations advocates can be summed up in a # few bullet points: # # 1. Validations are much simpler and better done using composition rather # than macros. # 2. Error messages should be kept separate and possibly in the view or # presenter layer. # 3. It should be easy to write your own validation routine. # # Other validations are simply added on a per-model or per-project basis. # # @example # # class Quote # attr_accessor :title # attr_accessor :price # attr_accessor :date # # def validate # assert_present :title # assert_numeric :price # assert_format :date, /\A[\d]{4}-[\d]{1,2}-[\d]{1,2}\z # end # end # # s = Quote.new # s.valid? # # => false # # s.errors # # => { :title => [:not_present], # :price => [:not_numeric], # :date => [:format] } # module Validations # Check if the current model state is valid. Each call to {#valid?} will # reset the {#errors} array. # # All validations should be declared in a `validate` method. # # @example # # class Login # attr_accessor :username # attr_accessor :password # # def validate # assert_present :user # assert_present :password # end # end # def valid?(*args, **kargs) errors.clear validate(*args, **kargs) errors.empty? end # Base validate implementation. Override this method in subclasses. def validate(*args, **kargs) end # Hash of errors for each attribute in this model. def errors @errors ||= Hash.new { |hash, key| hash[key] = [] } end protected # Allows you to do a validation check against a regular expression. # It's important to note that this internally calls {#assert_present}, # therefore you need not structure your regular expression to check # for a non-empty value. # # @param [Symbol] att The attribute you want to verify the format of. # @param [Regexp] format The regular expression with which to compare # the value of att with. # @param [Array<Symbol, Symbol>] error The error that should be returned # when the validation fails. def assert_format(att, format, error = [att, :format]) if assert_present(att, error) assert(send(att).to_s.match(format), error) end end # The most basic and highly useful assertion. Simply checks if the # value of the attribute is empty. # # @param [Symbol] att The attribute you wish to verify the presence of. # @param [Array<Symbol, Symbol>] error The error that should be returned # when the validation fails. def assert_present(att, error = [att, :not_present]) assert(!send(att).to_s.empty?, error) end # Checks if all the characters of an attribute is a digit. # # @param [Symbol] att The attribute you wish to verify the numeric format. # @param [Array<Symbol, Symbol>] error The error that should be returned # when the validation fails. def assert_numeric(att, error = [att, :not_numeric]) if assert_present(att, error) assert_format(att, /\A\-?\d+\z/, error) end end URL = /\A(http|https):\/\/([a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,12}|(2 5[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3} |localhost)(:[0-9]{1,5})?(\/.*)?\z/ix def assert_url(att, error = [att, :not_url]) if assert_present(att, error) assert_format(att, URL, error) end end EMAIL = /\A([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)* [\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+@ ((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+ [a-z]{2,12})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)\z/ix def assert_email(att, error = [att, :not_email]) if assert_present(att, error) assert_format(att, EMAIL, error) end end def assert_member(att, set, err = [att, :not_valid]) assert(set.include?(send(att)), err) end def assert_length(att, range, error = [att, :not_in_range]) if assert_present(att, error) val = send(att).to_s assert range.include?(val.length), error end end DECIMAL = /\A\-?(\d+)?(\.\d+)?\z/ def assert_decimal(att, error = [att, :not_decimal]) assert_format att, DECIMAL, error end # Check that the attribute has the expected value. It uses === for # comparison, so type checks are possible too. Note that in order # to make the case equality work, the check inverts the order of # the arguments: `assert_equal :foo, Bar` is translated to the # expression `Bar === send(:foo)`. # # @example # # def validate # assert_equal :status, "pending" # assert_equal :quantity, Fixnum # end # # @param [Symbol] att The attribute you wish to verify for equality. # @param [Object] value The value you want to test against. # @param [Array<Symbol, Symbol>] error The error that should be returned # when the validation fails. def assert_equal(att, value, error = [att, :not_equal]) assert value === send(att), error end # The grand daddy of all assertions. If you want to build custom # assertions, or even quick and dirty ones, you can simply use this method. # # @example # # class CreatePost # attr_accessor :slug # attr_accessor :votes # # def validate # assert_slug :slug # assert votes.to_i > 0, [:votes, :not_valid] # end # # protected # def assert_slug(att, error = [att, :not_slug]) # assert send(att).to_s =~ /\A[a-z\-0-9]+\z/, error # end # end def assert(value, error) value or errors[error.first].push(error.last) && false end end end
ruby
MIT
0695419ab75a608669741d873c5fa047371b65e0
2026-01-04T17:54:11.403060Z
false
algolia/algoliasearch-jekyll
https://github.com/algolia/algoliasearch-jekyll/blob/cb21e83402de3cea46201fe12bd1b9a2eaacebfb/spec/record_extractor_spec.rb
spec/record_extractor_spec.rb
require 'spec_helper' describe(AlgoliaSearchRecordExtractor) do let(:extractor) { AlgoliaSearchRecordExtractor } let(:site) { get_site } let(:page_file) { extractor.new(site.file_by_name('about.md')) } let(:html_page_file) { extractor.new(site.file_by_name('authors.html')) } let(:post_file) { extractor.new(site.file_by_name('test-post.md')) } let(:hierarchy_page_file) { extractor.new(site.file_by_name('hierarchy.md')) } let(:weight_page_file) { extractor.new(site.file_by_name('weight.md')) } let(:document_file) { extractor.new(site.file_by_name('collection-item.md')) } before(:each) do # Disabling the logs, while still allowing to spy them Jekyll.logger = double('Specific Mock Logger').as_null_object @logger = Jekyll.logger.writer end describe 'metadata' do it 'gets metadata from page' do # Given actual = page_file.metadata # Then expect(actual[:type]).to eq 'page' expect(actual[:slug]).to eq 'about' expect(actual[:title]).to eq 'About page' expect(actual[:url]).to eq '/about.html' expect(actual[:custom]).to eq 'Foo' end it 'gets metadata from post' do # Given actual = post_file.metadata # Then expect(actual[:slug]).to eq 'test-post' expect(actual[:title]).to eq 'Test post' expect(actual[:url]).to eq '/2015/07/02/test-post.html' expect(actual[:posted_at]).to eq 1_435_788_000 expect(actual[:custom]).to eq 'Foo' end it 'gets posted_at timestamp based on the configured timezone' do # Given site = get_site(timezone: 'America/New_York') post_file = extractor.new(site.file_by_name('test-post.md')) actual = post_file.metadata # Then expect(actual[:posted_at]).to eq 1_435_809_600 end it 'gets metadata from document' do # Given actual = document_file.metadata # Then expect(actual[:type]).to eq 'document' expect(actual[:slug]).to eq 'collection-item' expect(actual[:title]).to eq 'Collection Item' expect(actual[:url]).to eq '/my-collection/collection-item.html' expect(actual[:custom]).to eq 'Foo' end if restrict_jekyll_version(more_than: '3.0') describe 'Jekyll > 3.0' do it 'should not throw any deprecation warnings' do # Given # When post_file.metadata # Expect expect(@logger).to_not have_received(:warn) end end end end describe 'slug' do it 'gets it from data if available' do # Given post_file.file.data['slug'] = 'foo' allow(post_file.file).to receive(:respond_to?).with(:slug) do false end # When actual = post_file.slug # Then expect(actual).to eql('foo') end it 'gets it from the root if not in data' do # Given post_file.file.data.delete 'slug' allow(post_file.file).to receive(:slug).and_return('foo') # When actual = post_file.slug # Then expect(actual).to eql('foo') end it 'gets it from the data even if in the root' do # Given post_file.file.data['slug'] = 'foo' allow(post_file.file).to receive(:slug).and_return('bar') # When actual = post_file.slug # Then expect(actual).to eql('foo') end it 'guesses it from the path if not found' do # Given post_file.file.data.delete 'slug' allow(post_file.file).to receive(:respond_to?).with(:slug) do false end allow(post_file.file).to receive(:path) do '/path/to/file/foo.html' end # When actual = post_file.slug # # Then expect(actual).to eql('foo') end end describe 'tags' do it 'returns tags in data if available' do # Given post_file.file.data['tags'] = %w(foo bar) allow(post_file.file).to receive(:respond_to?).with(:tags) do false end # When actual = post_file.tags # Then expect(actual).to include('foo', 'bar') end it 'returns tags at the root if not in data' do # Given post_file.file.data.delete 'tags' allow(post_file.file).to receive(:tags).and_return(%w(foo bar)) # When actual = post_file.tags # Then expect(actual).to include('foo', 'bar') end it 'returns tags in data even if in root' do # Given post_file.file.data['tags'] = %w(foo bar) allow(post_file.file).to receive(:tags).and_return(%w(js css)) # When actual = post_file.tags # Then expect(actual).to include('foo', 'bar') end it 'parses tags as string if they are another type' do # Given tag_foo = double('Extended Tag', to_s: 'foo') tag_bar = double('Extended Tag', to_s: 'bar') post_file.file.data['tags'] = [tag_foo, tag_bar] allow(post_file.file).to receive(:respond_to?).with(:tags) do false end # When actual = post_file.tags # Then expect(actual).to include('foo', 'bar') end it 'extract tags from front matter' do # Given actual = post_file.tags # Then expect(actual).to include('tag', 'another tag') end end describe 'html_nodes' do it 'returns the list of all <p> by default' do expect(page_file.html_nodes.size).to eq 6 end it 'allow _config.yml to override the selector' do # Given site = get_site(algolia: { 'record_css_selector' => 'p,ul' }) page_file = extractor.new(site.file_by_name('about.md')) expect(page_file.html_nodes.size).to eq 7 end end describe 'node_heading_parent' do it 'returns the direct heading right above' do # Given nodes = hierarchy_page_file.html_nodes p = nodes[0] # When actual = hierarchy_page_file.node_heading_parent(p) # Then expect(actual.name).to eq 'h1' expect(actual.text).to eq 'H1' end it 'returns the closest heading even if in a sub tag' do # Given nodes = hierarchy_page_file.html_nodes p = nodes[2] # When actual = hierarchy_page_file.node_heading_parent(p) # Then expect(actual.name).to eq 'h2' expect(actual.text).to eq 'H2A' end it 'should automatically go up one level when indexing headings' do # Given site = get_site(algolia: { 'record_css_selector' => 'p,h2' }) hierarchy_page_file = extractor.new(site.file_by_name('hierarchy.md')) nodes = hierarchy_page_file.html_nodes h2 = nodes[4] # When actual = hierarchy_page_file.node_heading_parent(h2) # Then expect(actual.name).to eq 'h1' expect(actual.text).to eq 'H1' end it 'should find the correct parent when indexing deep headings' do # Given site = get_site(algolia: { 'record_css_selector' => 'h2' }) hierarchy_page_file = extractor.new(site.file_by_name('hierarchy.md')) nodes = hierarchy_page_file.html_nodes h2 = nodes[2] # When actual = hierarchy_page_file.node_heading_parent(h2) # Then expect(actual.name).to eq 'h1' expect(actual.text).to eq 'H1' end end describe 'node_hierarchy' do it 'returns the unique parent of a simple element' do # Note: First <p> should only have a h1 as hierarchy # Given nodes = hierarchy_page_file.html_nodes p = nodes[0] # When actual = hierarchy_page_file.node_hierarchy(p) # Then expect(actual).to include(h1: 'H1') end it 'returns the heading hierarchy of multiple headings' do # Note: 5th <p> is inside h3, second h2 and main h1 # Given nodes = hierarchy_page_file.html_nodes p = nodes[4] # When actual = hierarchy_page_file.node_hierarchy(p) # Then expect(actual).to include(h1: 'H1', h2: 'H2B', h3: 'H3A') end it 'works even if heading not on the same level' do # Note: The 6th <p> is inside a div # Given nodes = hierarchy_page_file.html_nodes p = nodes[5] # When actual = hierarchy_page_file.node_hierarchy(p) # Then expect(actual).to include(h1: 'H1', h2: 'H2B', h3: 'H3A', h4: 'H4') end it 'includes node in the output if headings are indexed' do # Given site = get_site(algolia: { 'record_css_selector' => 'h1' }) hierarchy_page_file = extractor.new(site.file_by_name('hierarchy.md')) nodes = hierarchy_page_file.html_nodes h1 = nodes[0] # When actual = hierarchy_page_file.node_hierarchy(h1) # Then expect(actual).to include(h1: 'H1') end it 'escape html in headings' do # Given nodes = hierarchy_page_file.html_nodes p = nodes[7] # When actual = hierarchy_page_file.node_hierarchy(p) # Then expect(actual).to include(h3: 'H3B &lt;code&gt;') end end describe 'node_raw_html' do it 'returns html including surrounding tags' do # Note: 3rd <p> is a real HTML with a custom class # Given nodes = page_file.html_nodes p = nodes[3] # When actual = page_file.node_raw_html(p) # Then expect(actual).to eq '<p id="text4">Another text 4</p>' end end describe 'node_text' do it 'returns inner text with <> escaped' do # Note: 4th <p> contains a <code> tag with <> # Given nodes = page_file.html_nodes p = nodes[4] # When actual = page_file.node_text(p) # Then expect(actual).to eq 'Another &lt;text&gt; 5' end end describe 'unique_hierarchy' do it 'combines title and headings' do # Given hierarchy = { title: 'title', h1: 'h1', h2: 'h2', h3: 'h3', h4: 'h4', h5: 'h5', h6: 'h6' } # When actual = page_file.unique_hierarchy(hierarchy) # Then expect(actual).to eq 'title > h1 > h2 > h3 > h4 > h5 > h6' end it 'combines title and headings even with missing elements' do # Given hierarchy = { title: 'title', h2: 'h2', h4: 'h4', h6: 'h6' } # When actual = page_file.unique_hierarchy(hierarchy) # Then expect(actual).to eq 'title > h2 > h4 > h6' end end describe 'node_css_selector' do it 'uses the #id to make the selector more precise if one is found' do # Given nodes = page_file.html_nodes p = nodes[3] # When actual = page_file.node_css_selector(p) # Then expect(actual).to eq '#text4' end it 'uses p:nth-of-type if no #id found' do # Given nodes = page_file.html_nodes p = nodes[2] # When actual = page_file.node_css_selector(p) # Then expect(actual).to eq 'p:nth-of-type(3)' end it 'handles custom <div> markup' do # Given nodes = page_file.html_nodes p = nodes[5] # When actual = page_file.node_css_selector(p) # Then expect(actual).to eq 'div:nth-of-type(2) > p' end end describe 'weight_heading_relevance' do it 'gets the number of words in text also in the title' do # Given data = { title: 'foo bar', text: 'Lorem ipsum dolor foo bar, consectetur adipiscing elit' } # When actual = page_file.weight_heading_relevance(data) # Then expect(actual).to eq 2 end it 'gets the number of words in text also in the headings' do # Given data = { title: 'foo', h1: 'bar', h2: 'baz', text: 'Lorem baz dolor foo bar, consectetur adipiscing elit' } # When actual = page_file.weight_heading_relevance(data) # Then expect(actual).to eq 3 end it 'count each word only once' do # Given data = { title: 'foo', h1: 'foo foo foo', h2: 'bar bar foo bar', text: 'foo bar bar bar bar baz foo bar baz' } # When actual = page_file.weight_heading_relevance(data) # Then expect(actual).to eq 2 end it 'is case-insensitive' do # Given data = { title: 'FOO', h1: 'bar Bar BAR', text: 'foo BAR' } # When actual = page_file.weight_heading_relevance(data) # Then expect(actual).to eq 2 end it 'should only use words, no partial matches' do # Given data = { title: 'foo bar', text: 'xxxfooxxx bar' } # When actual = page_file.weight_heading_relevance(data) # Then expect(actual).to eq 1 end it 'should still work with non-string keys' do # Given data = { title: nil, h1: [], h2: {}, h3: true, h4: false, h5: 'foo bar', text: 'foo bar' } # When actual = page_file.weight_heading_relevance(data) # Then expect(actual).to eq 2 end end describe 'weight_tag_name' do it 'gives a score of 0 to non-headings' do # Given data = { tag_name: 'p' } # When actual = page_file.weight_tag_name(data) # Then expect(actual).to eq 0 end it 'gives a score of 100 to h1' do # Given data = { tag_name: 'h1' } # When actual = page_file.weight_tag_name(data) # Then expect(actual).to eq 100 end it 'gives a score of 40 to h6' do # Given data = { tag_name: 'h6' } # When actual = page_file.weight_tag_name(data) # Then expect(actual).to eq 50 end end describe 'weight' do it 'returns an object with all weights' do # Given item = { tag_name: 'p' } allow(page_file).to receive(:weight_tag_name) { 10 } allow(page_file).to receive(:weight_heading_relevance) { 20 } # When actual = page_file.weight(item, 42) # Then expect(actual).to include(tag_name: 10) expect(actual).to include(heading_relevance: 20) expect(actual).to include(position: 42) end end describe 'custom_hook_each' do it 'let the user call a custom hook to modify a record' do # Given def page_file.custom_hook_each(item, _) item[:custom_attribute] = 'foo' item end # When actual = page_file.extract # Then expect(actual[0]).to include(custom_attribute: 'foo') end it 'let the user discard a record by returning nil' do # Given def page_file.custom_hook_each(_, _) nil end # When actual = page_file.extract # Then expect(actual.size).to eq 0 end end describe 'custom_hook_all' do it 'let the user call a custom hook to modify the list of records' do # Given def page_file.custom_hook_all(items) [items[0], { foo: 'bar' }] end # When actual = page_file.extract # Then expect(actual.size).to eq 2 expect(actual[1]).to include(foo: 'bar') end end end
ruby
MIT
cb21e83402de3cea46201fe12bd1b9a2eaacebfb
2026-01-04T17:53:57.372095Z
false
algolia/algoliasearch-jekyll
https://github.com/algolia/algoliasearch-jekyll/blob/cb21e83402de3cea46201fe12bd1b9a2eaacebfb/spec/spec_helper_simplecov.rb
spec/spec_helper_simplecov.rb
require 'simplecov' SimpleCov.configure do load_profile 'test_frameworks' end ENV['COVERAGE'] && SimpleCov.start do add_filter '/.rvm/' end
ruby
MIT
cb21e83402de3cea46201fe12bd1b9a2eaacebfb
2026-01-04T17:53:57.372095Z
false
algolia/algoliasearch-jekyll
https://github.com/algolia/algoliasearch-jekyll/blob/cb21e83402de3cea46201fe12bd1b9a2eaacebfb/spec/credential_checker_spec.rb
spec/credential_checker_spec.rb
require 'spec_helper' describe(AlgoliaSearchCredentialChecker) do let(:config) do { 'source' => fixture_path, 'markdown_ext' => 'md,mkd', 'algolia' => { 'application_id' => 'APPID', 'index_name' => 'INDEXNAME' } } end let(:checker) { AlgoliaSearchCredentialChecker.new(config) } describe 'api_key' do it 'returns nil if no key found' do # Given # When actual = checker.api_key # Then expect(actual).to be_nil end it 'reads from ENV var if set' do # Given stub_const('ENV', 'ALGOLIA_API_KEY' => 'APIKEY_FROM_ENV') # When actual = checker.api_key # Then expect(actual).to eq 'APIKEY_FROM_ENV' end it 'reads from _algolia_api_key in source if set' do # Given checker.config['source'] = File.join(config['source'], 'api_key_dir') # When actual = checker.api_key # Then expect(actual).to eq 'APIKEY_FROM_FILE' end it 'reads from ENV before from file' do # Given checker.config['source'] = File.join(config['source'], 'api_key_dir') stub_const('ENV', 'ALGOLIA_API_KEY' => 'APIKEY_FROM_ENV') # When actual = checker.api_key # Then expect(actual).to eq 'APIKEY_FROM_ENV' end end describe 'check_api_key' do it 'should exit with error if no API key' do # Given allow(checker).to receive(:api_key).and_return(nil) allow(checker.logger).to receive(:display) # When / Then expect(-> { checker.check_api_key }).to raise_error SystemExit end it 'should do nothing when an API key is found' do # Given allow(checker).to receive(:api_key).and_return('APIKEY') # When / Then expect(-> { checker.check_api_key }).not_to raise_error end end describe 'application_id' do it 'reads value from the _config.yml file' do # Given # When actual = checker.application_id # Then expect(actual).to eq 'APPID' end it 'reads from ENV var if set' do # Given stub_const('ENV', 'ALGOLIA_APPLICATION_ID' => 'APPLICATION_ID_FROM_ENV') # When actual = checker.application_id # Then expect(actual).to eq 'APPLICATION_ID_FROM_ENV' end it 'returns nil if no key found' do # Given config['algolia']['application_id'] = nil # When actual = checker.application_id # Then expect(actual).to be_nil end end describe 'check_application_id' do it 'should exit with error if no application ID' do # Given allow(checker).to receive(:application_id).and_return(nil) allow(checker.logger).to receive(:display) # When / Then expect(-> { checker.check_application_id }).to raise_error SystemExit end it 'should do nothing when an application ID is found' do # Given allow(checker).to receive(:application_id).and_return('APPLICATIONID') # When / Then expect(-> { checker.check_application_id }).not_to raise_error end end describe 'index_name' do it 'reads value from the _config.yml file' do # Given # When actual = checker.index_name # Then expect(actual).to eq 'INDEXNAME' end it 'reads from ENV var if set' do # Given stub_const('ENV', 'ALGOLIA_INDEX_NAME' => 'INDEX_NAME_FROM_ENV') # When actual = checker.index_name # Then expect(actual).to eq 'INDEX_NAME_FROM_ENV' end it 'returns nil if no key found' do # Given config['algolia']['index_name'] = nil # When actual = checker.index_name # Then expect(actual).to be_nil end end describe 'check_index_name' do it 'should exit with error if no index name' do # Given allow(checker).to receive(:index_name).and_return(nil) allow(checker.logger).to receive(:display) # When / Then expect(-> { checker.check_index_name }).to raise_error SystemExit end it 'should do nothing when an index name is found' do # Given allow(checker).to receive(:index_name).and_return('INDEXNAME') # When / Then expect(-> { checker.check_index_name }).not_to raise_error end end describe 'assert_valid' do before(:each) do allow(checker.logger).to receive(:display) end it 'should display error if no api key' do # Given allow(checker).to receive(:api_key).and_return nil # Then expect(-> { checker.assert_valid }).to raise_error SystemExit expect(checker.logger).to have_received(:display).with('api_key_missing') end it 'should display error if no application id' do # Given checker.config['algolia'] = { 'application_id' => nil, 'index_name' => 'INDEX_NAME' } stub_const('ENV', 'ALGOLIA_API_KEY' => 'APIKEY_FROM_ENV') # Then expect(-> { checker.assert_valid }).to raise_error SystemExit expect(checker.logger) .to have_received(:display) .with('application_id_missing') end it 'should display error if no index name' do # Given checker.config['algolia'] = { 'application_id' => 'APPLICATION_ID', 'index_name' => nil } stub_const('ENV', 'ALGOLIA_API_KEY' => 'APIKEY_FROM_ENV') # Then expect(-> { checker.assert_valid }).to raise_error SystemExit expect(checker.logger) .to have_received(:display) .with('index_name_missing') end it 'should init the Algolia client' do # Given allow(checker).to receive(:application_id).and_return('FOO') allow(checker).to receive(:api_key).and_return('BAR') allow(Algolia).to receive(:init) # When checker.assert_valid # Then expect(Algolia).to have_received(:init).with( application_id: 'FOO', api_key: 'BAR' ) end end end
ruby
MIT
cb21e83402de3cea46201fe12bd1b9a2eaacebfb
2026-01-04T17:53:57.372095Z
false
algolia/algoliasearch-jekyll
https://github.com/algolia/algoliasearch-jekyll/blob/cb21e83402de3cea46201fe12bd1b9a2eaacebfb/spec/error_handler_spec.rb
spec/error_handler_spec.rb
require 'spec_helper' describe(AlgoliaSearchErrorHandler) do before(:each) do @error_handler = AlgoliaSearchErrorHandler.new end describe 'display' do before(:each) do allow(Jekyll.logger).to receive(:error) allow(Jekyll.logger).to receive(:warn) end it 'should display first line as error' do # Given input = 'sample' # When @error_handler.display(input) # Then expect(Jekyll.logger).to have_received(:error).exactly(1).times end it 'should display all other lines as warnings' do # Given input = 'sample' # When @error_handler.display(input) # Then expect(Jekyll.logger).to have_received(:warn).exactly(3).times end end describe 'parse_algolia_error' do before(:each) do @algolia_error = 'Cannot PUT to ' \ 'https://appid.algolia.net/1/indexes/index_name/settings: ' \ '{"message":"Invalid Application-ID or API key","status":403} (403)' end it 'should extract all the url parts' do # Given input = @algolia_error # When actual = @error_handler.parse_algolia_error(input) # Then expect(actual['verb']).to eq 'PUT' expect(actual['scheme']).to eq 'https' expect(actual['app_id']).to eq 'appid' expect(actual['api_section']).to eq 'indexes' expect(actual['index_name']).to eq 'index_name' expect(actual['api_action']).to eq 'settings' end it 'should cast integers to integers' do # Given input = @algolia_error # When actual = @error_handler.parse_algolia_error(input) # Then expect(actual['api_version']).to eq 1 expect(actual['http_error']).to eq 403 end it 'should parse the JSON part' do # Given input = @algolia_error # When actual = @error_handler.parse_algolia_error(input) # Then expect(actual['json']).to be_a(Hash) expect(actual['json']['status']).to eq 403 end it 'should return false if this is not parsable' do # Given input = 'foo bar baz' # When actual = @error_handler.parse_algolia_error(input) # Then expect(actual).to eq(false) end it 'should work on multiline errors' do # Given input = @algolia_error.gsub('}', "}\n") # When actual = @error_handler.parse_algolia_error(input) # Then expect(actual).to be_a(Hash) expect(actual['http_error']).to eq 403 end end describe 'readable_algolia_error' do it 'should warn about key ACL' do # Given parsed = { 'http_error' => 403, 'index_name' => 'something_tmp' } allow(@error_handler).to receive(:parse_algolia_error).and_return(parsed) # When actual = @error_handler.readable_algolia_error('error') # Then expect(actual).to eq('check_key_acl_to_tmp_index') end it 'should return false if no nice message found' do # Given parsed = false allow(@error_handler).to receive(:parse_algolia_error).and_return(parsed) # When actual = @error_handler.readable_algolia_error('error') # Then expect(actual).to eq(false) end it 'should return false if message does not match any known case' do # Given parsed = { 'http_error' => 42 } allow(@error_handler).to receive(:parse_algolia_error).and_return(parsed) # When actual = @error_handler.readable_algolia_error('error') # Then expect(actual).to eq(false) end end end
ruby
MIT
cb21e83402de3cea46201fe12bd1b9a2eaacebfb
2026-01-04T17:53:57.372095Z
false
algolia/algoliasearch-jekyll
https://github.com/algolia/algoliasearch-jekyll/blob/cb21e83402de3cea46201fe12bd1b9a2eaacebfb/spec/push_spec.rb
spec/push_spec.rb
require 'spec_helper' describe(AlgoliaSearchJekyllPush) do let(:push) { AlgoliaSearchJekyllPush } let(:site) { get_site } let(:page_file) { site.file_by_name('about.md') } let(:html_page_file) { site.file_by_name('authors.html') } let(:excluded_page_file) { site.file_by_name('excluded.html') } let(:post_file) { site.file_by_name('2015-07-02-test-post.md') } let(:static_file) { site.file_by_name('ring.png') } let(:document_file) { site.file_by_name('collection-item.md') } let(:html_document_file) { site.file_by_name('collection-item.html') } let(:pagination_page) { site.file_by_name('page2/index.html') } let(:items) do [{ name: 'foo', url: '/foo' }, { name: 'bar', url: '/bar' }] end describe 'init_options' do it 'sets options and config' do # Given args = nil options = { 'foo' => 'bar' } config = { 'bar' => 'foo' } # When push.init_options(args, options, config) # Then expect(push.options).to include(options) expect(push.config).to include(config) end end describe 'indexable?' do it 'exclude StaticFiles' do expect(push.indexable?(static_file)).to eq false end it 'keeps markdown files' do expect(push.indexable?(page_file)).to eq true end it 'keeps html files' do expect(push.indexable?(html_page_file)).to eq true end it 'keeps markdown documents' do expect(push.indexable?(document_file)).to eq true end it 'keeps html documents' do expect(push.indexable?(html_document_file)).to eq true end it 'exclude file specified in config' do expect(push.indexable?(excluded_page_file)).to eq false end it 'does not index pagination pages' do expect(push.indexable?(pagination_page)).to eq false end end describe 'excluded_files?' do before(:each) do push.init_options(nil, {}, site.config) end it 'should not exclude normal pages' do expect(push.excluded_file?(html_page_file)).to eq false end it 'should alway exclude pagination pages' do expect(push.excluded_file?(pagination_page)).to eq true end it 'should exclude user specified strings' do expect(push.excluded_file?(excluded_page_file)).to eq true end end describe 'custom_hook_excluded_file?' do it 'let the user call a custom hook to exclude some files' do # Given def push.custom_hook_excluded_file?(_file) true end # Then expect(push.excluded_file?(html_page_file)).to eq true end end describe 'configure_index' do it 'sets some sane defaults' do # Given push.init_options(nil, {}, {}) index = double # Then expected = { attributeForDistinct: 'url', distinct: true, customRanking: [ 'desc(posted_at)', 'desc(weight.tag_name)', 'asc(weight.position)' ] } expect(index).to receive(:set_settings).with(hash_including(expected)) # When push.configure_index(index) end it 'allow user to override all settings' do # Given settings = { distinct: false, customSetting: 'foo', customRanking: ['asc(foo)', 'desc(bar)'] } config = { 'algolia' => { 'settings' => settings } } push.init_options(nil, {}, config) index = double # Then expect(index).to receive(:set_settings).with(hash_including(settings)) # When push.configure_index(index) end describe 'throw an error' do before(:each) do @index_double = double('Algolia Index').as_null_object @error_handler_double = double('Error Handler double').as_null_object push.init_options(nil, {}, {}) allow(@index_double).to receive(:set_settings).and_raise allow(Jekyll.logger).to receive(:error) end it 'stops if API throw an error' do # Given # When # Then expect(-> { push.configure_index(@index_double) }) .to raise_error SystemExit end it 'displays the error directly if unknown' do # Given allow(@error_handler_double) .to receive(:readable_algolia_error).and_return false allow(@error_handler_double) .to receive(:display) allow(AlgoliaSearchErrorHandler) .to receive(:new).and_return(@error_handler_double) # When # Then expect(-> { push.configure_index(@index_double) }) .to raise_error SystemExit expect(@error_handler_double) .to have_received(:display).exactly(0).times expect(Jekyll.logger) .to have_received(:error).with('Algolia Error: HTTP Error') end it 'display a human readable version of the error if one is found' do # Given allow(@error_handler_double) .to receive(:readable_algolia_error).and_return 'known_errors' allow(@error_handler_double) .to receive(:display) allow(AlgoliaSearchErrorHandler) .to receive(:new).and_return(@error_handler_double) # When # Then expect(-> { push.configure_index(@index_double) }) .to raise_error SystemExit expect(@error_handler_double) .to have_received(:display) .exactly(1).times .with('known_errors') end end end describe 'jekyll_new' do it 'should return a patched version of site with a custom write' do # Given normal_site = Jekyll::Site.new(Jekyll.configuration) normal_method = normal_site.method(:write).source_location patched_site = get_site({}, mock_write_method: false, process: false) patched_method = patched_site.method(:write).source_location # When # Then expect(patched_method).not_to eq normal_method end end describe 'process' do it 'should call the site write method' do # Given site = get_site({}, process: false) # When site.process # Then expect(site).to have_received(:write) end it 'should push items to Algolia' do # Given site = get_site({}, mock_write_method: false, process: false) # Keep only page_file allow(AlgoliaSearchJekyllPush).to receive(:indexable?) do |file| file.path == page_file.path end allow(AlgoliaSearchJekyllPush).to receive(:push) # When site.process # Then expect(AlgoliaSearchJekyllPush).to have_received(:push) do |arg| expect(arg.size).to eq 6 end end end describe 'set_user_agent_header' do before(:each) do allow(Algolia).to receive(:set_extra_header) end it 'should set a User-Agent with the plugin name and version' do # Given allow(AlgoliaSearchJekyllVersion).to receive(:to_s).and_return '99.42' # When push.set_user_agent_header # Then expect(Algolia).to have_received(:set_extra_header).with( 'User-Agent', /Jekyll(.*)99.42/ ) end end describe 'push' do let(:index_double) { double('Algolia Index').as_null_object } let(:config) do { 'algolia' => { 'index_name' => 'INDEXNAME' } } end before(:each) do push.init_options(nil, {}, config) # Mock all calls to not send anything allow_any_instance_of(AlgoliaSearchCredentialChecker) .to receive(:assert_valid) allow(Algolia).to receive(:set_extra_header) allow(Algolia).to receive(:init) allow(Algolia).to receive(:move_index) allow(Algolia::Index).to receive(:new).and_return(index_double) allow(Jekyll.logger).to receive(:info) end it 'should create a temporary index' do # Given # When push.push(items) # Then expect(Algolia::Index).to have_received(:new).with('INDEXNAME_tmp') end it 'should add elements to the temporary index' do # Given # When push.push(items) # Then expect(index_double).to have_received(:add_objects!) end it 'should move the temporary index as the main one' do # Given # When push.push(items) # Then expect(Algolia).to have_received(:move_index) .with('INDEXNAME_tmp', 'INDEXNAME') end it 'should display the number of elements indexed' do # Given # When push.push(items) # Then expect(Jekyll.logger).to have_received(:info).with(/of 2 items/i) end it 'should display an error if `add_objects!` failed' do allow(index_double).to receive(:add_objects!).and_raise expect(Jekyll.logger).to receive(:error) expect(-> { push.push(items) }).to raise_error SystemExit end end end
ruby
MIT
cb21e83402de3cea46201fe12bd1b9a2eaacebfb
2026-01-04T17:53:57.372095Z
false
algolia/algoliasearch-jekyll
https://github.com/algolia/algoliasearch-jekyll/blob/cb21e83402de3cea46201fe12bd1b9a2eaacebfb/spec/spec_helper.rb
spec/spec_helper.rb
if ENV['TRAVIS'] require 'coveralls' Coveralls.wear! end require 'awesome_print' require 'jekyll' require_relative './spec_helper_simplecov.rb' require './lib/push.rb' RSpec.configure do |config| config.filter_run(focus: true) config.fail_fast = true config.run_all_when_everything_filtered = true end # Disabling the logs Jekyll.logger.log_level = :error # Create a Jekyll::Site instance, patched with a `file_by_name` method def get_site(config = {}, options = {}) default_options = { mock_write_method: true, process: true } options = default_options.merge(options) config = config.merge( 'source' => fixture_path ) config = Jekyll.configuration(config) site = AlgoliaSearchJekyllPush.init_options({}, options, config) .jekyll_new(config) def site.file_by_name(file_name) each_site_file do |file| return file if file.path =~ /#{file_name}$/ end nil end allow(site).to receive(:write) if options[:mock_write_method] site.process if options[:process] site end # Return the fixture path, according to the current Jekyll version being tested def fixture_path jekyll_version = Jekyll::VERSION[0] fixture_path = "./spec/fixtures/jekyll_version_#{jekyll_version}" File.expand_path(fixture_path) end # Check the current Jekyll version def restrict_jekyll_version(more_than: nil, less_than: nil) jekyll_version = Gem::Version.new(Jekyll::VERSION) minimum_version = Gem::Version.new(more_than) maximum_version = Gem::Version.new(less_than) return false if !more_than.nil? && jekyll_version < minimum_version return false if !less_than.nil? && jekyll_version > maximum_version true end
ruby
MIT
cb21e83402de3cea46201fe12bd1b9a2eaacebfb
2026-01-04T17:53:57.372095Z
false
algolia/algoliasearch-jekyll
https://github.com/algolia/algoliasearch-jekyll/blob/cb21e83402de3cea46201fe12bd1b9a2eaacebfb/lib/version.rb
lib/version.rb
# Expose gem version class AlgoliaSearchJekyllVersion def self.to_s '0.9.1' end end
ruby
MIT
cb21e83402de3cea46201fe12bd1b9a2eaacebfb
2026-01-04T17:53:57.372095Z
false
algolia/algoliasearch-jekyll
https://github.com/algolia/algoliasearch-jekyll/blob/cb21e83402de3cea46201fe12bd1b9a2eaacebfb/lib/error_handler.rb
lib/error_handler.rb
require 'json' require 'verbal_expressions' # Helps in displaying useful error messages to users, to help them debug their # issues class AlgoliaSearchErrorHandler # Will output the specified error file. # First line is displayed as error, next ones as warning def display(file) file = File.expand_path(File.join(File.dirname(__FILE__), '../txt', file)) content = File.open(file).readlines.map(&:chomp) content.each_with_index do |line, index| if index == 0 Jekyll.logger.error line next end Jekyll.logger.warn line end end def error_tester # Ex: Cannot PUT to https://appid.algolia.net/1/indexes/index_name/settings: # {"message":"Invalid Application-ID or API key","status":403} (403) VerEx.new do find 'Cannot ' capture('verb') { word } find ' to ' capture('scheme') { word } find '://' capture('app_id') { word } anything_but '/' find '/' capture('api_version') { digit } find '/' capture('api_section') { word } find '/' capture('index_name') { word } find '/' capture('api_action') { word } find ': ' capture('json') do find '{' anything_but('}') find '}' end find ' (' capture('http_error') { word } find ')' end end def parse_algolia_error(error) error.delete!("\n") tester = error_tester matches = tester.match(error) return false unless matches hash = {} matches.names.each do |match| hash[match] = matches[match] end # Cast integers hash['api_version'] = hash['api_version'].to_i hash['http_error'] = hash['http_error'].to_i # Parse JSON hash['json'] = JSON.parse(hash['json']) hash end # Given an Algolia API error message, will return the best error message def readable_algolia_error(error) error = parse_algolia_error(error) return false unless error # Given API key does not have rights on the _tmp index if error['http_error'] == 403 && error['index_name'] =~ /_tmp$/ return 'check_key_acl_to_tmp_index' end false end end
ruby
MIT
cb21e83402de3cea46201fe12bd1b9a2eaacebfb
2026-01-04T17:53:57.372095Z
false
algolia/algoliasearch-jekyll
https://github.com/algolia/algoliasearch-jekyll/blob/cb21e83402de3cea46201fe12bd1b9a2eaacebfb/lib/credential_checker.rb
lib/credential_checker.rb
require 'algoliasearch' require 'nokogiri' require 'json' require_relative './error_handler.rb' # Given an HTML file as input, will return an array of records to index class AlgoliaSearchCredentialChecker attr_accessor :config, :logger def initialize(config) @config = config @logger = AlgoliaSearchErrorHandler.new end # Read the API key either from ENV or from an _algolia_api_key file in # source folder def api_key # First read in ENV return ENV['ALGOLIA_API_KEY'] if ENV['ALGOLIA_API_KEY'] # Otherwise from file in source directory key_file = File.join(@config['source'], '_algolia_api_key') if File.exist?(key_file) && File.size(key_file) > 0 return File.open(key_file).read.strip end nil end # Read key either from ENV or _config.yml def get_key(env_name, config_key) # First read in ENV return ENV[env_name] if ENV[env_name] # Otherwise read from _config.yml if @config['algolia'] && @config['algolia'][config_key] return @config['algolia'][config_key] end nil end # Read the application id either from the config file or from ENV def application_id get_key('ALGOLIA_APPLICATION_ID', 'application_id') end # Read the index name either from the config file or from ENV def index_name get_key('ALGOLIA_INDEX_NAME', 'index_name') end # Check that the API key is available def check_api_key return if api_key @logger.display('api_key_missing') exit 1 end # Check that the application id is defined def check_application_id return if application_id @logger.display('application_id_missing') exit 1 end # Check that the index name is defined def check_index_name return if index_name @logger.display('index_name_missing') exit 1 end # Check that all credentials are present # Stop with a helpful message if not def assert_valid check_api_key check_application_id check_index_name Algolia.init( application_id: application_id, api_key: api_key ) nil end end
ruby
MIT
cb21e83402de3cea46201fe12bd1b9a2eaacebfb
2026-01-04T17:53:57.372095Z
false
algolia/algoliasearch-jekyll
https://github.com/algolia/algoliasearch-jekyll/blob/cb21e83402de3cea46201fe12bd1b9a2eaacebfb/lib/push.rb
lib/push.rb
require 'algoliasearch' require 'nokogiri' require 'json' require_relative './version' require_relative './record_extractor' require_relative './credential_checker' require_relative './error_handler' # `jekyll algolia push` command class AlgoliaSearchJekyllPush < Jekyll::Command class << self attr_accessor :options, :config def init_with_program(_prog) end # Init the command with options passed on the command line # `jekyll algolia push ARG1 ARG2 --OPTION_NAME1 OPTION_VALUE1` # config comes from _config.yml def init_options(args = [], options = {}, config = {}) args = [] unless args @args = args @options = options @config = config @is_verbose = @config['verbose'] @is_dry_run = @config['dry_run'] self end # Check if the specified file should be indexed (we exclude static files, # robots.txt and custom defined exclusions). def indexable?(file) return false if file.is_a?(Jekyll::StaticFile) basename = File.basename(file.path) extname = File.extname(basename)[1..-1] # Keep only markdown and html files allowed_extensions = %w(html) if @config['markdown_ext'] allowed_extensions += @config['markdown_ext'].split(',') end if @config['algolia'] allowed_extensions += (@config['algolia']['allowed_extensions'] || []) end return false unless allowed_extensions.include?(extname) return false if excluded_file?(file) true end # Check if the file is in the list of excluded files def excluded_file?(file) excluded = [ %r{^page([0-9]*)/index\.html} ] if @config['algolia'] excluded += (@config['algolia']['excluded_files'] || []) end # Exclude files explicitly excluded in _config excluded.each do |pattern| pattern = /#{Regexp.quote(pattern)}/ if pattern.is_a? String return true if file.path =~ pattern end # Call user custom exclude hook on remaining files return true if custom_hook_excluded_file?(file) false end # User custom method to exclude some files when algolia.excluded_files is # not enough def custom_hook_excluded_file?(_file) false end # Return a patched version of a Jekyll instance def jekyll_new(config) site = Jekyll::Site.new(config) # Patched version of `write` that will push to Algolia instead of writing # on disk def site.write items = [] is_verbose = config['verbose'] each_site_file do |file| next unless AlgoliaSearchJekyllPush.indexable?(file) Jekyll.logger.info "Extracting data from #{file.path}" if is_verbose new_items = AlgoliaSearchRecordExtractor.new(file).extract next if new_items.nil? ap new_items if is_verbose items += new_items end AlgoliaSearchJekyllPush.push(items) end site end # Get index settings def configure_index(index) settings = { distinct: true, attributeForDistinct: 'url', attributesForFaceting: %w(tags type title), attributesToIndex: %w( title h1 h2 h3 h4 h5 h6 unordered(text) unordered(tags) ), attributesToRetrieve: nil, customRanking: [ 'desc(posted_at)', 'desc(weight.tag_name)', 'asc(weight.position)' ], highlightPreTag: '<span class="algolia__result-highlight">', highlightPostTag: '</span>' } # Merge default settings with user custom ones if @config['algolia'] (@config['algolia']['settings'] || []).each do |key, value| settings[key.to_sym] = value end end begin index.set_settings(settings) rescue StandardError => error display_error(error) exit 1 end end # Display the error in a human-friendly way if possible def display_error(error) error_handler = AlgoliaSearchErrorHandler.new readable_error = error_handler.readable_algolia_error(error.message) if readable_error error_handler.display(readable_error) else Jekyll.logger.error 'Algolia Error: HTTP Error' Jekyll.logger.warn error.message end end # Change the User-Agent header to isolate calls from this plugin def set_user_agent_header version = AlgoliaSearchJekyllVersion.to_s Algolia.set_extra_header('User-Agent', "Algolia for Jekyll #{version}") end # Create an index to push our data def create_index(index_name) set_user_agent_header index = Algolia::Index.new(index_name) configure_index(index) unless @is_dry_run index end # Push records to the index def batch_add_items(items, index) items.each_slice(1000) do |batch| Jekyll.logger.info "Indexing #{batch.size} items" begin index.add_objects!(batch) unless @is_dry_run rescue StandardError => error display_error(error) exit 1 end end end def push(items) checker = AlgoliaSearchCredentialChecker.new(@config) checker.assert_valid Jekyll.logger.info '=== DRY RUN ===' if @is_dry_run # Add items to a temp index, then rename it index_name = checker.index_name index_name_tmp = "#{index_name}_tmp" batch_add_items(items, create_index(index_name_tmp)) Algolia.move_index(index_name_tmp, index_name) unless @is_dry_run Jekyll.logger.info "Indexing of #{items.size} items " \ "in #{index_name} done." end end end
ruby
MIT
cb21e83402de3cea46201fe12bd1b9a2eaacebfb
2026-01-04T17:53:57.372095Z
false
algolia/algoliasearch-jekyll
https://github.com/algolia/algoliasearch-jekyll/blob/cb21e83402de3cea46201fe12bd1b9a2eaacebfb/lib/record_extractor.rb
lib/record_extractor.rb
require 'algoliasearch' require 'nokogiri' require 'json' # Given an HTML file as input, will return an array of records to index class AlgoliaSearchRecordExtractor attr_reader :file def initialize(file) @file = file @config = file.site.config default_config = { 'record_css_selector' => 'p' } @config = default_config.merge(file.site.config['algolia']) end # Hook to modify a record after extracting def custom_hook_each(item, _node) item end # Hook to modify all records after extracting def custom_hook_all(items) items end # Returns metadata from the current file def metadata metadata = {} @file.data.each { |key, value| metadata[key.to_sym] = value } metadata[:type] = @file.class.name.split('::')[1].downcase metadata[:url] = @file.url metadata[:slug] = slug metadata[:posted_at] = @file.date.to_time.to_i if @file.respond_to? :date metadata[:tags] = tags metadata end # Returns the slug of the document def slug # Jekyll v3 has it in data return @file.data['slug'] if @file.data.key?('slug') # Old Jekyll v2 has it at the root return @file.slug if @file.respond_to? :slug # Otherwise, we guess it from the filename basename = File.basename(@file.path) extname = File.extname(basename) File.basename(basename, extname) end # Extract a list of tags def tags tags = nil # Jekyll v3 has it in data, while v2 have it at the root if @file.data.key?('tags') tags = @file.data['tags'] elsif @file.respond_to? :tags tags = @file.tags end return tags if tags.nil? # Anyway, we force cast it to string as some plugins will extend the tags to # full featured objects tags.map(&:to_s) end # Get the list of all HTML nodes to index def html_nodes document = Nokogiri::HTML(@file.content) document.css(@config['record_css_selector']) end # Check if node is a heading def node_heading?(node) %w(h1 h2 h3 h4 h5 h6).include?(node.name) end # Get the closest heading parent def node_heading_parent(node, level = 'h7') # If initially called on a heading, we only accept stronger headings level = node.name if level == 'h7' && node_heading?(node) previous = node.previous_element # No previous element, we go up to the parent unless previous parent = node.parent # No more parent, then no heading found return nil if parent.name == 'body' return node_heading_parent(parent, level) end # This is a heading, we return it return previous if node_heading?(previous) && previous.name < level node_heading_parent(previous, level) end # Get all the parent headings of the specified node # If the node itself is a heading, we include it def node_hierarchy(node, state = { level: 7 }) tag_name = node.name level = tag_name.delete('h').to_i if node_heading?(node) && level < state[:level] state[tag_name.to_sym] = node_text(node) state[:level] = level end heading = node_heading_parent(node) # No previous heading, we can stop the recursion unless heading state.delete(:level) return state end node_hierarchy(heading, state) end # Return the raw HTML of the element to index def node_raw_html(node) node.to_s end # Return the text of the element, sanitized to be displayed def node_text(node) node.content.gsub('<', '&lt;').gsub('>', '&gt;') end # Returns a unique string of hierarchy from title to h6, used for distinct def unique_hierarchy(data) headings = %w(title h1 h2 h3 h4 h5 h6) headings.map { |heading| data[heading.to_sym] }.compact.join(' > ') end # Returns a hash of two CSS selectors. One for the node itself, and one its # closest heading parent def node_css_selector(node) return nil if node.nil? # Use the CSS id if one is set return "##{node['id']}" if node['id'] # Default Nokogiri selector node.css_path.gsub('html > body > ', '') end # The more words are in common between this node and its parent heading, the # higher the score def weight_heading_relevance(data) # Get list of unique words in headings title_words = %i(title h1 h2 h3 h4 h5 h6) .select { |title| data.key?(title) } .map { |title| data[title].to_s.split(/\W+/) } .flatten .compact .map(&:downcase) .uniq # Intersect words in headings with words in test text_words = data[:text].downcase.split(/\W+/) (title_words & text_words).size end # Returns a weight based on the tag_name def weight_tag_name(item) tag_name = item[:tag_name] # No a heading, no weight return 0 unless %w(h1 h2 h3 h4 h5 h6).include?(tag_name) # h1: 100, h2: 90, ..., h6: 50 100 - (tag_name.delete('h').to_i - 1) * 10 end # Returns an object of all weights def weight(item, index) { tag_name: weight_tag_name(item), heading_relevance: weight_heading_relevance(item), position: index } end def extract items = [] html_nodes.each_with_index do |node, index| next if node.text.empty? item = metadata.clone item.merge!(node_hierarchy(node)) item[:tag_name] = node.name item[:raw_html] = node_raw_html(node) item[:text] = node_text(node) item[:unique_hierarchy] = unique_hierarchy(item) item[:css_selector] = node_css_selector(node) item[:css_selector_parent] = node_css_selector(node_heading_parent(node)) item[:weight] = weight(item, index) # We pass item through the user defined custom hook item = custom_hook_each(item, node) next if item.nil? items << item end custom_hook_all(items) end end
ruby
MIT
cb21e83402de3cea46201fe12bd1b9a2eaacebfb
2026-01-04T17:53:57.372095Z
false
algolia/algoliasearch-jekyll
https://github.com/algolia/algoliasearch-jekyll/blob/cb21e83402de3cea46201fe12bd1b9a2eaacebfb/lib/algoliasearch-jekyll.rb
lib/algoliasearch-jekyll.rb
require 'rubygems' require 'bundler/setup' require 'awesome_print' require_relative './version' require_relative './push' # `jekyll algolia` main entry class AlgoliaSearchJekyll < Jekyll::Command class << self def init_with_program(prog) prog.command(:algolia) do |command| command.syntax 'algolia <command> [options]' command.description 'Keep your content in sync with your Algolia index' command.command(:push) do |subcommand| subcommand.syntax 'push [options]' subcommand.description 'Push your content to your index' add_build_options(subcommand) subcommand.action do |args, options| default_options = { 'dry_run' => false, 'verbose' => false } options = default_options.merge(options) @config = configuration_from_options(options) AlgoliaSearchJekyllPush.init_options(args, options, @config) .jekyll_new(@config) .process end end end end # Allow a subset of the default `jekyll build` options def add_build_options(command) command.option 'config', '--config CONFIG_FILE[,CONFIG_FILE2,...]', Array, 'Custom configuration file' command.option 'future', '--future', 'Index posts with a future date' command.option 'limit_posts', '--limit_posts MAX_POSTS', Integer, 'Limits the number of posts to parse and index' command.option 'show_drafts', '-D', '--drafts', 'Index posts in the _drafts folder' command.option 'unpublished', '--unpublished', 'Index posts that were marked as unpublished' command.option 'dry_run', '--dry-run', '-n', 'Do a dry run, do not push records' command.option 'verbose', '--verbose', 'Display more information on what is indexed' end end end
ruby
MIT
cb21e83402de3cea46201fe12bd1b9a2eaacebfb
2026-01-04T17:53:57.372095Z
false
mikbe/eventable
https://github.com/mikbe/eventable/blob/316a8e7e93ad4a897c14c84f321941d767bf362b/autotest/discover.rb
autotest/discover.rb
Autotest.add_discovery {"rspec2"}
ruby
MIT
316a8e7e93ad4a897c14c84f321941d767bf362b
2026-01-04T17:54:26.651177Z
false
mikbe/eventable
https://github.com/mikbe/eventable/blob/316a8e7e93ad4a897c14c84f321941d767bf362b/spec/spec_helper.rb
spec/spec_helper.rb
$: << '.' $:.unshift File.expand_path(File.join(File.dirname(__FILE__), "/../lib")) require 'rspec' require 'eventable'
ruby
MIT
316a8e7e93ad4a897c14c84f321941d767bf362b
2026-01-04T17:54:26.651177Z
false
mikbe/eventable
https://github.com/mikbe/eventable/blob/316a8e7e93ad4a897c14c84f321941d767bf362b/spec/eventable/eventable_spec.rb
spec/eventable/eventable_spec.rb
require 'spec_helper' # Callbacks are threaded to avoid blocking so tests need to wait for the callback to be scheduled and run CALLBACK_WAIT = 0.01 describe Eventable do before(:each) do @evented = EventClass.new @listener = ListenClass.new end context "when mixing in Eventable" do it "should not raise an error if class has no initialize method" do lambda{ class Foo include Eventable event :do_stuff end f = Foo.new f.fire_event(:do_stuff) }.should_not raise_error end it "should not raise an error if super is called in initialize" do lambda{ class Foo include Eventable event :do_stuff def initialize super end end f = Foo.new f.fire_event(:do_stuff) }.should_not raise_error end it "should raise an error if super is not called in initialize" do lambda{ class Foo include Eventable event :do_stuff def initialize end end f = Foo.new f.fire_event(:do_stuff) }.should raise_error(Eventable::Errors::SuperNotCalledInInitialize) end context "and the class inherites from a class with initialization parameters" do it "should not raise an error if they are optional and not given" do class Baz def initialize(attributes = nil, options = {}) end end class Qiz < Baz include Eventable end expect{q = Qiz.new}.not_to raise_error end it "should not raise an error if they are required and given" do class Baz2 def initialize(attributes) end end class Qiz2 < Baz2 include Eventable end expect{q = Qiz2.new('blah')}.not_to raise_error end it "should pass along blocks if given" do class Baz3 def initialize(attributes = nil, &block) yield if block_given? end end class Qiz3 < Baz3 include Eventable end random_value = rand(9999999999) Qiz3.new() { @cheesy = random_value } @cheesy.should == random_value remove_instance_variable :@cheesy end end end context "when specifiying an event" do it 'should list the event from the class' do EventClass.events.should include(:stuff_happens) end it 'should list more than one event' do EventClass.events.should include(:other_stuff_happens) end it 'should list the event from an instance of the class' do @evented.events.should include(:stuff_happens) end it 'should list more than one event from an instance' do @evented.events.should include(:other_stuff_happens) end it "should not add an event that's already been added" do eval %{ class EventClass include Eventable event :stuff_happens end } EventClass.events.count.should == 2 end it "should not add events to other classes" do eval %{ class EventClass2 include Eventable event :some_other_event end } EventClass.events.should_not include(:some_other_event) end it "should not allow its event list to be altered external" do events = EventClass.events events.pop events.should_not == EventClass.events end end context "when registering for an event" do context "and there is a missing parameter" do # these tests could be refactored into one... it "should raise an error if the event is not specified" do lambda{ @evented.register_for_event(listener: @listener, callback: :callback) }.should raise_error(ArgumentError) end it "should raise an error if the listener is not specified" do lambda{ @evented.register_for_event(event: :do_something, callback: :callback) }.should raise_error(ArgumentError) end it "should raise an error if the callback is not specified" do lambda{ @evented.register_for_event(event: :do_something, listener: @listener) }.should raise_error(ArgumentError) end end it "should raise an error if the event doesn't exist" do foo = Class.new lambda{ @evented.register_for_event(event: :nonexistent, listener: foo, callback: :bar) }.should raise_error(Eventable::Errors::UnknownEvent) end it "should not raise an error when registering for events that do exist" do lambda{ @evented.register_for_event(event: :stuff_happens, listener: @listener, callback: :callback) }.should_not raise_error end it "should allow multiple callbacks to the same method from different events" do @evented.register_for_event(event: :stuff_happens, listener: @listener, callback: :callback) @evented.register_for_event(event: :other_stuff_happens, listener: @listener, callback: :callback) @evented.callbacks.count.should == 2 end it "should not add a callback that's already been added" do @evented.register_for_event(event: :stuff_happens, listener: @listener, callback: :callback) @evented.register_for_event(event: :stuff_happens, listener: @listener, callback: :callback) @evented.callbacks[:stuff_happens].count.should == 1 end it "should allow multiple instances of the same class to register the same callback for the same event" do listener2 = ListenClass.new @evented.register_for_event(event: :stuff_happens, listener: @listener, callback: :callback) @evented.register_for_event(event: :stuff_happens, listener: listener2, callback: :callback) @evented.callbacks[:stuff_happens].keys.should == [@listener.object_id, listener2.object_id] end it "should allow callbacks from the same event to different methods in the same instance" do @evented.register_for_event(event: :stuff_happens, listener: @listener, callback: :callback) @evented.register_for_event(event: :stuff_happens, listener: @listener, callback: :callback2) @evented.do_event sleep(CALLBACK_WAIT) @listener.callback?.should be true @listener.callback2?.should be true end it "should allow callbacks to class methods" do # should be a no brainer because a class is an object too, but just to be sure @evented.register_for_event(event: :stuff_happens, listener: ListenClass, callback: :class_callback) @evented.do_event sleep(CALLBACK_WAIT) ListenClass.class_callback?.should be true end context "when multiple classes mixin eventable" do # this is kind of redundant but just to be sure there's no bleed over through the mixin module it "should not call the wrong class" do another_evented = AnotherEventClass.new another_listener = AnotherListenClass.new @evented.register_for_event(event: :stuff_happens, listener: @listener, callback: :callback) another_evented.register_for_event(event: :stuff_happens, listener: another_listener, callback: :callback) @evented.do_event sleep(CALLBACK_WAIT) @listener.callback?.should be true another_listener.callback?.should_not be true end it "should not call the wrong class when both evented classes fire events" do another_evented = AnotherEventClass.new another_listener = AnotherListenClass.new @evented.register_for_event(event: :stuff_happens, listener: @listener, callback: :callback) another_evented.register_for_event(event: :stuff_happens, listener: another_listener, callback: :callback2) @evented.do_event another_evented.do_event sleep(CALLBACK_WAIT) @listener.callback?.should be true another_listener.callback2?.should be true end end end context "when unregistering for an event" do it "should not throw an error if unregistering for an event you weren't registered for" do # Is this supporting sloppy programming(bad) or lazy programming(good)? lambda{@evented.unregister_for_event(event: :stuff_happens, listener: @listener, callback: :callback)}.should_not raise_error end it "should remove a callback" do @evented.register_for_event(event: :stuff_happens, listener: @listener, callback: :callback) @evented.callbacks[:stuff_happens].keys.should include(@listener.object_id) # <= just to be sure... @evented.unregister_for_event(event: :stuff_happens, listener: @listener, callback: :callback) @evented.callbacks[:stuff_happens].keys.should_not include(@listener.object_id) end it "should not call a callback that has been removed" do @evented.register_for_event(event: :stuff_happens, listener: @listener, callback: :callback) @evented.unregister_for_event(event: :stuff_happens, listener: @listener, callback: :callback) @evented.do_event @listener.callback?.should_not be true end it "should automatically remove callbacks to objects that are garbage collected" do listener_object_id = nil (0..1).each do listener = ListenClass.new listener_object_id ||= listener.object_id @evented.register_for_event(event: :stuff_happens, listener: listener, callback: :callback) end GC.start @evented.callbacks[:stuff_happens].keys.should_not include(listener_object_id) end end context "when an event is fired" do it "should return false if the event did not fire" do @evented.do_event @evented.do_event.should be false end it "should return true if the event did fire" do @evented.register_for_event(event: :stuff_happens, listener: @listener, callback: :callback) @evented.do_event.should be true end it "should not throw an error if no listeners have been registered for an event" do @evented.do_event lambda{@evented.do_event}.should_not raise_error end it "should call back the specified method when the event is fired" do @evented.register_for_event(event: :stuff_happens, listener: @listener, callback: :callback) @evented.do_event sleep(CALLBACK_WAIT) @listener.callback?.should be true end it "should not call back the wrong method when the event is fired" do @evented.register_for_event(event: :stuff_happens, listener: @listener, callback: :callback) @evented.do_event @listener.callback2?.should_not be true end it "should call back more than one class" do listener2 = ListenClass.new @evented.register_for_event(event: :stuff_happens, listener: @listener, callback: :callback) @evented.register_for_event(event: :stuff_happens, listener: listener2, callback: :callback2) @evented.do_event sleep(CALLBACK_WAIT) @listener.callback?.should be true listener2.callback2?.should be true end it "should not call back the wrong method when using multiple classes" do listener2 = ListenClass.new @evented.register_for_event(event: :stuff_happens, listener: @listener, callback: :callback) @evented.register_for_event(event: :stuff_happens, listener: listener2, callback: :callback2) @evented.do_event sleep(CALLBACK_WAIT) @listener.callback2?.should_not be true listener2.callback?.should_not be true end context "and it has return data" do it "should return the return values" do @evented.register_for_event(event: :stuff_happens, listener: @listener, callback: :callback_with_args) a, b, c = rand(100), rand(100), rand(100) @evented.do_event_with_args(a,b,c) sleep(CALLBACK_WAIT) @listener.callback_with_args?.should == [a,b,c] end it "should return a block" do @evented.register_for_event(event: :stuff_happens, listener: @listener, callback: :callback_with_block) block = proc {"a block"} @evented.do_event_with_block(&block) sleep(CALLBACK_WAIT) @listener.callback_with_block?.should == block end it "should return the return values and a block" do @evented.register_for_event(event: :stuff_happens, listener: @listener, callback: :callback_with_args_and_block) a, b, c, block = rand(100), rand(100), rand(100), proc {"a block"} @evented.do_event_with_args_and_block(a,b,c,&block) sleep(CALLBACK_WAIT) @listener.callback_with_args_and_block?.should == [a,b,c,block] end end context "when multithreading" do it "should not block on callbacks" do bc = BlockingClass.new @evented.register_for_event(event: :stuff_happens, listener: bc, callback: :blocking_call) start_time = Time.now @evented.do_event sleep(CALLBACK_WAIT * 2) # Just to make sure the event cycle starts Time.now.should_not > start_time + 1 end end end end # Test classes class BlockingClass def blocking_call # I don't know how long this will take but it's a lot longer than 1 second 1000000000.times { Math.sqrt(98979872938749283749729384792734927) } non_blocking_call end def non_blocking_call "all done" end end class EventClass include Eventable event :stuff_happens event :other_stuff_happens def do_event(event=:stuff_happens) fire_event(event) end def do_event_with_args(*args) fire_event(:stuff_happens, *args) end def do_event_with_block(&block) fire_event(:stuff_happens, &block) end def do_event_with_args_and_block(*args, &block) fire_event(:stuff_happens, *args, &block) end end class AnotherEventClass include Eventable event :stuff_happens event :different_happens def do_event(event=:stuff_happens) fire_event(event) end end class ListenClass def self.class_callback? @@callback end def self.class_callback @@callback = true end def callback? @callback end def callback @callback = true end def callback2? @callback2 end def callback2 @callback2 = true end def callback_with_args(a,b,c) @a, @b, @c = a, b, c end def callback_with_args? [@a, @b, @c] end def callback_with_block(&block) @block = block end def callback_with_block? @block end def callback_with_args_and_block(a,b,c,&block) @a, @b, @c, @block = a, b, c, block end def callback_with_args_and_block? [@a, @b, @c, @block] end end class AnotherListenClass def callback? @callback end def callback @callback = true end def callback2? @callback2 end def callback2 @callback2 = true end end
ruby
MIT
316a8e7e93ad4a897c14c84f321941d767bf362b
2026-01-04T17:54:26.651177Z
false
mikbe/eventable
https://github.com/mikbe/eventable/blob/316a8e7e93ad4a897c14c84f321941d767bf362b/lib/eventable.rb
lib/eventable.rb
require "eventable/version" require "eventable/errors" require "eventable/eventable"
ruby
MIT
316a8e7e93ad4a897c14c84f321941d767bf362b
2026-01-04T17:54:26.651177Z
false
mikbe/eventable
https://github.com/mikbe/eventable/blob/316a8e7e93ad4a897c14c84f321941d767bf362b/lib/eventable/version.rb
lib/eventable/version.rb
module Eventable VERSION = "0.2.1" end
ruby
MIT
316a8e7e93ad4a897c14c84f321941d767bf362b
2026-01-04T17:54:26.651177Z
false
mikbe/eventable
https://github.com/mikbe/eventable/blob/316a8e7e93ad4a897c14c84f321941d767bf362b/lib/eventable/errors.rb
lib/eventable/errors.rb
module Eventable module Errors UnknownEvent = Class.new(StandardError) SuperNotCalledInInitialize = Class.new(ScriptError) end end
ruby
MIT
316a8e7e93ad4a897c14c84f321941d767bf362b
2026-01-04T17:54:26.651177Z
false
mikbe/eventable
https://github.com/mikbe/eventable/blob/316a8e7e93ad4a897c14c84f321941d767bf362b/lib/eventable/eventable.rb
lib/eventable/eventable.rb
require 'thread' # Incredibly simple framework for adding events module Eventable module EventableEventMethods # register an event def event(event_name) @eventable_events ||= [] @eventable_events << event_name unless @eventable_events.include? event_name end # returns a list of registered events def events @eventable_events.clone end end def events self.class.events end # Allows for dynamic discovery of hooked callbacks attr_reader :callbacks # Add the #event method to the extending class not instances of that class def self.included(base) base.extend(EventableEventMethods) end def initialize(*args) super @eventable_mutex = Mutex.new end # When the event happens the class where it happens runs this def fire_event(event, *return_value, &block) check_mutex @eventable_mutex.synchronize { return false unless @callbacks && @callbacks[event] && !@callbacks[event].empty? @callbacks[event].each do |listener_id, callbacks| begin listener = ObjectSpace._id2ref(listener_id) callbacks.each do |callback| Thread.new {listener.send callback, *return_value, &block} end rescue RangeError => re # Don't bubble up a missing recycled object, I don't care if it's not there, I just won't call it raise re unless re.message.match(/is recycled object/) end end } true end # Allows an object to listen for an event and have a callback run when the event happens def register_for_event(args) [:event, :listener, :callback].each do |parameter| raise ArgumentError, "Missing parameter :#{parameter}" unless args[parameter] end # Make access to the callback array threadsafe check_mutex @eventable_mutex.synchronize { event = args[:event] raise Errors::UnknownEvent unless events.include? event @callbacks ||= {} @callbacks[event] ||= {} listener = args[:listener] listener_id = listener.object_id callback = args[:callback] # save the callback info without creating a reference to the object @callbacks[event][listener_id] ||= [] @callbacks[event][listener_id] << callback # will remove the object from the callback list if it is destroyed ObjectSpace.define_finalizer( listener, unregister_finalizer(event, listener_id, callback) ) } end # Allows objects to stop listening to events def unregister_for_event(args) check_mutex @eventable_mutex.synchronize { event = args[:event] return unless @callbacks && @callbacks[event] listener_id = args[:listener_id] || args[:listener].object_id callback = args[:callback] @callbacks[event].delete_if do |listener, callbacks| callbacks.delete(callback) if listener == listener_id callbacks.empty? end } end private def check_mutex raise Errors::SuperNotCalledInInitialize, "You must include super in your class's initialize method" unless @eventable_mutex end # Wrapper for the finalize proc. You have to call a method # from define_finalizer; you can't just put this proc in there. def unregister_finalizer(event, listener_id, callback) proc {unregister_for_event(event: event, listener_id: listener_id, callback: callback)} end end
ruby
MIT
316a8e7e93ad4a897c14c84f321941d767bf362b
2026-01-04T17:54:26.651177Z
false
fatkodima/columns_trace
https://github.com/fatkodima/columns_trace/blob/76cdd86a78d99b8001e1bfd23fe36946a2d578c6/test/sidekiq_test.rb
test/sidekiq_test.rb
# frozen_string_literal: true require "test_helper" class SidekiqTest < ActiveSupport::TestCase test "reports unused columns" do output = capture_logging do SidekiqJob.perform_inline end assert_match %(SidekiqJob#perform\n 1 User record: unused columns - "id", "email", "created_at", "updated_at"; used columns - "name"), output assert_match "↳", output assert_match(/app\/jobs\/sidekiq_job\.rb:\d+:in `perform/, output) end end
ruby
MIT
76cdd86a78d99b8001e1bfd23fe36946a2d578c6
2026-01-04T17:54:31.811968Z
false
fatkodima/columns_trace
https://github.com/fatkodima/columns_trace/blob/76cdd86a78d99b8001e1bfd23fe36946a2d578c6/test/controller_test.rb
test/controller_test.rb
# frozen_string_literal: true require "test_helper" class ControllerTest < ActionDispatch::IntegrationTest test "GET /action1" do output = capture_logging do get action1_path end assert_match %(UsersController#action1\n 2 User records: unused columns - "id", "created_at", "updated_at"; used columns - "email", "name"), output assert_match "↳", output assert_match(/app\/controllers\/users_controller\.rb:\d+:in `action1/, output) end test "GET /action2" do output = capture_logging do get action2_path end assert_match %(UsersController#action2\n 1 User record: unused columns - "name", "email", "created_at", "updated_at"; used columns - "id"), output assert_match "↳", output assert_match(/app\/controllers\/users_controller\.rb:\d+:in `action2/, output) end test "GET /action3" do output = capture_logging do get action3_path end assert_empty output end test "GET /action4" do output = capture_logging do get action4_path end assert_equal 2, output.count("↳") end test "GET /action5" do output = capture_logging do get action5_path end assert_match %(UsersController#action5\n 1 User record: unused columns - "id", "name", "email", "created_at", "updated_at"; used columns -), output assert_match ' 1 Project record: unused columns - "id", "name"; used columns -', output end test "ignored models" do ColumnsTrace.ignored_models = [User] output = capture_logging do get action1_path end assert_empty output ensure ColumnsTrace.ignored_models = [] end test "ignored columns" do ColumnsTrace.ignored_columns = [:created_at, { Project => :name }] output = capture_logging do get action5_path end assert_match %(UsersController#action5\n 1 User record: unused columns - "id", "name", "email", "updated_at"; used columns -), output assert_match ' 1 Project record: unused columns - "id"; used columns -', output ensure ColumnsTrace.ignored_columns = [] end end
ruby
MIT
76cdd86a78d99b8001e1bfd23fe36946a2d578c6
2026-01-04T17:54:31.811968Z
false
fatkodima/columns_trace
https://github.com/fatkodima/columns_trace/blob/76cdd86a78d99b8001e1bfd23fe36946a2d578c6/test/test_helper.rb
test/test_helper.rb
# frozen_string_literal: true ENV["RAILS_ENV"] = "test" require "columns_trace" require "logger" require "minitest/autorun" require_relative "dummy/config/environment" ActiveRecord::Migration.suppress_messages do require_relative "dummy/db/schema" end User.create!([ { name: "John", email: "john@example.com" }, { name: "Jane", email: "jane@example.com" } ]) Project.create!(name: "Ruby on Rails") # A hack to make server middleware work. # See https://github.com/sidekiq/sidekiq/wiki/Testing#testing-server-middleware. module Sidekiq class << self undef server? def server? true end end end ColumnsTrace.enable_sidekiq_tracing! module ActiveSupport class TestCase def capture_logging(&block) out = StringIO.new logger = Logger.new(out) reporter = ColumnsTrace::LogReporter.new(logger) ColumnsTrace.stub(:reporter, reporter, &block) out.string end end end
ruby
MIT
76cdd86a78d99b8001e1bfd23fe36946a2d578c6
2026-01-04T17:54:31.811968Z
false
fatkodima/columns_trace
https://github.com/fatkodima/columns_trace/blob/76cdd86a78d99b8001e1bfd23fe36946a2d578c6/test/mailer_test.rb
test/mailer_test.rb
# frozen_string_literal: true require "test_helper" class MailerTest < ActionMailer::TestCase setup do @user = User.first end test "reports unused columns" do email = UserMailer.with(user: @user).unused_fields_email output = capture_logging do email.deliver_now end assert_match %(UserMailer#unused_fields_email\n 1 Project record: unused columns - "id"; used columns - "name"), output assert_match "↳", output assert_match(/app\/mailers\/user_mailer\.rb:\d+:in `unused_fields_email/, output) end test "does not report when all columns are used" do email = UserMailer.with(user: @user).used_fields_email output = capture_logging do email.deliver_now end assert_empty output end end
ruby
MIT
76cdd86a78d99b8001e1bfd23fe36946a2d578c6
2026-01-04T17:54:31.811968Z
false
fatkodima/columns_trace
https://github.com/fatkodima/columns_trace/blob/76cdd86a78d99b8001e1bfd23fe36946a2d578c6/test/job_test.rb
test/job_test.rb
# frozen_string_literal: true require "test_helper" class JobTest < ActiveJob::TestCase test "reports unused columns" do output = capture_logging do UnusedJob.perform_now end assert_match %(UnusedJob#perform\n 1 User record: unused columns - "id", "name", "created_at", "updated_at"; used columns - "email"), output assert_match "↳", output assert_match(/app\/jobs\/unused_job\.rb:\d+:in `perform/, output) end test "does not report when all columns are used" do output = capture_logging do UsedJob.perform_now end assert_empty output end end
ruby
MIT
76cdd86a78d99b8001e1bfd23fe36946a2d578c6
2026-01-04T17:54:31.811968Z
false
fatkodima/columns_trace
https://github.com/fatkodima/columns_trace/blob/76cdd86a78d99b8001e1bfd23fe36946a2d578c6/test/dummy/app/jobs/used_job.rb
test/dummy/app/jobs/used_job.rb
# frozen_string_literal: true class UsedJob < ActiveJob::Base def perform User.first.attributes end end
ruby
MIT
76cdd86a78d99b8001e1bfd23fe36946a2d578c6
2026-01-04T17:54:31.811968Z
false
fatkodima/columns_trace
https://github.com/fatkodima/columns_trace/blob/76cdd86a78d99b8001e1bfd23fe36946a2d578c6/test/dummy/app/jobs/unused_job.rb
test/dummy/app/jobs/unused_job.rb
# frozen_string_literal: true class UnusedJob < ActiveJob::Base def perform User.first.email end end
ruby
MIT
76cdd86a78d99b8001e1bfd23fe36946a2d578c6
2026-01-04T17:54:31.811968Z
false
fatkodima/columns_trace
https://github.com/fatkodima/columns_trace/blob/76cdd86a78d99b8001e1bfd23fe36946a2d578c6/test/dummy/app/jobs/sidekiq_job.rb
test/dummy/app/jobs/sidekiq_job.rb
# frozen_string_literal: true class SidekiqJob include Sidekiq::Job def perform User.first.name end end
ruby
MIT
76cdd86a78d99b8001e1bfd23fe36946a2d578c6
2026-01-04T17:54:31.811968Z
false
fatkodima/columns_trace
https://github.com/fatkodima/columns_trace/blob/76cdd86a78d99b8001e1bfd23fe36946a2d578c6/test/dummy/app/controllers/users_controller.rb
test/dummy/app/controllers/users_controller.rb
# frozen_string_literal: true class UsersController < ActionController::Base # Multiple records with unused columns. def action1 user1, user2 = User.all.to_a user1.email user2.name head :ok end # Single record with unused columns. def action2 user = User.first user.id head :ok end # Single record with all used columns. def action3 user = User.first user.attributes head :ok end # Different backtraces. def action4 User.first User.last head :ok end # Different models. def action5 User.first Project.last head :ok end end
ruby
MIT
76cdd86a78d99b8001e1bfd23fe36946a2d578c6
2026-01-04T17:54:31.811968Z
false
fatkodima/columns_trace
https://github.com/fatkodima/columns_trace/blob/76cdd86a78d99b8001e1bfd23fe36946a2d578c6/test/dummy/app/models/project.rb
test/dummy/app/models/project.rb
# frozen_string_literal: true class Project < ActiveRecord::Base end
ruby
MIT
76cdd86a78d99b8001e1bfd23fe36946a2d578c6
2026-01-04T17:54:31.811968Z
false
fatkodima/columns_trace
https://github.com/fatkodima/columns_trace/blob/76cdd86a78d99b8001e1bfd23fe36946a2d578c6/test/dummy/app/models/user.rb
test/dummy/app/models/user.rb
# frozen_string_literal: true class User < ActiveRecord::Base end
ruby
MIT
76cdd86a78d99b8001e1bfd23fe36946a2d578c6
2026-01-04T17:54:31.811968Z
false
fatkodima/columns_trace
https://github.com/fatkodima/columns_trace/blob/76cdd86a78d99b8001e1bfd23fe36946a2d578c6/test/dummy/app/mailers/user_mailer.rb
test/dummy/app/mailers/user_mailer.rb
# frozen_string_literal: true class UserMailer < ActionMailer::Base default from: "foo@example.com" def unused_fields_email user = params[:user] _projects = Project.all.map(&:name) mail(to: user.email) do |format| format.text { render plain: "Text" } end end def used_fields_email user = params[:user] _projects = Project.all.map(&:attributes) mail(to: user.email) do |format| format.text { render plain: "Text" } end end end
ruby
MIT
76cdd86a78d99b8001e1bfd23fe36946a2d578c6
2026-01-04T17:54:31.811968Z
false
fatkodima/columns_trace
https://github.com/fatkodima/columns_trace/blob/76cdd86a78d99b8001e1bfd23fe36946a2d578c6/test/dummy/db/schema.rb
test/dummy/db/schema.rb
# frozen_string_literal: true ActiveRecord::Schema.define do create_table :users, force: true do |t| t.string :name t.string :email t.timestamps end create_table :projects, force: true do |t| t.string :name end end
ruby
MIT
76cdd86a78d99b8001e1bfd23fe36946a2d578c6
2026-01-04T17:54:31.811968Z
false
fatkodima/columns_trace
https://github.com/fatkodima/columns_trace/blob/76cdd86a78d99b8001e1bfd23fe36946a2d578c6/test/dummy/config/application.rb
test/dummy/config/application.rb
# frozen_string_literal: true require_relative "boot" require "rails" require "active_record/railtie" require "action_mailer/railtie" require "active_job/railtie" require "rails/test_unit/railtie" Bundler.require(*Rails.groups) module Dummy class Application < Rails::Application config.root = File.expand_path("..", __dir__) config.eager_load = false if Rails::VERSION::MAJOR >= 7 config.load_defaults 7.0 else config.load_defaults 6.0 end end end
ruby
MIT
76cdd86a78d99b8001e1bfd23fe36946a2d578c6
2026-01-04T17:54:31.811968Z
false
fatkodima/columns_trace
https://github.com/fatkodima/columns_trace/blob/76cdd86a78d99b8001e1bfd23fe36946a2d578c6/test/dummy/config/environment.rb
test/dummy/config/environment.rb
# frozen_string_literal: true # Load the Rails application. require_relative "application" # Initialize the Rails application. Rails.application.initialize!
ruby
MIT
76cdd86a78d99b8001e1bfd23fe36946a2d578c6
2026-01-04T17:54:31.811968Z
false
fatkodima/columns_trace
https://github.com/fatkodima/columns_trace/blob/76cdd86a78d99b8001e1bfd23fe36946a2d578c6/test/dummy/config/routes.rb
test/dummy/config/routes.rb
# frozen_string_literal: true Rails.application.routes.draw do (1..5).each do |i| get "/action#{i}", to: "users#action#{i}", as: "action#{i}" end end
ruby
MIT
76cdd86a78d99b8001e1bfd23fe36946a2d578c6
2026-01-04T17:54:31.811968Z
false
fatkodima/columns_trace
https://github.com/fatkodima/columns_trace/blob/76cdd86a78d99b8001e1bfd23fe36946a2d578c6/test/dummy/config/boot.rb
test/dummy/config/boot.rb
# frozen_string_literal: true ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile", __dir__) require "bundler/setup" # Set up gems listed in the Gemfile.
ruby
MIT
76cdd86a78d99b8001e1bfd23fe36946a2d578c6
2026-01-04T17:54:31.811968Z
false
fatkodima/columns_trace
https://github.com/fatkodima/columns_trace/blob/76cdd86a78d99b8001e1bfd23fe36946a2d578c6/test/dummy/config/environments/test.rb
test/dummy/config/environments/test.rb
# frozen_string_literal: true Rails.application.configure do config.cache_classes = false config.eager_load = false config.active_job.queue_adapter = :inline end
ruby
MIT
76cdd86a78d99b8001e1bfd23fe36946a2d578c6
2026-01-04T17:54:31.811968Z
false
fatkodima/columns_trace
https://github.com/fatkodima/columns_trace/blob/76cdd86a78d99b8001e1bfd23fe36946a2d578c6/lib/columns_trace.rb
lib/columns_trace.rb
# frozen_string_literal: true require "active_record" require_relative "columns_trace/created_record" require_relative "columns_trace/registry" require_relative "columns_trace/rails_integration" require_relative "columns_trace/log_reporter" require_relative "columns_trace/version" require_relative "columns_trace/railtie" if defined?(Rails) module ColumnsTrace class << self # Manually trace columns usage in an arbitrary code. # # @param title [String] title of the reporting, e.g. controller action etc # # @example # task my_rake_task: :environment do # ColumnsTrace.report("my_rake_task") do # # do stuff # end # end # def report(title) Registry.clear yield reporter.report(title, Registry.created_records) end # @private attr_reader :ignored_models # Configures models that will be ignored. # # @example # ColumnsTrace.ignored_models = [Settings] # # Always adds Rails' internal `ActiveRecord::SchemaMigration` # and `ActiveRecord::InternalMetadata` models by default. # def ignored_models=(models) @ignored_models = Array(models) | [ActiveRecord::SchemaMigration, ActiveRecord::InternalMetadata] end # @private def ignored_model?(model) ignored_models.include?(model) end # Configures columns that will be ignored. # # @example Global setting # ColumnsTrace.ignored_columns = [:updated_at] # @example Per-model setting # ColumnsTrace.ignored_columns = [:updated_at, { User => :admin }] # attr_accessor :ignored_columns # @private def ignored_column?(model, column) ignored_columns.any? do |value| if value.is_a?(Hash) columns = value[model] || value[model.name] || value[model.name.to_sym] if columns columns = Array(columns).map(&:to_s) columns.include?(column) end else value.to_s == column end end end # Allows to set the reporter. # Defaults to log reporter that outputs to `log/columns_trace.log` file # when inside a rails application. # attr_accessor :reporter # @private attr_reader :backtrace_cleaner # Allows to set a backtrace_cleaner used to clean backtrace before printing them. # Defaults to `Rails.backtrace_cleaner` when inside a rails application. # def backtrace_cleaner=(cleaner) @backtrace_cleaner = if cleaner.respond_to?(:clean) ->(backtrace) { cleaner.clean(backtrace) } else cleaner end end # Enables integration with Sidekiq, which is disabled by default. # def enable_sidekiq_tracing! require_relative "columns_trace/sidekiq_integration" true end # A convenient method to configure this gem. # # @example # ColumnsTrace.configure do |config| # # ... # end # def configure yield self end end self.ignored_models = [] self.ignored_columns = [] self.backtrace_cleaner = ->(backtrace) { backtrace } end
ruby
MIT
76cdd86a78d99b8001e1bfd23fe36946a2d578c6
2026-01-04T17:54:31.811968Z
false
fatkodima/columns_trace
https://github.com/fatkodima/columns_trace/blob/76cdd86a78d99b8001e1bfd23fe36946a2d578c6/lib/columns_trace/version.rb
lib/columns_trace/version.rb
# frozen_string_literal: true module ColumnsTrace VERSION = "0.3.1" end
ruby
MIT
76cdd86a78d99b8001e1bfd23fe36946a2d578c6
2026-01-04T17:54:31.811968Z
false
fatkodima/columns_trace
https://github.com/fatkodima/columns_trace/blob/76cdd86a78d99b8001e1bfd23fe36946a2d578c6/lib/columns_trace/created_record.rb
lib/columns_trace/created_record.rb
# frozen_string_literal: true module ColumnsTrace # Class that is used to store metadata about created ActiveRecord records. class CreatedRecord # Model class # @return [Class] # attr_reader :model # Model instance # @return [ActiveRecord::Base] # attr_reader :record # Backtrace where the instance was created # @return [Array<String>] # attr_reader :backtrace def initialize(record, backtrace) @model = record.class @record = record @backtrace = backtrace end # Get accessed fields on model instance # @return [Array<String>] # def accessed_fields @accessed_fields ||= record.accessed_fields end # Get unused fields on model instance # @return [Array<String>] # def unused_fields # We need to store this into local variable, because `record.attributes` # will access all attributes. accessed = accessed_fields record.attributes.keys - accessed end end end
ruby
MIT
76cdd86a78d99b8001e1bfd23fe36946a2d578c6
2026-01-04T17:54:31.811968Z
false
fatkodima/columns_trace
https://github.com/fatkodima/columns_trace/blob/76cdd86a78d99b8001e1bfd23fe36946a2d578c6/lib/columns_trace/registry.rb
lib/columns_trace/registry.rb
# frozen_string_literal: true module ColumnsTrace # @private # Note: can use ActiveSupport::IsolatedExecutionState instead of this module for rails 7.0+. module Registry class << self def register(record, backtrace) state << CreatedRecord.new(record, backtrace) end def clear state.clear end def created_records state end private def state Thread.current[:columns_trace] ||= [] end end end end
ruby
MIT
76cdd86a78d99b8001e1bfd23fe36946a2d578c6
2026-01-04T17:54:31.811968Z
false
fatkodima/columns_trace
https://github.com/fatkodima/columns_trace/blob/76cdd86a78d99b8001e1bfd23fe36946a2d578c6/lib/columns_trace/railtie.rb
lib/columns_trace/railtie.rb
# frozen_string_literal: true module ColumnsTrace # @private class Railtie < Rails::Railtie initializer "columns_trace.set_configs" do ColumnsTrace.backtrace_cleaner = Rails.backtrace_cleaner logger = ActiveSupport::Logger.new(Rails.root.join("log", "columns_trace.log")) ColumnsTrace.reporter ||= LogReporter.new(logger) end end end
ruby
MIT
76cdd86a78d99b8001e1bfd23fe36946a2d578c6
2026-01-04T17:54:31.811968Z
false
fatkodima/columns_trace
https://github.com/fatkodima/columns_trace/blob/76cdd86a78d99b8001e1bfd23fe36946a2d578c6/lib/columns_trace/rails_integration.rb
lib/columns_trace/rails_integration.rb
# frozen_string_literal: true module ColumnsTrace ActiveSupport.on_load(:active_record) do after_find do backtrace = Kernel.caller if ColumnsTrace.backtrace_cleaner backtrace = ColumnsTrace.backtrace_cleaner.call(backtrace) end Registry.register(self, backtrace) unless ColumnsTrace.ignored_model?(self.class) end end ActiveSupport.on_load(:action_controller) do around_action do |controller, action| ColumnsTrace.report("#{controller.class.name}##{action_name}", &action) end end ActiveSupport.on_load(:action_mailer) do around_action do |mailer, action| ColumnsTrace.report("#{mailer.class.name}##{action_name}", &action) end end ActiveSupport.on_load(:active_job) do around_perform do |job, perform| ColumnsTrace.report("#{job.class.name}#perform", &perform) end end end
ruby
MIT
76cdd86a78d99b8001e1bfd23fe36946a2d578c6
2026-01-04T17:54:31.811968Z
false
fatkodima/columns_trace
https://github.com/fatkodima/columns_trace/blob/76cdd86a78d99b8001e1bfd23fe36946a2d578c6/lib/columns_trace/log_reporter.rb
lib/columns_trace/log_reporter.rb
# frozen_string_literal: true module ColumnsTrace # Reporter that reports into the provided logger. class LogReporter def initialize(logger) @logger = logger end # Main reporter's method # # @param title [String] title of the reporting, e.g. controller action etc # @param created_records [Array<ColumnsTrace::CreatedRecord>] items that hold # metadata about created records # def report(title, created_records) lines = [] created_records.group_by(&:model).each do |model, grouped_created_records| lines.concat(lines_for_created_records(model, grouped_created_records)) end if lines.any? @logger.info("#{title}\n#{lines.join("\n")}") end end private def lines_for_created_records(model, created_records) lines = [] created_records.group_by(&:backtrace).each do |backtrace, grouped_created_records| accessed = accessed_fields(grouped_created_records) unused = grouped_created_records.first.unused_fields - accessed unused.reject! { |column| ColumnsTrace.ignored_column?(model, column) } if unused.any? records_text = "record".pluralize(grouped_created_records.size) lines << <<-MSG #{grouped_created_records.size} #{model.name} #{records_text}: unused columns - #{format_columns(unused)}; used columns - #{format_columns(accessed)} ↳ #{backtrace.join("\n ")} MSG end end lines end def accessed_fields(created_records) created_records.map(&:accessed_fields).flatten.uniq end def format_columns(columns) columns.map(&:inspect).join(", ") end end end
ruby
MIT
76cdd86a78d99b8001e1bfd23fe36946a2d578c6
2026-01-04T17:54:31.811968Z
false
fatkodima/columns_trace
https://github.com/fatkodima/columns_trace/blob/76cdd86a78d99b8001e1bfd23fe36946a2d578c6/lib/columns_trace/sidekiq_integration.rb
lib/columns_trace/sidekiq_integration.rb
# frozen_string_literal: true module ColumnsTrace # @private class SidekiqMiddleware def call(worker, _job, _queue, &block) ColumnsTrace.report("#{worker.class.name}#perform", &block) end end end Sidekiq.configure_server do |config| config.server_middleware do |chain| chain.add(ColumnsTrace::SidekiqMiddleware) end end
ruby
MIT
76cdd86a78d99b8001e1bfd23fe36946a2d578c6
2026-01-04T17:54:31.811968Z
false
adamalbrecht/docx_replace
https://github.com/adamalbrecht/docx_replace/blob/87012115d4316994ff498b5cefabe340a67f7e10/spec/docx_replace_spec.rb
spec/docx_replace_spec.rb
require 'spec_helper' require 'docx_replace' require 'zip' describe DocxReplace::Doc do let(:output_file) { Tempfile.new('docx_replace_tmp_output') } let(:output_text) { docx_content(output_file) } it "replaces a single variable in a very basic document" do doc = described_class.new(get_fixture("basic.docx")) doc.replace("FOOBAR", "hello world") doc.commit(output_file) expect(output_text).to match(/hello world/) expect(output_text).not_to match(/FOOBAR/) end it "can replace multiple occurrences of the same variable" do doc = described_class.new(get_fixture("multiple.docx")) doc.replace("FOOBAR", "hello world", true) doc.commit(output_file) expect(output_text).not_to match(/FOOBAR/) expect(output_text.scan("hello world").size).to eq(2) end it "does not replace multiple occurrences unless instructed to do so" do doc = described_class.new(get_fixture("multiple.docx")) doc.replace("FOOBAR", "hello world", false) doc.commit(output_file) expect(output_text.scan("FOOBAR").size).to eq(1) expect(output_text.scan("hello world").size).to eq(1) end private def get_fixture(name) File.join(project_root, "spec", "fixtures", name) end def project_root File.expand_path(File.dirname(File.dirname(__FILE__))) end def docx_content(path) zip_file = Zip::File.new(path) zip_file.read("word/document.xml") end end
ruby
MIT
87012115d4316994ff498b5cefabe340a67f7e10
2026-01-04T17:54:29.790964Z
false
adamalbrecht/docx_replace
https://github.com/adamalbrecht/docx_replace/blob/87012115d4316994ff498b5cefabe340a67f7e10/spec/spec_helper.rb
spec/spec_helper.rb
RSpec.configure do |config| config.run_all_when_everything_filtered = true config.filter_run :focus # 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' end
ruby
MIT
87012115d4316994ff498b5cefabe340a67f7e10
2026-01-04T17:54:29.790964Z
false
adamalbrecht/docx_replace
https://github.com/adamalbrecht/docx_replace/blob/87012115d4316994ff498b5cefabe340a67f7e10/lib/docx_replace.rb
lib/docx_replace.rb
# encoding: UTF-8 require "docx_replace/version" require 'zip' require 'tempfile' module DocxReplace class Doc attr_reader :document_content def initialize(path, temp_dir=nil) @zip_file = Zip::File.new(path) @temp_dir = temp_dir read_docx_file end def replace(pattern, replacement, multiple_occurrences=false) replace = replacement.to_s.encode(xml: :text) if multiple_occurrences @document_content.force_encoding("UTF-8").gsub!(pattern, replace) else @document_content.force_encoding("UTF-8").sub!(pattern, replace) end end def matches(pattern) @document_content.scan(pattern).map{|match| match.first} end def unique_matches(pattern) matches(pattern) end alias_method :uniq_matches, :unique_matches def commit(new_path=nil) write_back_to_file(new_path) end private DOCUMENT_FILE_PATH = 'word/document.xml' def read_docx_file @document_content = @zip_file.read(DOCUMENT_FILE_PATH) end def write_back_to_file(new_path=nil) if @temp_dir.nil? temp_file = Tempfile.new('docxedit-') else temp_file = Tempfile.new('docxedit-', @temp_dir) end Zip::OutputStream.open(temp_file.path) do |zos| @zip_file.entries.each do |e| unless e.name == DOCUMENT_FILE_PATH zos.put_next_entry(e.name) zos.print e.get_input_stream.read end end zos.put_next_entry(DOCUMENT_FILE_PATH) zos.print @document_content end if new_path.nil? path = @zip_file.name FileUtils.rm(path) else path = new_path end FileUtils.mv(temp_file.path, path) @zip_file = Zip::File.new(path, true) end end end
ruby
MIT
87012115d4316994ff498b5cefabe340a67f7e10
2026-01-04T17:54:29.790964Z
false
adamalbrecht/docx_replace
https://github.com/adamalbrecht/docx_replace/blob/87012115d4316994ff498b5cefabe340a67f7e10/lib/docx_replace/version.rb
lib/docx_replace/version.rb
module DocxReplace VERSION = "1.2.1" end
ruby
MIT
87012115d4316994ff498b5cefabe340a67f7e10
2026-01-04T17:54:29.790964Z
false
chesterbr/ruby2600
https://github.com/chesterbr/ruby2600/blob/7a947c978423b53e9770b54a86a594bcb37906ac/spec/spec_helper.rb
spec/spec_helper.rb
require 'simplecov' require 'simplecov-gem-adapter' SimpleCov.start 'gem' require 'rubygems' require 'json' require 'humanize' require 'timeout' require 'ruby2600' require 'support/shared_examples_for_bus.rb' require 'support/shared_examples_for_cpu.rb' require 'support/shared_examples_for_riot.rb' require 'support/shared_examples_for_tia.rb' include Ruby2600::Constants RSpec.configure do |c| c.alias_it_behaves_like_to :it_does end # Helper methods def hex_word(word) sprintf("$%04X", word) rescue "$????" end def hex_byte(byte) sprintf("$%02X", byte) rescue "$??" end def rand_with_bit(bit, status) mask = 1 << bit status == :set ? mask | rand(256) : (0xFF ^ mask) & rand(256) end def pixels(graphic, first = 1, last = 160) (first-1).times { graphic.tick } (0..(last - first)).map { graphic.tick; graphic.pixel } end def scanline_with_object(size, color, copies = 1) 1.upto(copies).map{ Array.new(size, color) + Array.new(32 - size) }.flatten + Array.new(160 - 32 * copies) end def path_for_ROM(name) "spec/fixtures/files/#{name}.bin" end
ruby
MIT
7a947c978423b53e9770b54a86a594bcb37906ac
2026-01-04T17:54:37.265867Z
false