From e5fa357cdd9ed6e5d6e09036cc6f711ec5708fc7 Mon Sep 17 00:00:00 2001 From: Joel Hawksley Date: Mon, 30 Nov 2026 11:00:24 -0700 Subject: [PATCH 1/2] Adopt rubyfmt while retaining compatible Ruby lint checks --- .github/workflows/lint.yml | 18 +- .rubocop.yml | 27 +- .standard.yml | 3 - Appraisals | 18 +- Gemfile | 1 + Gemfile.lock | 5 + Rakefile | 173 +++--- .../view_component/preview_actions.rb | 12 +- app/controllers/view_components_controller.rb | 3 +- .../view_components_system_test_controller.rb | 7 +- docs/CHANGELOG.md | 4 + docs/CONTRIBUTING.md | 12 + docs/Gemfile | 2 +- gemfiles/rails_7.1.gemfile | 3 +- gemfiles/rails_7.1.gemfile.lock | 4 + gemfiles/rails_7.2.gemfile | 3 +- gemfiles/rails_7.2.gemfile.lock | 4 + gemfiles/rails_8.0.gemfile | 3 +- gemfiles/rails_8.0.gemfile.lock | 4 + gemfiles/rails_8.1.gemfile | 3 +- gemfiles/rails_8.1.gemfile.lock | 4 + gemfiles/rails_main.gemfile | 3 +- gemfiles/rails_main.gemfile.lock | 5 + gemfiles/rails_main_head.gemfile | 3 +- gemfiles/rails_main_head.gemfile.lock | 4 + lib/docs/docs_builder_component.rb | 12 +- .../view_component/abstract_generator.rb | 5 +- .../component/component_generator.rb | 4 +- .../view_component/locale/locale_generator.rb | 4 +- .../preview/preview_generator.rb | 13 +- .../view_component/rspec/rspec_generator.rb | 2 +- .../stimulus/stimulus_generator.rb | 2 +- .../test_unit/test_unit_generator.rb | 4 +- lib/view_component/base.rb | 114 ++-- lib/view_component/cache_digest.rb | 44 +- .../cache_digest/dependency_tracking.rb | 8 +- .../cache_digest/digestor_lookup.rb | 21 +- lib/view_component/cache_digest/resolver.rb | 127 ++-- lib/view_component/cacheable.rb | 18 +- lib/view_component/collection.rb | 1 + lib/view_component/compile_cache.rb | 5 +- lib/view_component/compiler.rb | 118 ++-- lib/view_component/config.rb | 31 +- lib/view_component/configurable.rb | 6 +- lib/view_component/engine.rb | 16 +- lib/view_component/errors.rb | 155 +++-- lib/view_component/inline_template.rb | 3 +- lib/view_component/instrumentation.rb | 4 +- lib/view_component/preview.rb | 17 +- lib/view_component/serializable.rb | 4 +- lib/view_component/serializable/proxy.rb | 3 + lib/view_component/slot.rb | 39 +- lib/view_component/slotable.rb | 70 +-- lib/view_component/template.rb | 36 +- lib/view_component/test_helpers.rb | 21 +- lib/view_component/translatable.rb | 7 +- performance/boot.rb | 14 +- performance/compare.rb | 45 +- performance/components/inline_component.rb | 2 +- .../components/new_inline_component.rb | 34 +- performance/components/slots_component.rb | 4 +- performance/executor.rb | 19 +- performance/measure.rb | 154 +++-- script/console | 1 + script/format | 6 + script/regression_check.rb | 145 +++-- script/regression_check/runner.rb | 17 +- script/regression_check_history.rb | 103 +++- script/sync_contributors.rb | 33 +- spec/components/feature_spec.rb | 14 +- .../previews/preview_component_spec.rb | 4 +- spec/components/system_spec.rb | 18 +- spec/spec_helper.rb | 7 +- test/docs_rake_task_test.rb | 2 +- test/isolated/template_caching_test.rb | 215 ++++--- .../app/components/action_list_component.rb | 16 +- .../app/components/action_menu_component.rb | 12 +- .../action_menu_panel_wrapper_component.rb | 2 +- .../parent_component.rb | 2 +- .../components/cacheable_call_component.rb | 2 +- .../cacheable_call_partial_component.rb | 2 +- .../cacheable_dynamic_constant_component.rb | 2 +- .../cacheable_inline_partial_component.rb | 8 +- .../cacheable_inline_template_component.rb | 8 +- .../cacheable_plain_dependency_component.rb | 2 +- ...eable_raising_ruby_dependency_component.rb | 2 +- .../cacheable_slot_class_name_component.rb | 8 +- .../app/components/container_component.rb | 2 +- .../app/components/content_eval_component.rb | 5 +- .../controller_inline_with_block_component.rb | 2 +- .../deep_navigation_wrapper_component.rb | 2 +- .../default_form_builder_component.rb | 3 +- .../app/components/inline_component.rb | 4 +- .../inline_trailing_whitespace_component.rb | 8 +- .../components/inline_variant_component.rb | 2 +- test/sandbox/app/components/item_component.rb | 8 +- .../app/components/lambda_slot_component.rb | 9 +- .../components/lambda_slot_inner_component.rb | 21 +- .../components/lambda_slot_outer_component.rb | 12 +- .../lambda_slot_passthrough_component.rb | 2 +- ...mbda_slot_translation_wrapper_component.rb | 2 +- .../app/components/menu_item_component.rb | 12 +- test/sandbox/app/components/nav_component.rb | 12 +- .../nested_shared_state/table_component.rb | 17 +- .../polymorphic_content_slot_component.rb | 15 +- .../components/polymorphic_slot_component.rb | 57 +- .../app/components/section_component.rb | 12 +- .../app/components/serializable_component.rb | 22 +- .../sandbox/app/components/sleep_component.rb | 2 +- .../slot_partial_helper_component.rb | 12 +- .../components/slotable_default_component.rb | 8 +- .../slotable_default_instance_component.rb | 8 +- .../sandbox/app/components/slots_component.rb | 20 +- .../slots_render_predicate_component.rb | 4 +- .../slots_with_empty_lambda_component.rb | 11 +- .../slots_without_content_block_component.rb | 2 +- .../integration_examples_controller.rb | 12 +- .../app/controllers/my_preview_controller.rb | 2 +- .../app/helpers/cacheable_child_helper.rb | 2 +- test/sandbox/config/application.rb | 4 +- test/sandbox/config/boot.rb | 2 +- test/sandbox/config/environment.rb | 1 + .../zzz_complete_initialization.rb | 6 +- test/sandbox/config/routes.rb | 89 +-- test/sandbox/test/base_test.rb | 191 +++--- test/sandbox/test/better_html_test.rb | 5 +- .../test/cacheable_integration_test.rb | 70 +-- test/sandbox/test/cacheable_review_test.rb | 60 +- test/sandbox/test/cacheable_test.rb | 469 +++++++++------ test/sandbox/test/collection_test.rb | 40 +- .../deeply_nested_translation_test.rb | 6 +- ...tive_translation_partial_component_test.rb | 2 +- .../test/components/render_preview_test.rb | 52 +- .../without_preview_component_test.rb | 2 +- test/sandbox/test/config_test.rb | 146 +++-- ...default_preview_layout_integration_test.rb | 24 +- .../generators/component_generator_test.rb | 232 ++++---- .../test/generators/erb_generator_test.rb | 34 +- .../test/generators/haml_generator_test.rb | 22 +- .../test/generators/locale_generator_test.rb | 36 +- .../test/generators/preview_generator_test.rb | 36 +- .../test/generators/rspec_generator_test.rb | 35 +- .../test/generators/slim_generator_test.rb | 22 +- .../generators/stimulus_generator_test.rb | 30 +- .../generators/tailwindcss_generator_test.rb | 18 +- .../generators/test_unit_generator_test.rb | 7 +- test/sandbox/test/initializers/engine_test.rb | 5 +- test/sandbox/test/inline_template_test.rb | 93 +-- test/sandbox/test/instrumentation_test.rb | 25 +- test/sandbox/test/integration_test.rb | 544 +++++++++--------- test/sandbox/test/layouts_test.rb | 8 +- test/sandbox/test/mailer_test.rb | 10 +- test/sandbox/test/rendering_test.rb | 427 +++++++------- test/sandbox/test/reused_instance_test.rb | 18 +- .../security_preview_template_poc_test.rb | 4 +- test/sandbox/test/serializable_test.rb | 103 ++-- test/sandbox/test/slotable_test.rb | 292 +++++----- ...test_entrypoint_path_traversal_poc_test.rb | 4 +- test/sandbox/test/template_annotation_test.rb | 15 +- test/sandbox/test/template_regression_test.rb | 154 ++--- test/sandbox/test/test_helper_test.rb | 102 ++-- test/sandbox/test/translatable_test.rb | 176 +++--- .../test/view_component_system_test.rb | 39 +- test/script/benchmark_workflow_test.rb | 251 ++++---- test/script/performance_test.rb | 27 +- test/script/regression_check_test.rb | 273 +++++---- test/script/release_test.rb | 219 +++---- .../update_dependencies_workflow_test.rb | 52 +- test/test_helper.rb | 7 +- .../test_engine/example_component.rb | 3 +- test_engine/test/config_test.rb | 12 +- .../generators/component_generator_test.rb | 8 +- .../test/generators/preview_generator_test.rb | 4 +- .../generators/test_unit_generator_test.rb | 4 +- test_engine/test_helper.rb | 3 +- view_component.gemspec | 6 +- 176 files changed, 4006 insertions(+), 2980 deletions(-) delete mode 100644 .standard.yml create mode 100755 script/format diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index ae3597a78..24877f609 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -82,6 +82,22 @@ jobs: echo "::error file=CHANGELOG.md,line=1,col=1::Please make sure that you add a docs/CHANGELOG.md entry to describe the changes in this pull request." exit 1 fi + rubyfmt: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + persist-credentials: false + - name: Install rubyfmt + run: | + curl --fail --location --output "$RUNNER_TEMP/rubyfmt.tar.gz" \ + https://github.com/fables-tales/rubyfmt/releases/download/v0.14.1/rubyfmt-v0.14.1-Linux-x86_64.tar.gz + echo "9590cc3b8b2ed37a250a5f7c22a542ce014f13954f613c93a72230de8a74fbbd $RUNNER_TEMP/rubyfmt.tar.gz" | sha256sum --check + mkdir "$RUNNER_TEMP/rubyfmt" + tar -xzf "$RUNNER_TEMP/rubyfmt.tar.gz" -C "$RUNNER_TEMP/rubyfmt" + echo "$RUNNER_TEMP/rubyfmt/tmp/releases/v0.14.1-Linux" >> "$GITHUB_PATH" + - name: Check Ruby formatting + run: script/format --check lint: runs-on: ubuntu-latest steps: @@ -100,7 +116,7 @@ jobs: run: | bundle config path vendor/bundle bundle update - bundle exec standardrb -r "rubocop-md" + bundle exec rubocop bundle exec erb_lint --lint-all env: RAILS_VERSION: '~> 8' diff --git a/.rubocop.yml b/.rubocop.yml index a7861a1ed..929a6889d 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -1,6 +1,31 @@ require: - standard plugins: + - standard-performance - rubocop-md + - rubocop-rubyfmt inherit_gem: - standard: config/base.yml + standard: + - config/default.yml + - config/ruby-3.2.yml + standard-performance: config/base.yml + rubocop-rubyfmt: + - config/default.yml + - config/full.yml + +AllCops: + TargetRubyVersion: 3.2 + Exclude: + - 'vendor/**/*' + - 'docs/CHANGELOG.md' + +Layout: + Enabled: false + +# rubyfmt uses << for multiline string concatenation. +Style/LineEndConcatenation: + Enabled: false + +# rubyfmt keeps parentheses when a local variable shadows the method name. +Style/MethodCallWithoutArgsParentheses: + Enabled: false diff --git a/.standard.yml b/.standard.yml deleted file mode 100644 index 127dd6f8d..000000000 --- a/.standard.yml +++ /dev/null @@ -1,3 +0,0 @@ -ruby_version: 3.2 -ignore: - - 'docs/CHANGELOG.md' # Rubocop doesn't like our indenting of code examples diff --git a/Appraisals b/Appraisals index fae987bf7..53216382f 100644 --- a/Appraisals +++ b/Appraisals @@ -1,45 +1,45 @@ # frozen_string_literal: true -appraise "rails-7.1" do +appraise("rails-7.1") do ruby "~> 3.2" gem "rails", "~> 7.1.0" gem "json", "< 3" group :development, :test do - remove_gem "audition" + remove_gem("audition") gem "turbo-rails", "~> 1" gem "rspec-rails", "~> 7" end end -appraise "rails-7.2" do +appraise("rails-7.2") do ruby "~> 3.3" gem "rails", "~> 7.2.0" gem "json", "< 3" group :development, :test do - remove_gem "audition" + remove_gem("audition") gem "turbo-rails", "~> 2" gem "rspec-rails", "~> 7" end end -appraise "rails-8.0" do +appraise("rails-8.0") do ruby "~> 3.4" gem "rails", "~> 8.0.0" gem "json", "< 3" group :development, :test do - remove_gem "audition" + remove_gem("audition") gem "turbo-rails", "~> 2" gem "rspec-rails", "~> 8" end end -appraise "rails-8.1" do +appraise("rails-8.1") do ruby "~> 4.0" gem "rails", "~> 8.1.0" @@ -50,7 +50,7 @@ appraise "rails-8.1" do end end -appraise "rails-main" do +appraise("rails-main") do ruby "~> 4.0" gem "rack", git: "https://github.com/rack/rack", ref: "8a4475a9f416a72e5b02bd7817e4a8ed684f29b0" @@ -62,7 +62,7 @@ appraise "rails-main" do end end -appraise "rails-main_head" do +appraise("rails-main_head") do ruby "4.1.0.dev" gem "rack", git: "https://github.com/rack/rack", ref: "8a4475a9f416a72e5b02bd7817e4a8ed684f29b0" diff --git a/Gemfile b/Gemfile index 4d97c5c92..66f4d61bf 100644 --- a/Gemfile +++ b/Gemfile @@ -37,6 +37,7 @@ group :development, :test do gem "redis", ">= 4", "< 6" gem "rspec-rails" gem "rubocop-md", "~> 2" + gem "rubocop-rubyfmt", "~> 0.1" gem "simplecov-console", "< 1" gem "simplecov", "< 2" gem "slim", "~> 5" diff --git a/Gemfile.lock b/Gemfile.lock index 6ee36613e..a644b98a6 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -368,6 +368,9 @@ GEM lint_roller (~> 1.1) rubocop (>= 1.75.0, < 2.0) rubocop-ast (>= 1.47.1, < 2.0) + rubocop-rubyfmt (0.1.2) + lint_roller (~> 1.1) + rubocop (>= 1.72.2) ruby-progressbar (1.13.0) rubydex (0.4.4) rubydex (0.4.4-aarch64-linux) @@ -483,6 +486,7 @@ DEPENDENCIES redis (>= 4, < 6) rspec-rails rubocop-md (~> 2) + rubocop-rubyfmt (~> 0.1) simplecov (< 2) simplecov-console (< 1) slim (~> 5) @@ -637,6 +641,7 @@ CHECKSUMS rubocop-ast (1.54.0) sha256=11f7cadec54e593e905b1bb78f2b28bdd4b8e13b34cb82fe49c876e3dd5008c1 rubocop-md (2.0.4) sha256=0d076b6b5e99dea2ddc928c4bd702497decb9a8400da7808091e02ebcafcfb93 rubocop-performance (1.26.1) sha256=cd19b936ff196df85829d264b522fd4f98b6c89ad271fa52744a8c11b8f71834 + rubocop-rubyfmt (0.1.2) sha256=854c50c9133415b4846d20161bfe896bd56dad3ff8eccf755fac8614b587f1cb ruby-progressbar (1.13.0) sha256=80fc9c47a9b640d6834e0dc7b3c94c9df37f08cb072b7761e4a71e22cff29b33 rubydex (0.4.4) sha256=f506bcc9f4ef4c55ac1312392410f95392ce919a4c0b0c36a18f243969bdd2ba rubydex (0.4.4-aarch64-linux) sha256=3638b08b7d683f264eb3215e86974c0f2458c7d63e4aab0c772d625e9e0392ea diff --git a/Rakefile b/Rakefile index e808a5007..b94d351f4 100644 --- a/Rakefile +++ b/Rakefile @@ -30,38 +30,38 @@ Rake::TestTask.new(:engine_test) do |t| t.test_files = FileList["test_engine/**/*_test.rb"] end -desc "Runs benchmarks against components" -task :partial_benchmark do +desc("Runs benchmarks against components") +task(:partial_benchmark) do ruby "./performance/partial_benchmark.rb" end -task :translatable_benchmark do +task(:translatable_benchmark) do ruby "./performance/translatable_benchmark.rb" end -task :slots_benchmark do +task(:slots_benchmark) do ruby "./performance/slots_benchmark.rb" end -task :inline_components_benchmark do +task(:inline_components_benchmark) do ruby "./performance/inline_benchmark.rb" end -namespace :coverage do - task :report do +namespace(:coverage) do + task(:report) do require "simplecov" require "simplecov-console" - SimpleCov.minimum_coverage 100 + SimpleCov.minimum_coverage(100) - SimpleCov.collate Dir["{coverage,simplecov-resultset-*}/.resultset.json"], "rails" do - formatter SimpleCov::Formatter::Console + SimpleCov.collate(Dir["{coverage,simplecov-resultset-*}/.resultset.json"], "rails") do + formatter(SimpleCov::Formatter::Console) end end end -namespace :docs do - task :build do +namespace(:docs) do + task(:build) do YARD::Rake::YardocTask.new do |t| t.options = ["--no-output", "-q"] end @@ -71,16 +71,17 @@ namespace :docs do registry = YARD::RegistryStore.new registry.load!(".yardoc") - meths = - registry - .get("ViewComponent::Base") - .meths - .select do |method| + meths = registry + .get("ViewComponent::Base") + .meths + .select do |method| !method.tag(:private) && method.path.include?("ViewComponent::Base") && method.visibility == :public && - !method[:name].to_s.start_with?("_") # Ignore methods we mark as internal by prefixing with underscores - end.sort_by { |method| method[:name] } + # Ignore methods we mark as internal by prefixing with underscores + !method[:name].to_s.start_with?("_") + end + .sort_by { |method| method[:name] } instance_methods_to_document = meths.select { |method| method.scope != :class } class_methods_to_document = meths.select { |method| method.scope == :class } @@ -90,9 +91,9 @@ namespace :docs do .meths .sort_by { |method| method[:name] } .select do |method| - !method.tag(:private) && - method.visibility == :public - end + !method.tag(:private) && + method.visibility == :public + end require "rails" require "action_controller" @@ -101,33 +102,36 @@ namespace :docs do error_keys = registry.keys.select { |key| key.to_s.include?("Error::MESSAGE") }.map(&:to_s) - docs = ActionController::Base.renderer.render( - ViewComponent::DocsBuilderComponent.new( - sections: [ - ViewComponent::DocsBuilderComponent::Section.new( - heading: "Class methods", - methods: class_methods_to_document - ), - ViewComponent::DocsBuilderComponent::Section.new( - heading: "Instance methods", - methods: instance_methods_to_document - ), - ViewComponent::DocsBuilderComponent::Section.new( - heading: "Configuration", - methods: configuration_methods_to_document, - show_types: false - ), - ViewComponent::DocsBuilderComponent::Section.new( - heading: "ViewComponent::TestHelpers", - methods: test_helper_methods_to_document - ), - ViewComponent::DocsBuilderComponent::Section.new( - heading: "Errors", - error_klasses: error_keys - ) - ] + docs = ActionController::Base + .renderer + .render( + ViewComponent::DocsBuilderComponent.new( + sections: [ + ViewComponent::DocsBuilderComponent::Section.new( + heading: "Class methods", + methods: class_methods_to_document + ), + ViewComponent::DocsBuilderComponent::Section.new( + heading: "Instance methods", + methods: instance_methods_to_document + ), + ViewComponent::DocsBuilderComponent::Section.new( + heading: "Configuration", + methods: configuration_methods_to_document, + show_types: false + ), + ViewComponent::DocsBuilderComponent::Section.new( + heading: "ViewComponent::TestHelpers", + methods: test_helper_methods_to_document + ), + ViewComponent::DocsBuilderComponent::Section.new( + heading: "Errors", + error_klasses: error_keys + ) + ] + ) ) - ).chomp + .chomp if ENV["RAILS_ENV"] != "test" File.open("docs/api.md", "w") do |f| @@ -137,16 +141,20 @@ namespace :docs do end end -desc "Verify the app boots with eager_load=true (catches missing requires)" -task :eager_load_check do - puts "Checking eager loading..." +desc("Verify the app boots with eager_load=true (catches missing requires)") +task(:eager_load_check) do + puts("Checking eager loading...") # Boot a minimal Rails app with eager_load enabled. Using a bare app (no # components) ensures Zeitwerk doesn't accidentally autoload # ViewComponent::Base before processing the engine's controllers — exactly # the scenario that triggers NameError in a fresh host application. result = system( {"RAILS_ENV" => "test"}, - "bundle", "exec", "ruby", "-e", <<~RUBY + "bundle", + "exec", + "ruby", + "-e", + <<~RUBY require "rails" require "action_controller/railtie" require "view_component" @@ -161,66 +169,87 @@ task :eager_load_check do RUBY ) abort("Eager loading check failed!") unless result - puts "Eager loading check passed" + puts("Eager loading check passed") end # Gems that are used, but not loaded by `rake all_tests`. # Older Rails needs redis for eager loading; Rails main uses redis-client. GEMS_NOT_LOADED_BY_TESTS = %w[ - appraisal appraisal-run audition erb_lint m rubocop-md standard yard-lint + appraisal + appraisal-run + audition + erb_lint + m + rubocop-md + rubocop-rubyfmt + standard + yard-lint benchmark-ips - bundler rails - propshaft puma sprockets-rails + bundler + rails + propshaft + puma + sprockets-rails redis -].freeze +] + .freeze -desc "Fail if a gem in the Gemfile or gemspec wasn't loaded by the test suite" -task :unused_gems_check do +desc("Fail if a gem in the Gemfile or gemspec wasn't loaded by the test suite") +task(:unused_gems_check) do loaded = Dir[File.join(ENV.fetch("LOADED_GEMS_DIR"), "*.txt")].flat_map { File.readlines(_1, chomp: true) } - loaded |= Gem.loaded_specs.values.select { |spec| $LOADED_FEATURES.any? { _1.start_with?("#{spec.full_gem_path}/") } }.map(&:name) + loaded |= Gem + .loaded_specs + .values + .select { |spec| $LOADED_FEATURES.any? { _1.start_with?("#{spec.full_gem_path}/") } } + .map(&:name) declared = Bundler.definition.dependencies.map(&:name) - ["view_component"] declared |= Gem::Specification.load("view_component.gemspec").runtime_dependencies.map(&:name) unused = declared - loaded - GEMS_NOT_LOADED_BY_TESTS - abort("Gems not loaded by the test suite, remove them or add them to GEMS_NOT_LOADED_BY_TESTS: #{unused.sort.join(", ")}") if unused.any? - puts "Unused gems check passed" + if unused.any? + abort( + "Gems not loaded by the test suite, remove them or add them to GEMS_NOT_LOADED_BY_TESTS: #{unused.sort.join(", ")}" + ) + end + + puts("Unused gems check passed") end -task :all_tests do +task(:all_tests) do ENV["RAILS_ENV"] = "test" ENV["LOADED_GEMS_DIR"] = Dir.mktmpdir ENV["RUBYOPT"] = "#{ENV["RUBYOPT"]} -r#{File.expand_path("script/record_loaded_gems.rb", __dir__)}" if ENV["MEASURE_COVERAGE"] SimpleCov.start do - command_name "rails#{Rails::VERSION::STRING}-ruby#{RUBY_VERSION}" - enable_coverage :branch - formatter SimpleCov::Formatter::Console + command_name("rails#{Rails::VERSION::STRING}-ruby#{RUBY_VERSION}") + enable_coverage(:branch) + formatter(SimpleCov::Formatter::Console) end end - puts "Checking eager loading" + puts("Checking eager loading") Rake::Task["eager_load_check"].invoke puts puts - puts "Running Minitests" + puts("Running Minitests") Rake::Task["test"].invoke puts puts - puts "Running isolated Minitests" + puts("Running isolated Minitests") Rake::Task["isolated_test"].invoke puts puts - puts "Running Minitests for Rails Engine compatibility" + puts("Running Minitests for Rails Engine compatibility") Rake::Task["engine_test"].invoke puts puts - puts "Running RSpecs" + puts("Running RSpecs") Rake::Task["spec"].invoke puts puts Rake::Task["unused_gems_check"].invoke end -task default: [:all_tests] +task(default: [:all_tests]) diff --git a/app/controllers/concerns/view_component/preview_actions.rb b/app/controllers/concerns/view_component/preview_actions.rb index 3501cce00..cae2cb4bd 100644 --- a/app/controllers/concerns/view_component/preview_actions.rb +++ b/app/controllers/concerns/view_component/preview_actions.rb @@ -20,7 +20,7 @@ module PreviewActions def index @previews = ViewComponent::Preview.all @page_title = "Component Previews" - render "view_components/index", **determine_layout + render("view_components/index", **determine_layout) end def previews @@ -28,7 +28,7 @@ def previews if params[:path] == @preview.preview_name @page_title = "Component Previews for #{@preview.preview_name}" - render "view_components/previews", **determine_layout + render("view_components/previews", **determine_layout) else prepend_application_view_paths prepend_preview_examples_view_path @@ -39,7 +39,7 @@ def previews opts = {} opts[:layout] = layout if layout.present? || layout == false opts[:locals] = locals if locals.present? - render "view_components/preview", opts + render("view_components/preview", opts) end end @@ -59,7 +59,9 @@ def previews_enabled? def find_preview candidates = [] params[:path].to_s.scan(%r{/|$}) { candidates << Regexp.last_match.pre_match } - preview = candidates.sort_by(&:length).reverse_each.detect { |candidate| ViewComponent::Preview.exists?(candidate) } + preview = candidates.sort_by(&:length).reverse_each.detect { |candidate| + ViewComponent::Preview.exists?(candidate) + } if preview @preview = ViewComponent::Preview.find(preview) @@ -95,7 +97,7 @@ def determine_layout(layout_override = nil, prepend_views: true) end def prepend_application_view_paths - prepend_view_path Rails.root.join("app/views") if defined?(Rails.root) + prepend_view_path(Rails.root.join("app/views")) if defined?(Rails.root) end def prepend_preview_examples_view_path diff --git a/app/controllers/view_components_controller.rb b/app/controllers/view_components_controller.rb index 3c4e31e1f..e73c834cb 100644 --- a/app/controllers/view_components_controller.rb +++ b/app/controllers/view_components_controller.rb @@ -2,6 +2,7 @@ require "rails/application_controller" -class ViewComponentsController < Rails::ApplicationController # :nodoc: +# :nodoc: +class ViewComponentsController < Rails::ApplicationController include ViewComponent::PreviewActions end diff --git a/app/controllers/view_components_system_test_controller.rb b/app/controllers/view_components_system_test_controller.rb index b5972a2c7..8c55c3181 100644 --- a/app/controllers/view_components_system_test_controller.rb +++ b/app/controllers/view_components_system_test_controller.rb @@ -2,7 +2,8 @@ require "view_component/errors" -class ViewComponentsSystemTestController < ActionController::Base # :nodoc: +# :nodoc: +class ViewComponentsSystemTestController < ActionController::Base if Rails.env.test? before_action :validate_file_path @@ -14,13 +15,13 @@ def self.temp_dir rescue_from Errno::ENOENT, with: :render_not_found def system_test_entrypoint - render file: @path + render(file: @path) end private def render_not_found - head :not_found + head(:not_found) end # Ensure that the file path is valid and doesn't target files outside diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index a05ca2b80..dcfce9319 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -10,6 +10,10 @@ nav_order: 6 ## main +* Adopt rubyfmt for Ruby formatting while retaining compatible Standard lint rules. + + *Joel Hawksley* + * Fix gem publishing workflow failures when waiting for a release to propagate on RubyGems. *Joel Hawksley* diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.md index c85633d49..cc78751e7 100644 --- a/docs/CONTRIBUTING.md +++ b/docs/CONTRIBUTING.md @@ -87,6 +87,18 @@ Use [`m`](https://rubygems.org/gems/m): bundle exec m test/view_component/YOUR_COMPONENT_test.rb:line_number ``` +### Ruby formatting and linting + +Install [rubyfmt](https://github.com/fables-tales/rubyfmt) (`brew install rubyfmt` on macOS). +CI uses rubyfmt 0.14.1. + +Run `script/format --in-place` to format tracked Ruby files, including Gemfiles and the Rakefile. +Stage new files first, or format them directly with `rubyfmt --in-place path/to/file.rb`. +Run `script/format --check` to check formatting without changing files. + +Run `bundle exec rubocop` for compatible Standard lint rules and Ruby examples in Markdown. +Run `bundle exec erb_lint --lint-all` for ERB linting. + ### Running tests for a specific version of Rails Specify one of the supported versions listed in [Appraisals](https://github.com/viewcomponent/view_component/blob/main/Appraisals): diff --git a/docs/Gemfile b/docs/Gemfile index cdf0567ab..5f389858a 100644 --- a/docs/Gemfile +++ b/docs/Gemfile @@ -7,7 +7,7 @@ gem "webrick" # Windows and JRuby doesn't include zoneinfo files, so bundle the tzinfo-data gem # and associated library. -platforms :mingw, :x64_mingw, :mswin, :jruby do +platforms(:mingw, :x64_mingw, :mswin, :jruby) do gem "tzinfo", "~> 1.2" gem "tzinfo-data" end diff --git a/gemfiles/rails_7.1.gemfile b/gemfiles/rails_7.1.gemfile index 97bab5e9f..04d06b9cd 100644 --- a/gemfiles/rails_7.1.gemfile +++ b/gemfiles/rails_7.1.gemfile @@ -33,6 +33,7 @@ group :development, :test do gem "redis", ">= 4", "< 6" gem "rspec-rails", "~> 7" gem "rubocop-md", "~> 2" + gem "rubocop-rubyfmt", "~> 0.1" gem "simplecov-console", "< 1" gem "simplecov", "< 2" gem "slim", "~> 5" @@ -45,4 +46,4 @@ group :development, :test do gem "yard", "< 1" end -gemspec path: "../" +gemspec(path: "../") diff --git a/gemfiles/rails_7.1.gemfile.lock b/gemfiles/rails_7.1.gemfile.lock index 064825331..939f78b84 100644 --- a/gemfiles/rails_7.1.gemfile.lock +++ b/gemfiles/rails_7.1.gemfile.lock @@ -351,6 +351,9 @@ GEM lint_roller (~> 1.1) rubocop (>= 1.75.0, < 2.0) rubocop-ast (>= 1.47.1, < 2.0) + rubocop-rubyfmt (0.1.2) + lint_roller (~> 1.1) + rubocop (>= 1.72.2) ruby-progressbar (1.13.0) securerandom (0.4.1) simplecov (1.2.0) @@ -455,6 +458,7 @@ DEPENDENCIES redis (>= 4, < 6) rspec-rails (~> 7) rubocop-md (~> 2) + rubocop-rubyfmt (~> 0.1) simplecov (< 2) simplecov-console (< 1) slim (~> 5) diff --git a/gemfiles/rails_7.2.gemfile b/gemfiles/rails_7.2.gemfile index 05902aae2..a5b4b9e66 100644 --- a/gemfiles/rails_7.2.gemfile +++ b/gemfiles/rails_7.2.gemfile @@ -33,6 +33,7 @@ group :development, :test do gem "redis", ">= 4", "< 6" gem "rspec-rails", "~> 7" gem "rubocop-md", "~> 2" + gem "rubocop-rubyfmt", "~> 0.1" gem "simplecov-console", "< 1" gem "simplecov", "< 2" gem "slim", "~> 5" @@ -45,4 +46,4 @@ group :development, :test do gem "yard", "< 1" end -gemspec path: "../" +gemspec(path: "../") diff --git a/gemfiles/rails_7.2.gemfile.lock b/gemfiles/rails_7.2.gemfile.lock index 0c4ff7eda..aaae28219 100644 --- a/gemfiles/rails_7.2.gemfile.lock +++ b/gemfiles/rails_7.2.gemfile.lock @@ -351,6 +351,9 @@ GEM lint_roller (~> 1.1) rubocop (>= 1.75.0, < 2.0) rubocop-ast (>= 1.47.1, < 2.0) + rubocop-rubyfmt (0.1.2) + lint_roller (~> 1.1) + rubocop (>= 1.72.2) ruby-progressbar (1.13.0) securerandom (0.4.1) simplecov (1.3.2) @@ -455,6 +458,7 @@ DEPENDENCIES redis (>= 4, < 6) rspec-rails (~> 7) rubocop-md (~> 2) + rubocop-rubyfmt (~> 0.1) simplecov (< 2) simplecov-console (< 1) slim (~> 5) diff --git a/gemfiles/rails_8.0.gemfile b/gemfiles/rails_8.0.gemfile index 068c88efe..2365a7d8d 100644 --- a/gemfiles/rails_8.0.gemfile +++ b/gemfiles/rails_8.0.gemfile @@ -33,6 +33,7 @@ group :development, :test do gem "redis", ">= 4", "< 6" gem "rspec-rails", "~> 8" gem "rubocop-md", "~> 2" + gem "rubocop-rubyfmt", "~> 0.1" gem "simplecov-console", "< 1" gem "simplecov", "< 2" gem "slim", "~> 5" @@ -45,4 +46,4 @@ group :development, :test do gem "yard", "< 1" end -gemspec path: "../" +gemspec(path: "../") diff --git a/gemfiles/rails_8.0.gemfile.lock b/gemfiles/rails_8.0.gemfile.lock index 9357f9d06..88e89784e 100644 --- a/gemfiles/rails_8.0.gemfile.lock +++ b/gemfiles/rails_8.0.gemfile.lock @@ -347,6 +347,9 @@ GEM lint_roller (~> 1.1) rubocop (>= 1.75.0, < 2.0) rubocop-ast (>= 1.47.1, < 2.0) + rubocop-rubyfmt (0.1.2) + lint_roller (~> 1.1) + rubocop (>= 1.72.2) ruby-progressbar (1.13.0) securerandom (0.4.1) simplecov (1.3.2) @@ -452,6 +455,7 @@ DEPENDENCIES redis (>= 4, < 6) rspec-rails (~> 8) rubocop-md (~> 2) + rubocop-rubyfmt (~> 0.1) simplecov (< 2) simplecov-console (< 1) slim (~> 5) diff --git a/gemfiles/rails_8.1.gemfile b/gemfiles/rails_8.1.gemfile index 0a32865bd..ff6f5bb0d 100644 --- a/gemfiles/rails_8.1.gemfile +++ b/gemfiles/rails_8.1.gemfile @@ -33,6 +33,7 @@ group :development, :test do gem "redis", ">= 4", "< 6" gem "rspec-rails", "~> 8" gem "rubocop-md", "~> 2" + gem "rubocop-rubyfmt", "~> 0.1" gem "simplecov-console", "< 1" gem "simplecov", "< 2" gem "slim", "~> 5" @@ -45,4 +46,4 @@ group :development, :test do gem "yard", "< 1" end -gemspec path: "../" +gemspec(path: "../") diff --git a/gemfiles/rails_8.1.gemfile.lock b/gemfiles/rails_8.1.gemfile.lock index a6ea1c6b5..198e90df5 100644 --- a/gemfiles/rails_8.1.gemfile.lock +++ b/gemfiles/rails_8.1.gemfile.lock @@ -368,6 +368,9 @@ GEM lint_roller (~> 1.1) rubocop (>= 1.75.0, < 2.0) rubocop-ast (>= 1.47.1, < 2.0) + rubocop-rubyfmt (0.1.2) + lint_roller (~> 1.1) + rubocop (>= 1.72.2) ruby-progressbar (1.13.0) rubydex (0.4.4) rubydex (0.4.4-aarch64-linux) @@ -483,6 +486,7 @@ DEPENDENCIES redis (>= 4, < 6) rspec-rails (~> 8) rubocop-md (~> 2) + rubocop-rubyfmt (~> 0.1) simplecov (< 2) simplecov-console (< 1) slim (~> 5) diff --git a/gemfiles/rails_main.gemfile b/gemfiles/rails_main.gemfile index b487d9cdf..9505e0446 100644 --- a/gemfiles/rails_main.gemfile +++ b/gemfiles/rails_main.gemfile @@ -34,6 +34,7 @@ group :development, :test do gem "redis", ">= 4", "< 6" gem "rspec-rails", "~> 8" gem "rubocop-md", "~> 2" + gem "rubocop-rubyfmt", "~> 0.1" gem "simplecov-console", "< 1" gem "simplecov", "< 2" gem "slim", "~> 5" @@ -46,4 +47,4 @@ group :development, :test do gem "yard", "< 1" end -gemspec path: "../" +gemspec(path: "../") diff --git a/gemfiles/rails_main.gemfile.lock b/gemfiles/rails_main.gemfile.lock index d7b76fb93..6414a2d65 100644 --- a/gemfiles/rails_main.gemfile.lock +++ b/gemfiles/rails_main.gemfile.lock @@ -380,6 +380,9 @@ GEM lint_roller (~> 1.1) rubocop (>= 1.75.0, < 2.0) rubocop-ast (>= 1.47.1, < 2.0) + rubocop-rubyfmt (0.1.2) + lint_roller (~> 1.1) + rubocop (>= 1.72.2) ruby-progressbar (1.13.0) rubydex (0.4.4) rubydex (0.4.4-aarch64-linux) @@ -497,6 +500,7 @@ DEPENDENCIES redis (>= 4, < 6) rspec-rails (~> 8) rubocop-md (~> 2) + rubocop-rubyfmt (~> 0.1) simplecov (< 2) simplecov-console (< 1) slim (~> 5) @@ -646,6 +650,7 @@ CHECKSUMS rubocop-ast (1.54.0) sha256=11f7cadec54e593e905b1bb78f2b28bdd4b8e13b34cb82fe49c876e3dd5008c1 rubocop-md (2.0.4) sha256=0d076b6b5e99dea2ddc928c4bd702497decb9a8400da7808091e02ebcafcfb93 rubocop-performance (1.26.1) sha256=cd19b936ff196df85829d264b522fd4f98b6c89ad271fa52744a8c11b8f71834 + rubocop-rubyfmt (0.1.2) sha256=854c50c9133415b4846d20161bfe896bd56dad3ff8eccf755fac8614b587f1cb ruby-progressbar (1.13.0) sha256=80fc9c47a9b640d6834e0dc7b3c94c9df37f08cb072b7761e4a71e22cff29b33 rubydex (0.4.4) sha256=f506bcc9f4ef4c55ac1312392410f95392ce919a4c0b0c36a18f243969bdd2ba rubydex (0.4.4-aarch64-linux) sha256=3638b08b7d683f264eb3215e86974c0f2458c7d63e4aab0c772d625e9e0392ea diff --git a/gemfiles/rails_main_head.gemfile b/gemfiles/rails_main_head.gemfile index e01173e2c..b2ccc59c5 100644 --- a/gemfiles/rails_main_head.gemfile +++ b/gemfiles/rails_main_head.gemfile @@ -34,6 +34,7 @@ group :development, :test do gem "redis", ">= 4", "< 6" gem "rspec-rails", "~> 8" gem "rubocop-md", "~> 2" + gem "rubocop-rubyfmt", "~> 0.1" gem "simplecov-console", "< 1" gem "simplecov", "< 2" gem "slim", "~> 5" @@ -46,4 +47,4 @@ group :development, :test do gem "yard", "< 1" end -gemspec path: "../" +gemspec(path: "../") diff --git a/gemfiles/rails_main_head.gemfile.lock b/gemfiles/rails_main_head.gemfile.lock index 5ff1b28ef..39ba20395 100644 --- a/gemfiles/rails_main_head.gemfile.lock +++ b/gemfiles/rails_main_head.gemfile.lock @@ -347,6 +347,9 @@ GEM lint_roller (~> 1.1) rubocop (>= 1.75.0, < 2.0) rubocop-ast (>= 1.47.1, < 2.0) + rubocop-rubyfmt (0.1.2) + lint_roller (~> 1.1) + rubocop (>= 1.72.2) ruby-progressbar (1.13.0) rubydex (0.4.4) securerandom (0.4.1) @@ -454,6 +457,7 @@ DEPENDENCIES redis (>= 4, < 6) rspec-rails (~> 8) rubocop-md (~> 2) + rubocop-rubyfmt (~> 0.1) simplecov (< 2) simplecov-console (< 1) slim (~> 5) diff --git a/lib/docs/docs_builder_component.rb b/lib/docs/docs_builder_component.rb index 479362aaf..960f3d84e 100644 --- a/lib/docs/docs_builder_component.rb +++ b/lib/docs/docs_builder_component.rb @@ -24,11 +24,13 @@ def error_message end def call - <<~DOCS.chomp.html_safe + <<~DOCS `#{klass_name}` #{error_message} DOCS + .chomp + .html_safe end end @@ -70,19 +72,23 @@ def deprecation_text # :nocov: def docstring_and_deprecation_text - <<~DOCS.strip.html_safe + <<~DOCS #{docstring} #{"_#{deprecation_text}_" if deprecated?} DOCS + .strip + .html_safe end def call - <<~DOCS.chomp.html_safe + <<~DOCS `#{separator}#{signature_or_name}`#{types}#{suffix} #{docstring_and_deprecation_text} DOCS + .chomp + .html_safe end end diff --git a/lib/generators/view_component/abstract_generator.rb b/lib/generators/view_component/abstract_generator.rb index c1dc8ea62..e37247ee9 100644 --- a/lib/generators/view_component/abstract_generator.rb +++ b/lib/generators/view_component/abstract_generator.rb @@ -3,7 +3,7 @@ module ViewComponent module AbstractGenerator def self.included(generator) - generator.class_option :skip_suffix, type: :boolean, default: false + generator.class_option(:skip_suffix, type: :boolean, default: false) end def initialize(...) @@ -54,7 +54,8 @@ def component_path def stimulus_controller if stimulus? - File.join(destination_directory, destination_file_name) + File + .join(destination_directory, destination_file_name) .sub("#{component_path}/", "") .tr("_", "-") .gsub("/", "--") diff --git a/lib/generators/view_component/component/component_generator.rb b/lib/generators/view_component/component/component_generator.rb index 3e126c5da..b85d2b499 100644 --- a/lib/generators/view_component/component/component_generator.rb +++ b/lib/generators/view_component/component/component_generator.rb @@ -21,11 +21,11 @@ class ComponentGenerator < Rails::Generators::NamedBase class_option :typescript, type: :boolean def check_class_collision - class_collisions component_class_name + class_collisions(component_class_name) end def create_component_file - template "component.rb", File.join(component_path, class_path, "#{destination_file_name}.rb") + template("component.rb", File.join(component_path, class_path, "#{destination_file_name}.rb")) end hook_for :test_framework diff --git a/lib/generators/view_component/locale/locale_generator.rb b/lib/generators/view_component/locale/locale_generator.rb index fbada6bc3..2a138abd9 100644 --- a/lib/generators/view_component/locale/locale_generator.rb +++ b/lib/generators/view_component/locale/locale_generator.rb @@ -14,10 +14,10 @@ class LocaleGenerator < ::Rails::Generators::NamedBase def create_locale_file if ViewComponent::Base.config.generate.distinct_locale_files I18n.available_locales.each do |locale| - create_file destination(locale), translations_hash([locale]).to_yaml + create_file(destination(locale), translations_hash([locale]).to_yaml) end else - create_file destination, translations_hash(I18n.available_locales).to_yaml + create_file(destination, translations_hash(I18n.available_locales).to_yaml) end end diff --git a/lib/generators/view_component/preview/preview_generator.rb b/lib/generators/view_component/preview/preview_generator.rb index f522f5ef1..9f50ce681 100644 --- a/lib/generators/view_component/preview/preview_generator.rb +++ b/lib/generators/view_component/preview/preview_generator.rb @@ -8,12 +8,17 @@ class PreviewGenerator < ::Rails::Generators::NamedBase include ViewComponent::AbstractGenerator source_root File.expand_path("templates", __dir__) - class_option :preview_path, type: :string, desc: "Path for previews, required when multiple preview paths are configured", default: ViewComponent::Base.config.generate.preview_path + class_option( + :preview_path, + type: :string, + desc: "Path for previews, required when multiple preview paths are configured", + default: ViewComponent::Base.config.generate.preview_path + ) argument :attributes, type: :array, default: [], banner: "attribute" def check_class_collision - class_collisions "#{component_class_name}Preview" + class_collisions("#{component_class_name}Preview") end def create_preview_file @@ -27,7 +32,7 @@ def create_preview_file preview_paths.one? ? preview_paths.first : "test/components/previews" end - template "component_preview.rb", File.join(path_prefix, class_path, "#{destination_file_name}_preview.rb") + template("component_preview.rb", File.join(path_prefix, class_path, "#{destination_file_name}_preview.rb")) end private @@ -35,7 +40,7 @@ def create_preview_file def render_signature return if attributes.blank? - attributes.map { |attr| %(#{attr.name}: "#{attr.name}") }.join(", ") + attributes.map { |attr| "#{attr.name}: \"#{attr.name}\"" }.join(", ") end end end diff --git a/lib/generators/view_component/rspec/rspec_generator.rb b/lib/generators/view_component/rspec/rspec_generator.rb index 01fa9cd45..73bc5c342 100644 --- a/lib/generators/view_component/rspec/rspec_generator.rb +++ b/lib/generators/view_component/rspec/rspec_generator.rb @@ -10,7 +10,7 @@ class RspecGenerator < ::Rails::Generators::NamedBase source_root File.expand_path("templates", __dir__) def create_test_file - template "component_spec.rb", File.join(spec_component_path, class_path, "#{destination_file_name}_spec.rb") + template("component_spec.rb", File.join(spec_component_path, class_path, "#{destination_file_name}_spec.rb")) end private diff --git a/lib/generators/view_component/stimulus/stimulus_generator.rb b/lib/generators/view_component/stimulus/stimulus_generator.rb index 583042445..3215cae69 100644 --- a/lib/generators/view_component/stimulus/stimulus_generator.rb +++ b/lib/generators/view_component/stimulus/stimulus_generator.rb @@ -12,7 +12,7 @@ class StimulusGenerator < ::Rails::Generators::NamedBase class_option :typescript, type: :boolean def create_stimulus_controller - template "component_controller.#{filetype}", destination + template("component_controller.#{filetype}", destination) end def stimulus_module diff --git a/lib/generators/view_component/test_unit/test_unit_generator.rb b/lib/generators/view_component/test_unit/test_unit_generator.rb index 27e1f53ab..17a5e740d 100644 --- a/lib/generators/view_component/test_unit/test_unit_generator.rb +++ b/lib/generators/view_component/test_unit/test_unit_generator.rb @@ -10,11 +10,11 @@ class TestUnitGenerator < ::Rails::Generators::NamedBase source_root File.expand_path("templates", __dir__) def check_class_collision - class_collisions "#{component_class_name}Test" + class_collisions("#{component_class_name}Test") end def create_test_file - template "component_test.rb", File.join("test/components", class_path, "#{destination_file_name}_test.rb") + template("component_test.rb", File.join("test/components", class_path, "#{destination_file_name}_test.rb")) end end end diff --git a/lib/view_component/base.rb b/lib/view_component/base.rb index 2d0f8a705..9855df683 100644 --- a/lib/view_component/base.rb +++ b/lib/view_component/base.rb @@ -61,6 +61,7 @@ def config module_parent_config = module_parent.config.try(:view_component) return module_parent_config if module_parent_config end + ViewComponent::Config.current end end @@ -131,6 +132,7 @@ def render_in(view_context, **, &block) else __vc_render_uncached(view_context, &block) end + ensure @__vc_rendered = true end @@ -162,7 +164,8 @@ def render_parent # # When rendering the parent inside an .erb template, use `#render_parent` instead. def render_parent_to_string - @__vc_parent_render_level ||= 0 # ensure a good starting value + # ensure a good starting value + @__vc_parent_render_level ||= 0 old_current_template = @current_template begin @@ -297,15 +300,25 @@ def helpers if defined?(Rails.env) && (::Rails.env.development? || ::Rails.env.test?) # @private - def method_missing(method_name, *args) # rubocop:disable Style/MissingRespondToMissing + # rubocop:disable Style/MissingRespondToMissing + def method_missing(method_name, *args) + # rubocop:enable Style/MissingRespondToMissing super - rescue => e # rubocop:disable Style/RescueStandardError - e.set_backtrace e.backtrace.tap(&:shift) - raise e, <<~MESSAGE.chomp if view_context && e.is_a?(NameError) && helpers.respond_to?(method_name) - #{e.message} - - You may be trying to call a method provided as a view helper. Did you mean `helpers.#{method_name}`? - MESSAGE + # rubocop:disable Style/RescueStandardError + rescue => e + # rubocop:enable Style/RescueStandardError + e.set_backtrace(e.backtrace.tap(&:shift)) + if view_context && e.is_a?(NameError) && helpers.respond_to?(method_name) + raise( + e, + <<~MESSAGE + #{e.message} + + You may be trying to call a method provided as a view helper. Did you mean `helpers.#{method_name}`? + MESSAGE + .chomp + ) + end raise end @@ -353,14 +366,13 @@ def content @__vc_content_evaluated = true return @__vc_content if defined?(@__vc_content) - @__vc_content = - if __vc_render_in_block_provided? - with_captured_virtual_path(@old_virtual_path) do - view_context.capture(self, &@__vc_render_in_block) - end - elsif __vc_content_set_by_with_content_defined? - @__vc_content_set_by_with_content + @__vc_content = if __vc_render_in_block_provided? + with_captured_virtual_path(@old_virtual_path) do + view_context.capture(self, &@__vc_render_in_block) end + elsif __vc_content_set_by_with_content_defined? + @__vc_content_set_by_with_content + end end # Whether `content` has been passed to the component. @@ -465,7 +477,9 @@ def __vc_render_uncached(view_context, &block) end end - if ActionView::Base.annotate_rendered_view_with_filenames && current_template.inline_call? && request&.format == :html + if ActionView::Base.annotate_rendered_view_with_filenames && + current_template.inline_call? && + request&.format == :html identifier = defined?(Rails.root) ? self.class.identifier.sub("#{Rails.root}/", "") : self.class.identifier value = "".html_safe + value + "".html_safe end @@ -474,6 +488,7 @@ def __vc_render_uncached(view_context, &block) else "".html_safe end + ensure view_context.instance_variable_set(:@virtual_path, old_virtual_path) @current_template = old_current_template @@ -498,19 +513,25 @@ def __vc_maybe_escape_html(text) def __vc_safe_output_preamble __vc_maybe_escape_html(output_preamble) do - Kernel.warn("WARNING: The #{self.class} component was provided an HTML-unsafe preamble. The preamble will be automatically escaped, but you may want to investigate.") + Kernel.warn( + "WARNING: The #{self.class} component was provided an HTML-unsafe preamble. The preamble will be automatically escaped, but you may want to investigate." + ) end end def __vc_safe_output_postamble __vc_maybe_escape_html(output_postamble) do - Kernel.warn("WARNING: The #{self.class} component was provided an HTML-unsafe postamble. The postamble will be automatically escaped, but you may want to investigate.") + Kernel.warn( + "WARNING: The #{self.class} component was provided an HTML-unsafe postamble. The postamble will be automatically escaped, but you may want to investigate." + ) end end def __vc_safe_around_render_output(output) __vc_maybe_escape_html(output) do - Kernel.warn("WARNING: The #{self.class} component's around_render returned an HTML-unsafe string. The output will be automatically escaped, but you may want to investigate.") + Kernel.warn( + "WARNING: The #{self.class} component's around_render returned an HTML-unsafe string. The output will be automatically escaped, but you may want to investigate." + ) end end @@ -652,12 +673,11 @@ def sidecar_files(extensions) # end # # Without this, `MyOtherComponent` will not look for `my_component/my_other_component.html.erb` - nested_component_files = - if name.include?("::") && component_name != filename - __vc_files_ending_with(extensions, "#{directory}/#{filename}/#{component_name}.*") - else - [] - end + nested_component_files = if name.include?("::") && component_name != filename + __vc_files_ending_with(extensions, "#{directory}/#{filename}/#{component_name}.*") + else + [] + end # view files in the same directory as the component sidecar_files = __vc_files_ending_with(extensions, "#{directory}/#{component_name}.*") @@ -706,15 +726,19 @@ def inherited(child) # such a scenario, the parent will override ViewComponent::Base#render_template_for, # meaning it will not be called for any children and thus not compile their templates. if !child.method_defined?(:render_template_for, false) && !child.__vc_compiled? - child.class_eval <<~RUBY, __FILE__, __LINE__ + 1 - def render_template_for(requested_details) - # Force compilation here so the compiler always redefines render_template_for. - # This is mostly a safeguard to prevent infinite recursion. - self.class.__vc_compile(raise_errors: true, force: true) - # .__vc_compile replaces this method; call the new one - render_template_for(requested_details) - end - RUBY + child.class_eval( + <<~RUBY, + def render_template_for(requested_details) + # Force compilation here so the compiler always redefines render_template_for. + # This is mostly a safeguard to prevent infinite recursion. + self.class.__vc_compile(raise_errors: true, force: true) + # .__vc_compile replaces this method; call the new one + render_template_for(requested_details) + end + RUBY + __FILE__, + __LINE__ - 9 + ) end # Derive the source location of the component Ruby file from the call stack. @@ -863,13 +887,14 @@ def __vc_iteration_argument_present? # @private def __vc_build_collection_arguments - names = - if respond_to?(:attribute_names) - attribute_names.map(&:to_sym) - else - __vc_initialize_signatures.flat_map { |_owner, parameters| parameters.map(&:last) } - end - parameter = __vc_provided_collection_parameter || (name && name.demodulize.underscore.chomp("_component").to_sym) + names = if respond_to?(:attribute_names) + attribute_names.map(&:to_sym) + else + __vc_initialize_signatures.flat_map { |_owner, parameters| parameters.map(&:last) } + end + + parameter = __vc_provided_collection_parameter || + (name && name.demodulize.underscore.chomp("_component").to_sym) counter_parameter = :"#{parameter}_counter" iteration_parameter = :"#{parameter}_iteration" @@ -897,7 +922,9 @@ def __vc_collection_parameter_accepted?(parameter) end def __vc_splatted_keyword_argument_present? - prepended_modules = ancestors.grep(Class).flat_map { |klass| klass.ancestors.take_while { |mod| mod != klass } } + prepended_modules = ancestors.grep(Class).flat_map { |klass| + klass.ancestors.take_while { |mod| mod != klass } + } __vc_initialize_signatures.any? do |owner, parameters| parameters.any? do |type, name| @@ -919,6 +946,7 @@ def __vc_initialize_signatures method = method.super_method end + signatures end diff --git a/lib/view_component/cache_digest.rb b/lib/view_component/cache_digest.rb index 334180c83..10caae55f 100644 --- a/lib/view_component/cache_digest.rb +++ b/lib/view_component/cache_digest.rb @@ -133,6 +133,7 @@ def template_dependencies?(source, handler) return true if code.match?(/render|[A-Z]/) end + false else true @@ -162,7 +163,8 @@ def renders_in(source, name, view_paths: nil, nesting: []) # the same superclass, so it's scanned once per digest computation. memoize([:renders_in, source, name, view_paths, nesting]) do components, _component_calls, other_calls = partition_render_calls(Prism.parse(source).value, nesting) - partials = partials_rendered_by(other_calls, name) - unresolved_partials_rendered_by(other_calls, name, view_paths) + partials = partials_rendered_by(other_calls, name) - + unresolved_partials_rendered_by(other_calls, name, view_paths) [component_paths(components), partials] end end @@ -452,7 +454,9 @@ def partials_rendered_by(calls, name) end def partial_paths_in(source, name) - RENDER_PARSER.new(name, source).render_calls + RENDER_PARSER + .new(name, source) + .render_calls .map { |path| path.gsub(%r{/_}, "/") } .uniq end @@ -466,6 +470,7 @@ def unresolved_partials_rendered_by(calls, name, view_paths) literal, dynamic = targets.partition do |target| target.is_a?(Prism::StringNode) || target.is_a?(Prism::InterpolatedStringNode) end + interpolated = literal.grep(Prism::InterpolatedStringNode) unresolved = [] if interpolated.any? @@ -476,36 +481,43 @@ def unresolved_partials_rendered_by(calls, name, view_paths) static = literal.grep(Prism::StringNode) unresolved -= partial_paths_in(static.map { |target| "render(#{target.slice})" }.join("\n"), name) end + return unresolved unless view_paths && dynamic.any? inferred = partial_paths_in(dynamic.map { |target| "render(#{target.slice})" }.join("\n"), name) declared = partial_paths_in(literal.map { |target| "render(#{target.slice})" }.join("\n"), name) finder = ActionView::LookupContext.new(view_paths, variants: :any, locale: I18n.available_locales) - unresolved | inferred.reject do |path| - declared.include?(path) || finder.exists?(path, [], true) - end + unresolved | + inferred.reject do |path| + declared.include?(path) || finder.exists?(path, [], true) + end end def render_targets(call) arguments = call.arguments&.arguments || [] - targets = arguments.flat_map do |argument| - if argument.is_a?(Prism::KeywordHashNode) || argument.is_a?(Prism::HashNode) - argument.elements.filter_map do |element| - next unless element.is_a?(Prism::AssocNode) && element.key.is_a?(Prism::SymbolNode) - next unless %w[partial template layout spacer_template].include?(element.key.unescaped) - - element.value + targets = arguments + .flat_map do |argument| + if argument.is_a?(Prism::KeywordHashNode) || argument.is_a?(Prism::HashNode) + argument.elements.filter_map do |element| + next unless element.is_a?(Prism::AssocNode) && element.key.is_a?(Prism::SymbolNode) + next unless %w[partial template layout spacer_template].include?(element.key.unescaped) + + element.value + end + elsif argument.equal?(arguments.first) + argument end - elsif argument.equal?(arguments.first) - argument end - end.compact + .compact targets.map do |target| - while target.is_a?(Prism::ParenthesesNode) && target.body.is_a?(Prism::StatementsNode) && target.body.body.one? + while target.is_a?(Prism::ParenthesesNode) && + target.body.is_a?(Prism::StatementsNode) && + target.body.body.one? target = target.body.body.first end + target end end diff --git a/lib/view_component/cache_digest/dependency_tracking.rb b/lib/view_component/cache_digest/dependency_tracking.rb index 1b6fee496..57bf3fd5a 100644 --- a/lib/view_component/cache_digest/dependency_tracking.rb +++ b/lib/view_component/cache_digest/dependency_tracking.rb @@ -51,8 +51,12 @@ def find_dependencies(name, template, view_paths = nil) end end - component_paths, inferred_partials = - CacheDigest.template_renders_in(CacheDigest.compiled_source(template), name, view_paths: view_paths, &tracker) + component_paths, inferred_partials = CacheDigest.template_renders_in( + CacheDigest.compiled_source(template), + name, + view_paths: view_paths, + &tracker + ) # Older ERB trackers omit the underscore on unqualified partial paths. inferred_partials |= inferred_partials.map { |path| path.delete_prefix("_") } declared = source.scan(CacheDigest::EXPLICIT_DEPENDENCY).flatten diff --git a/lib/view_component/cache_digest/digestor_lookup.rb b/lib/view_component/cache_digest/digestor_lookup.rb index f629152cb..83efddd56 100644 --- a/lib/view_component/cache_digest/digestor_lookup.rb +++ b/lib/view_component/cache_digest/digestor_lookup.rb @@ -35,6 +35,7 @@ def digest(finder:, **) finder.digest_cache.clear end + ensure CacheDigest.memo[:pruned] = previous end @@ -56,7 +57,12 @@ def tree(name, finder, partial = false, seen = {}) next super unless template pruned[name] = cached - seen[template.identifier] ||= ActionView::Digestor::Node.create(name, name.gsub(%r{/_}, "/"), template, partial) + seen[template.identifier] ||= ActionView::Digestor::Node.create( + name, + name.gsub(%r{/_}, "/"), + template, + partial + ) end end @@ -65,9 +71,16 @@ def tree(name, finder, partial = false, seen = {}) def find_template(finder, name, prefixes, partial, keys) key = [:template, name, prefixes.first, partial, finder.formats, finder.view_paths] template = CacheDigest.memoize(key) do - Resolver.instance.find_templates( - name, prefixes.first, partial, {formats: finder.formats}, view_paths: finder.view_paths - ).first + Resolver + .instance + .find_templates( + name, + prefixes.first, + partial, + {formats: finder.formats}, + view_paths: finder.view_paths + ) + .first end template || super diff --git a/lib/view_component/cache_digest/resolver.rb b/lib/view_component/cache_digest/resolver.rb index 4dd30c9e3..9588c7bf0 100644 --- a/lib/view_component/cache_digest/resolver.rb +++ b/lib/view_component/cache_digest/resolver.rb @@ -43,11 +43,13 @@ def find_templates(name, prefix, partial, details, locals = [], view_paths: Acti def to_s "ViewComponent::CacheDigest::Resolver" end + alias_method :to_path, :to_s def eql?(other) self.class.equal?(other.class) end + alias_method :==, :eql? # The synthetic source. Every section exists to change this string when @@ -78,11 +80,12 @@ def source_for(component) # the template sources, where they'd also infer partials from component # renders. dependencies(component, templates).each do |dependency| - parts << if dependency.start_with?(RELATIVE_PARTIAL_PREFIX) - "<%# Relative Template Dependency: #{dependency.delete_prefix(RELATIVE_PARTIAL_PREFIX)} %>" - else - "<%# Template Dependency: #{dependency} %>" - end + parts << + if dependency.start_with?(RELATIVE_PARTIAL_PREFIX) + "<%# Relative Template Dependency: #{dependency.delete_prefix(RELATIVE_PARTIAL_PREFIX)} %>" + else + "<%# Template Dependency: #{dependency} %>" + end end # Content hashes of the templates, including inline ones. @@ -115,9 +118,11 @@ def resolve_relative_dependencies(source, view_paths) paths = view_paths.flat_map(&:all_template_paths).uniq source.gsub(RELATIVE_DEPENDENCY) do name = Regexp.last_match(1) - matches = paths.filter_map do |path| - path.to_s if path.partial? && ::File.fnmatch?(name.delete_prefix("_"), path.name) - end.sort + matches = paths + .filter_map do |path| + path.to_s if path.partial? && ::File.fnmatch?(name.delete_prefix("_"), path.name) + end + .sort matches = [name] if matches.empty? matches.map { |path| "<%# Template Dependency: #{path} %>" }.join("\n") end @@ -132,6 +137,7 @@ def component_ancestors(component) ancestors << component component = component.superclass end + ancestors end @@ -142,27 +148,38 @@ def component_ancestors(component) # # @return [Array] the files the modules are defined in def module_files(component) - component.ancestors.take_while { |ancestor| ancestor != ViewComponent::Base }.filter_map { |ancestor| - next if ancestor.is_a?(Class) || ancestor.name.nil? - - begin - path, _line = Object.const_source_location(ancestor.name) - rescue NameError - next - end - path unless path.nil? || path.start_with?(VIEW_COMPONENT_LIB) - }.uniq + component + .ancestors + .take_while { |ancestor| ancestor != ViewComponent::Base } + .filter_map { |ancestor| + next if ancestor.is_a?(Class) || ancestor.name.nil? + + begin + path, _line = Object.const_source_location(ancestor.name) + rescue NameError + next + end + + path unless path.nil? || path.start_with?(VIEW_COMPONENT_LIB) + } + .uniq end def source_files(component) - sidecars = component_ancestors(component).flat_map { |ancestor| ancestor.__vc_sidecar_files(SIDECAR_EXTENSIONS) } + sidecars = component_ancestors(component).flat_map { |ancestor| + ancestor.__vc_sidecar_files(SIDECAR_EXTENSIONS) + } (ruby_files(component) + sidecars).uniq.select { |path| ::File.exist?(path) } end def ruby_files(component) CacheDigest.memoize([:ruby_files, component]) do - component_ancestors(component).map(&:identifier).concat(module_files(component)) - .compact.uniq.select { |path| ::File.exist?(path) } + component_ancestors(component) + .map(&:identifier) + .concat(module_files(component)) + .compact + .uniq + .select { |path| ::File.exist?(path) } end end @@ -171,33 +188,38 @@ def ruby_files(component) # # @return [Array] source, extension, and defining component def template_sources(component) - component_ancestors(component).flat_map do |ancestor| - sources = ancestor.__vc_sidecar_files(ActionView::Template::Handlers.extensions).filter_map do |path| - [CompileCache.read_file(path), ::File.extname(path).delete_prefix("."), ancestor] if ::File.exist?(path) - end - inline_template = ancestor.__vc_inline_template - sources << [inline_template.source, inline_template.language.to_s, ancestor] if inline_template - - sources - end.uniq - end - - def explicit_dependencies(sources) - sources.flat_map { |source| - # A cheap check first: most sources declare nothing, and the - # pattern is slow to scan for in sources with many comments. - next [] unless source.include?("Template Dependency:") + component_ancestors(component) + .flat_map do |ancestor| + sources = ancestor.__vc_sidecar_files(ActionView::Template::Handlers.extensions).filter_map do |path| + [CompileCache.read_file(path), ::File.extname(path).delete_prefix("."), ancestor] if ::File.exist?(path) + end - declared = source.scan(CacheDigest::EXPLICIT_DEPENDENCY).flatten + inline_template = ancestor.__vc_inline_template + sources << [inline_template.source, inline_template.language.to_s, ancestor] if inline_template - # Component class names are translated to the path they're digested - # under; anything else is a template path already. - CacheDigest.explicit_component_dependencies(source).each do |name, virtual_path| - declared = declared - [name] + [virtual_path] + sources end + .uniq + end - declared - }.uniq + def explicit_dependencies(sources) + sources + .flat_map { |source| + # A cheap check first: most sources declare nothing, and the + # pattern is slow to scan for in sources with many comments. + next [] unless source.include?("Template Dependency:") + + declared = source.scan(CacheDigest::EXPLICIT_DEPENDENCY).flatten + + # Component class names are translated to the path they're digested + # under; anything else is a template path already. + CacheDigest.explicit_component_dependencies(source).each do |name, virtual_path| + declared = declared - [name] + [virtual_path] + end + + declared + } + .uniq end # Everything but the component and its superclasses, which a component @@ -210,7 +232,9 @@ def dependencies(component, templates) dependencies = explicit_dependencies(ruby + templates.map(&:first)) | ruby.flat_map { |source| ruby_dependencies(source, virtual_path) } | CacheDigest.slot_renders_of(component) | - templates.flat_map { |source, extension, owner| template_dependencies(owner, source, extension, virtual_path) } + templates.flat_map { |source, extension, owner| + template_dependencies(owner, source, extension, virtual_path) + } dependencies - own_paths end @@ -232,10 +256,14 @@ def template_dependencies(component, source, extension, virtual_path) format: nil, virtual_path: virtual_path ) - CacheDigest.renders_in( - CacheDigest.compiled_source(template), virtual_path, - view_paths: ActionController::Base.view_paths, nesting: [component] - ).flatten + CacheDigest + .renders_in( + CacheDigest.compiled_source(template), + virtual_path, + view_paths: ActionController::Base.view_paths, + nesting: [component] + ) + .flatten end # Components loaded from encrypted files, as some commercial gems ship @@ -257,6 +285,7 @@ def file_digest(path) else ::File.binread(path) end + ActiveSupport::Digest.hexdigest(source) end end diff --git a/lib/view_component/cacheable.rb b/lib/view_component/cacheable.rb index 30cdddb3b..69d97417b 100644 --- a/lib/view_component/cacheable.rb +++ b/lib/view_component/cacheable.rb @@ -56,24 +56,30 @@ module Cacheable # @return [void] def cache_on(*methods, **options, &block) if block - raise ArgumentError, + raise( + ArgumentError, "`cache_on` doesn't accept a block. Name the methods whose values form the cache key, " \ - "such as `cache_on :message`." + "such as `cache_on :message`." + ) end methods.each do |method| next if method.is_a?(Symbol) || method.is_a?(String) - raise ArgumentError, + raise( + ArgumentError, "`cache_on` expects method names as symbols, got #{method.class}. " \ - "Define a method for the value and name it, such as `cache_on :message`." + "Define a method for the value and name it, such as `cache_on :message`." + ) end unknown = options.keys - %i[if unless] if unknown.any? - raise ArgumentError, + raise( + ArgumentError, "`cache_on` received unknown #{"option".pluralize(unknown.count)} " \ - "#{unknown.map(&:inspect).to_sentence}. Supported options are `:if` and `:unless`." + "#{unknown.map(&:inspect).to_sentence}. Supported options are `:if` and `:unless`." + ) end @__vc_cache_on = __vc_cache_on | methods.map(&:to_sym) diff --git a/lib/view_component/collection.rb b/lib/view_component/collection.rb index febe8bbb2..5894a2b4a 100644 --- a/lib/view_component/collection.rb +++ b/lib/view_component/collection.rb @@ -19,6 +19,7 @@ def render_in(view_context, **_, &block) rendered = components.map! do |component| component.render_in(view_context, &block) end + safe_join(rendered, rendered_spacer(view_context)) end diff --git a/lib/view_component/compile_cache.rb b/lib/view_component/compile_cache.rb index 6b17b8663..bb7e6d484 100644 --- a/lib/view_component/compile_cache.rb +++ b/lib/view_component/compile_cache.rb @@ -15,7 +15,7 @@ def register(klass) end def compiled?(klass) - @@cache.include? klass + @@cache.include?(klass) end def invalidate_class!(klass) @@ -77,7 +77,8 @@ def sidecar_files_matching(pattern) directory = File.dirname(pattern) # Index the shared directory by component name instead of scanning all # its entries again for every component and extension. - entries = directories[directory] ||= Dir.glob("#{directory}/*", File::FNM_DOTMATCH) + entries = directories[directory] ||= Dir + .glob("#{directory}/*", File::FNM_DOTMATCH) .group_by { |path| File.basename(path).split(".", 2).first } candidates = entries.fetch(prefix.split(".", 2).first, []) candidates.select { |path| File.fnmatch?(filename, File.basename(path)) } diff --git a/lib/view_component/compiler.rb b/lib/view_component/compiler.rb index a7e42a2bb..705416aae 100644 --- a/lib/view_component/compiler.rb +++ b/lib/view_component/compiler.rb @@ -30,7 +30,8 @@ def compile(raise_errors: false, force: false) gather_templates - if (self.class.__vc_development_mode || !@component.superclass.__vc_compiled?) && @templates.any?(&:requires_compiled_superclass?) + if (self.class.__vc_development_mode || !@component.superclass.__vc_compiled?) && + @templates.any?(&:requires_compiled_superclass?) @component.superclass.__vc_compile(raise_errors: raise_errors) @templates = nil gather_templates @@ -133,9 +134,12 @@ def define_render_template_for RUBY else methods.const_set(:COMPILER, self) - calls = @templates.each_with_index.map do |template, index| - "when TEMPLATE_#{index}\n#{template.safe_method_call}" - end.join("\n") + calls = @templates + .each_with_index + .map do |template, index| + "when TEMPLATE_#{index}\n#{template.safe_method_call}" + end + .join("\n") body = <<~RUBY @current_template = COMPILER.find_templates_for(details).first case @current_template @@ -146,11 +150,15 @@ def define_render_template_for RUBY end - methods.module_eval <<~RUBY, __FILE__, __LINE__ + 1 - def render_template_for(details) - #{body} - end - RUBY + methods.module_eval( + <<~RUBY, + def render_template_for(details) + #{body} + end + RUBY + __FILE__, + __LINE__ - 5 + ) @component.define_method(:render_template_for, methods.instance_method(:render_template_for)) # Descendants retain these unbound methods for render_parent. @@ -174,12 +182,12 @@ def template_errors .tally .select { |_, count| count > 1 } .each do |tally| - variant, this_format = tally.first + variant, this_format = tally.first - variant_string = " for variant `#{variant}`" if variant.present? + variant_string = " for variant `#{variant}`" if variant.present? - errors << "More than one #{this_format.upcase} template found#{variant_string} for #{@component}. " - end + errors << "More than one #{this_format.upcase} template found#{variant_string} for #{@component}. " + end default_template_types = @templates.each_with_object(Set.new) do |template, memo| next if template.variant @@ -193,14 +201,13 @@ def template_errors if default_template_types.length > 1 errors << "Template file and inline render method found for #{@component}. " \ - "There can only be a template file or inline render method per component." + "There can only be a template file or inline render method per component." end # If a template has inline calls, they can conflict with template files the component may use # to render. This attempts to catch and raise that issue before run time. For example, # `def render_mobile` would conflict with a sidecar template of `component.html+mobile.erb` - duplicate_template_file_and_inline_call_variants = - @templates.reject(&:inline_call?).map(&:variant) & + duplicate_template_file_and_inline_call_variants = @templates.reject(&:inline_call?).map(&:variant) & @templates.select { _1.inline_call? && _1.defined_on_self? }.map(&:variant) unless duplicate_template_file_and_inline_call_variants.empty? @@ -208,73 +215,84 @@ def template_errors errors << "Template #{"file".pluralize(count)} and inline render #{"method".pluralize(count)} " \ - "found for #{"variant".pluralize(count)} " \ - "#{duplicate_template_file_and_inline_call_variants.map { |v| "'#{v}'" }.to_sentence} " \ - "in #{@component}. There can only be a template file or inline render method per variant." + "found for #{"variant".pluralize(count)} " \ + "#{duplicate_template_file_and_inline_call_variants.map { |v| "'#{v}'" }.to_sentence} " \ + "in #{@component}. There can only be a template file or inline render method per variant." end - @templates.select(&:variant).each_with_object(Hash.new { |h, k| h[k] = Set.new }) do |template, memo| - memo[template.normalized_variant_name] << template.variant - memo - end.each do |_, variant_names| - next unless variant_names.length > 1 + @templates + .select(&:variant) + .each_with_object(Hash.new { |h, k| h[k] = Set.new }) do |template, memo| + memo[template.normalized_variant_name] << template.variant + memo + end + .each do |_, variant_names| + next unless variant_names.length > 1 - errors << "Colliding templates #{variant_names.sort.map { |v| "'#{v}'" }.to_sentence} found in #{@component}." - end + errors << + "Colliding templates #{variant_names.sort.map { |v| "'#{v}'" }.to_sentence} found in #{@component}." + end errors end end def gather_templates - @templates ||= - if @component.__vc_inline_template.present? - [Template::Inline.new( + @templates ||= if @component.__vc_inline_template.present? + [ + Template::Inline.new( component: @component, inline_template: @component.__vc_inline_template - )] - else - path_parser = CompileCache.path_parser - templates = @component.__vc_sidecar_files( + ) + ] + else + path_parser = CompileCache.path_parser + templates = @component + .__vc_sidecar_files( ActionView::Template::Handlers.extensions - ).map do |path| + ) + .map do |path| details = path_parser.parse(path).details Template::File.new(component: @component, path: path, details: details) end - component_instance_methods_on_self = @component.instance_methods(false) + component_instance_methods_on_self = @component.instance_methods(false) - ( - @component.ancestors.take_while { |ancestor| ancestor != ViewComponent::Base } - @component.included_modules - ).flat_map { |ancestor| ancestor.instance_methods(false).grep(/^call(_|$)/) } - .uniq - .each do |method_name| + (@component.ancestors.take_while { |ancestor| ancestor != ViewComponent::Base } - @component.included_modules) + .flat_map { |ancestor| ancestor.instance_methods(false).grep(/^call(_|$)/) } + .uniq + .each do |method_name| unless component_instance_methods_on_self.include?(method_name) owner = @component.instance_method(method_name).owner inherited = owner.respond_to?(:__vc_compiler) ? owner.__vc_compiler.templates_for_call(method_name) : [] if inherited.any? # A format and a variant can share a public call_* alias. inherited.each do |template| - next if templates.any? do |own| - own.variant == template.variant && - (own.format || Template::DEFAULT_FORMAT) == (template.format || Template::DEFAULT_FORMAT) + if templates.any? do |own| + own.variant == template.variant && + (own.format || Template::DEFAULT_FORMAT) == (template.format || Template::DEFAULT_FORMAT) + end + + next end templates << Template::Inherited.new(component: @component, template: template) end + next end end - templates << Template::InlineCall.new( - component: @component, - method_name: method_name, - defined_on_self: component_instance_methods_on_self.include?(method_name) - ) + templates << + Template::InlineCall.new( + component: @component, + method_name: method_name, + defined_on_self: component_instance_methods_on_self.include?(method_name) + ) end - templates - end + templates + end end end end diff --git a/lib/view_component/config.rb b/lib/view_component/config.rb index 09d82c6b7..2242704c2 100644 --- a/lib/view_component/config.rb +++ b/lib/view_component/config.rb @@ -6,7 +6,8 @@ module ViewComponent class Config # An `ActiveSupport::OrderedOptions` that raises when an option it doesn't # know about is set, rather than silently storing it. - class Options < ActiveSupport::OrderedOptions # :nodoc: + # :nodoc: + class Options < ActiveSupport::OrderedOptions ROOT_NAMESPACE = "config.view_component" def initialize(namespace, allowed_keys, default: nil, renamed: {}, removed: {}) @@ -33,12 +34,14 @@ def []=(key, value) super else - raise UnknownConfigOptionError.new( - "#{@namespace}.#{key}", - renamed_to: @renamed[key] && "#{ROOT_NAMESPACE}.#{@renamed[key]}", - removed: @removed.key?(key), - hint: @removed[key], - valid_options: @allowed_keys + raise( + UnknownConfigOptionError.new( + "#{@namespace}.#{key}", + renamed_to: @renamed[key] && "#{ROOT_NAMESPACE}.#{@renamed[key]}", + removed: @removed.key?(key), + hint: @removed[key], + valid_options: @allowed_keys + ) ) end end @@ -53,6 +56,7 @@ def merge!(*others) self[key] = value end end + self end @@ -256,7 +260,18 @@ def registered_rails_engines_with_previews def default_generate_options options = Options.new( "#{Options::ROOT_NAMESPACE}.generate", - %i[path preview_path parent_class sidecar stimulus_controller typescript locale distinct_locale_files preview use_component_path_for_rspec_tests], + %i[ + path + preview_path + parent_class + sidecar + stimulus_controller + typescript + locale + distinct_locale_files + preview + use_component_path_for_rspec_tests + ], default: false, renamed: {component_parent_class: RENAMED_OPTIONS.fetch(:component_parent_class)} ) diff --git a/lib/view_component/configurable.rb b/lib/view_component/configurable.rb index 1e92c7473..5e3660b38 100644 --- a/lib/view_component/configurable.rb +++ b/lib/view_component/configurable.rb @@ -19,7 +19,11 @@ def configure end included do - next if respond_to?(:config) && config.respond_to?(:view_component) && config.respond_to_missing?(:instrumentation_enabled) + if respond_to?(:config) && + config.respond_to?(:view_component) && + config.respond_to_missing?(:instrumentation_enabled) + next + end configure do |config| config.view_component ||= ActiveSupport::InheritableOptions.new diff --git a/lib/view_component/engine.rb b/lib/view_component/engine.rb index 6a8b52fd5..fdbf20676 100644 --- a/lib/view_component/engine.rb +++ b/lib/view_component/engine.rb @@ -6,7 +6,8 @@ require "view_component/cache_digest" module ViewComponent - class Engine < Rails::Engine # :nodoc: + # :nodoc: + class Engine < Rails::Engine config.view_component = ViewComponent::Config.current initializer "view_component.cache_digest" do @@ -19,14 +20,18 @@ class Engine < Rails::Engine # :nodoc: %i[generate previews].each do |config_option| options[config_option] ||= ViewComponent::Base.public_send(config_option) end + options.instrumentation_enabled = false if options.instrumentation_enabled.nil? options.previews.enabled = (Rails.env.development? || Rails.env.test?) if options.previews.enabled.nil? if options.previews.enabled # This is still necessary because when `config.view_component` is declared, `Rails.root` is unspecified. - options.previews.paths << "#{Rails.root}/test/components/previews" if defined?(Rails.root) && Dir.exist?( - "#{Rails.root}/test/components/previews" - ) + if defined?(Rails.root) && + Dir.exist?( + "#{Rails.root}/test/components/previews" + ) + options.previews.paths << "#{Rails.root}/test/components/previews" + end end end @@ -78,7 +83,7 @@ class Engine < Rails::Engine # :nodoc: self.check_precompiled_asset = app.config.assets.check_precompiled_asset self.unknown_asset_fallback = app.config.assets.unknown_asset_fallback # Expose the app precompiled asset check to the view - self.precompiled_asset_checker = ->(logical_path) { app.asset_precompiled? logical_path } + self.precompiled_asset_checker = -> (logical_path) { app.asset_precompiled? logical_path } end end end @@ -86,6 +91,7 @@ class Engine < Rails::Engine # :nodoc: initializer "view_component.serializable" do ActiveSupport.on_load(:active_job) do require "view_component/active_job_serializer" + ActiveJob::Serializers.add_serializers(ViewComponent::ActiveJobSerializer) end end diff --git a/lib/view_component/errors.rb b/lib/view_component/errors.rb index e0552e573..54a27884a 100644 --- a/lib/view_component/errors.rb +++ b/lib/view_component/errors.rb @@ -6,10 +6,10 @@ def initialize end class DuplicateSlotContentError < StandardError - MESSAGE = - "It looks like a block was provided after calling `with_content` on COMPONENT, " \ + MESSAGE = "It looks like a block was provided after calling `with_content` on COMPONENT, " \ "which means that ViewComponent doesn't know which content to use.\n\n" \ - "To fix this issue, use either `with_content` or a block.".freeze + "To fix this issue, use either `with_content` or a block." + .freeze def initialize(klass_name) super(MESSAGE.gsub("COMPONENT", klass_name.to_s)) @@ -29,9 +29,9 @@ class MultipleInlineTemplatesError < BaseError end class MissingPreviewTemplateError < StandardError - MESSAGE = - "A preview template for example EXAMPLE doesn't exist.\n\n" \ - "To fix this issue, create a template for the example.".freeze + MESSAGE = "A preview template for example EXAMPLE doesn't exist.\n\n" \ + "To fix this issue, create a template for the example." + .freeze def initialize(example) super(MESSAGE.gsub("EXAMPLE", example)) @@ -39,9 +39,9 @@ def initialize(example) end class MissingTemplateError < StandardError - MESSAGE = - "No templates for COMPONENT match the request DETAIL.\n\n" \ - "To fix this issue, provide a suitable template.".freeze + MESSAGE = "No templates for COMPONENT match the request DETAIL.\n\n" \ + "To fix this issue, provide a suitable template." + .freeze def initialize(component, request_detail) detail = { @@ -55,10 +55,10 @@ def initialize(component, request_detail) end class DuplicateContentError < StandardError - MESSAGE = - "It looks like a block was provided after calling `with_content` on COMPONENT, " \ + MESSAGE = "It looks like a block was provided after calling `with_content` on COMPONENT, " \ "which means that ViewComponent doesn't know which content to use.\n\n" \ - "To fix this issue, use either `with_content` or a block.".freeze + "To fix this issue, use either `with_content` or a block." + .freeze def initialize(klass_name) super(MESSAGE.gsub("COMPONENT", klass_name.to_s)) @@ -66,11 +66,11 @@ def initialize(klass_name) end class MissingCollectionArgumentError < StandardError - MESSAGE = - "The initializer for COMPONENT doesn't accept the parameter `PARAMETER`, " \ + MESSAGE = "The initializer for COMPONENT doesn't accept the parameter `PARAMETER`, " \ "which is required to render it as a collection.\n\n" \ "To fix this issue, update the initializer to accept `PARAMETER`.\n\n" \ - "See [the collections docs](https://viewcomponent.org/guide/collections.html) for more information on rendering collections.".freeze + "See [the collections docs](https://viewcomponent.org/guide/collections.html) for more information on rendering collections." + .freeze def initialize(klass_name, parameter) super(MESSAGE.gsub("COMPONENT", klass_name.to_s).gsub("PARAMETER", parameter.to_s)) @@ -78,9 +78,9 @@ def initialize(klass_name, parameter) end class ReservedParameterError < StandardError - MESSAGE = - "COMPONENT initializer can't accept the parameter `PARAMETER`, as it will override a " \ - "public ViewComponent method. To fix this issue, rename the parameter.".freeze + MESSAGE = "COMPONENT initializer can't accept the parameter `PARAMETER`, as it will override a " \ + "public ViewComponent method. To fix this issue, rename the parameter." + .freeze def initialize(klass_name, parameter) super(MESSAGE.gsub("COMPONENT", klass_name.to_s).gsub("PARAMETER", parameter.to_s)) @@ -88,16 +88,16 @@ def initialize(klass_name, parameter) end class InvalidCollectionArgumentError < BaseError - MESSAGE = - "The value of the first argument passed to `with_collection` isn't a valid collection. " \ - "Make sure it responds to `to_ary`.".freeze + MESSAGE = "The value of the first argument passed to `with_collection` isn't a valid collection. " \ + "Make sure it responds to `to_ary`." + .freeze end class ContentSlotNameError < StandardError - MESSAGE = - "COMPONENT declares a slot named content, which is a reserved word in ViewComponent.\n\n" \ + MESSAGE = "COMPONENT declares a slot named content, which is a reserved word in ViewComponent.\n\n" \ "Content passed to a ViewComponent as a block is captured and assigned to the `content` accessor without having to create an explicit slot.\n\n" \ - "To fix this issue, either use the `content` accessor directly or choose a different slot name.".freeze + "To fix this issue, either use the `content` accessor directly or choose a different slot name." + .freeze def initialize(klass_name) super(MESSAGE.gsub("COMPONENT", klass_name.to_s)) @@ -105,20 +105,20 @@ def initialize(klass_name) end class InvalidSlotDefinitionError < BaseError - MESSAGE = - "Invalid slot definition. Please pass a class, " \ - "string, or callable (that is proc, lambda, etc)".freeze + MESSAGE = "Invalid slot definition. Please pass a class, " \ + "string, or callable (that is proc, lambda, etc)" + .freeze end class InvalidSlotNameError < StandardError end class SlotPredicateNameError < InvalidSlotNameError - MESSAGE = - "COMPONENT declares a slot named SLOT_NAME, which ends with a question mark.\n\n" \ + MESSAGE = "COMPONENT declares a slot named SLOT_NAME, which ends with a question mark.\n\n" \ "This isn't allowed because the ViewComponent framework already provides predicate " \ "methods ending in `?`.\n\n" \ - "To fix this issue, choose a different name.".freeze + "To fix this issue, choose a different name." + .freeze def initialize(klass_name, slot_name) super(MESSAGE.gsub("COMPONENT", klass_name.to_s).gsub("SLOT_NAME", slot_name.to_s)) @@ -126,9 +126,9 @@ def initialize(klass_name, slot_name) end class RedefinedSlotError < StandardError - MESSAGE = - "COMPONENT declares the SLOT_NAME slot multiple times.\n\n" \ - "To fix this issue, choose a different slot name.".freeze + MESSAGE = "COMPONENT declares the SLOT_NAME slot multiple times.\n\n" \ + "To fix this issue, choose a different slot name." + .freeze def initialize(klass_name, slot_name) super(MESSAGE.gsub("COMPONENT", klass_name.to_s).gsub("SLOT_NAME", slot_name.to_s)) @@ -136,9 +136,9 @@ def initialize(klass_name, slot_name) end class ReservedSingularSlotNameError < InvalidSlotNameError - MESSAGE = - "COMPONENT declares a slot named SLOT_NAME, which is a reserved word in the ViewComponent framework.\n\n" \ - "To fix this issue, choose a different name.".freeze + MESSAGE = "COMPONENT declares a slot named SLOT_NAME, which is a reserved word in the ViewComponent framework.\n\n" \ + "To fix this issue, choose a different name." + .freeze def initialize(klass_name, slot_name) super(MESSAGE.gsub("COMPONENT", klass_name.to_s).gsub("SLOT_NAME", slot_name.to_s)) @@ -146,9 +146,9 @@ def initialize(klass_name, slot_name) end class ReservedPluralSlotNameError < InvalidSlotNameError - MESSAGE = - "COMPONENT declares a slot named SLOT_NAME, which is a reserved word in the ViewComponent framework.\n\n" \ - "To fix this issue, choose a different name.".freeze + MESSAGE = "COMPONENT declares a slot named SLOT_NAME, which is a reserved word in the ViewComponent framework.\n\n" \ + "To fix this issue, choose a different name." + .freeze def initialize(klass_name, slot_name) super(MESSAGE.gsub("COMPONENT", klass_name.to_s).gsub("SLOT_NAME", slot_name.to_s)) @@ -156,9 +156,9 @@ def initialize(klass_name, slot_name) end class UncountableSlotNameError < InvalidSlotNameError - MESSAGE = - "COMPONENT declares a slot named SLOT_NAME, which is an uncountable word\n\n" \ - "To fix this issue, choose a different name.".freeze + MESSAGE = "COMPONENT declares a slot named SLOT_NAME, which is an uncountable word\n\n" \ + "To fix this issue, choose a different name." + .freeze def initialize(klass_name, slot_name) super(MESSAGE.gsub("COMPONENT", klass_name.to_s).gsub("SLOT_NAME", slot_name.to_s)) @@ -174,18 +174,18 @@ def initialize(slot_name) end class NilWithContentError < BaseError - MESSAGE = - "No content provided to `#with_content` for #{self}.\n\n" \ - "To fix this issue, pass a value.".freeze + MESSAGE = "No content provided to `#with_content` for #{self}.\n\n" \ + "To fix this issue, pass a value." + .freeze end class ReusedInstanceError < StandardError - MESSAGE = - "ViewComponent instances are single-use; a COMPONENT instance was rendered more than once.\n\n" \ + MESSAGE = "ViewComponent instances are single-use; a COMPONENT instance was rendered more than once.\n\n" \ "Reusing a component instance across renders can leak request-scoped state " \ "(controller, helpers, request, view_flow, slot content, `with_content`) from an earlier render " \ "into a later one, which has security and correctness implications (GHSA-8qw7-6phv-7q6p).\n\n" \ - "To fix this issue, create a new component instance per render.".freeze + "To fix this issue, create a new component instance per render." + .freeze def initialize(klass_name) super(MESSAGE.gsub("COMPONENT", klass_name.to_s)) @@ -193,30 +193,30 @@ def initialize(klass_name) end class TranslateCalledBeforeRenderError < BaseError - MESSAGE = - "`#translate` can't be used before rendering as it depends " \ + MESSAGE = "`#translate` can't be used before rendering as it depends " \ "on the view context that only exists once a ViewComponent is passed to " \ "the Rails render pipeline.\n\n" \ "It's sometimes possible to fix this issue by moving code dependent on " \ - "`#translate` to a [`#before_render` method](https://viewcomponent.org/api.html#before_render--void).".freeze + "`#translate` to a [`#before_render` method](https://viewcomponent.org/api.html#before_render--void)." + .freeze end class HelpersCalledBeforeRenderError < BaseError - MESSAGE = - "`#helpers` can't be used before rendering as it depends " \ + MESSAGE = "`#helpers` can't be used before rendering as it depends " \ "on the view context that only exists once a ViewComponent is passed to " \ "the Rails render pipeline.\n\n" \ "It's sometimes possible to fix this issue by moving code dependent on " \ - "`#helpers` to a [`#before_render` method](https://viewcomponent.org/api.html#before_render--void).".freeze + "`#helpers` to a [`#before_render` method](https://viewcomponent.org/api.html#before_render--void)." + .freeze end class ControllerCalledBeforeRenderError < BaseError - MESSAGE = - "`#controller` can't be used before rendering, as it depends " \ + MESSAGE = "`#controller` can't be used before rendering, as it depends " \ "on the view context that only exists once a ViewComponent is passed to " \ "the Rails render pipeline.\n\n" \ "It's sometimes possible to fix this issue by moving code dependent on " \ - "`#controller` to a [`#before_render` method](https://viewcomponent.org/api.html#before_render--void).".freeze + "`#controller` to a [`#before_render` method](https://viewcomponent.org/api.html#before_render--void)." + .freeze end class SystemTestControllerNefariousPathError < BaseError @@ -224,9 +224,9 @@ class SystemTestControllerNefariousPathError < BaseError end class AlreadyDefinedPolymorphicSlotSetterError < StandardError - MESSAGE = - "A method called 'SETTER_METHOD_NAME' already exists and would be overwritten by the 'SETTER_NAME' polymorphic " \ - "slot setter.\n\nPlease choose a different setter name.".freeze + MESSAGE = "A method called 'SETTER_METHOD_NAME' already exists and would be overwritten by the 'SETTER_NAME' polymorphic " \ + "slot setter.\n\nPlease choose a different setter name." + .freeze def initialize(setter_method_name, setter_name) super(MESSAGE.gsub("SETTER_METHOD_NAME", setter_method_name.to_s).gsub("SETTER_NAME", setter_name.to_s)) @@ -234,11 +234,11 @@ def initialize(setter_method_name, setter_name) end class CacheDigestTemplateError < StandardError - MESSAGE = - "The synthetic cache digest template for COMPONENT was rendered.\n\n" \ + MESSAGE = "The synthetic cache digest template for COMPONENT was rendered.\n\n" \ "This template exists only so Rails can compute a cache digest for the " \ "component and is never meant to be rendered. Render the component " \ - "itself instead.".freeze + "itself instead." + .freeze def initialize(component_name) super(MESSAGE.gsub("COMPONENT", component_name.to_s)) @@ -246,9 +246,9 @@ def initialize(component_name) end class UndefinedCacheKeyMethodError < StandardError - MESSAGE = - "`cache_on` declared `METHOD` on COMPONENT, but no such method is defined.\n\n" \ - "To fix this issue, define `METHOD` or remove it from `cache_on`.".freeze + MESSAGE = "`cache_on` declared `METHOD` on COMPONENT, but no such method is defined.\n\n" \ + "To fix this issue, define `METHOD` or remove it from `cache_on`." + .freeze def initialize(component_name, method_name) super(MESSAGE.gsub("COMPONENT", component_name.to_s).gsub("METHOD", method_name.to_s)) @@ -256,12 +256,12 @@ def initialize(component_name, method_name) end class ContentPassedToCachedComponentError < StandardError - MESSAGE = - "COMPONENT declares `cache_on`, so it caches its own output, but its caller passed it content.\n\n" \ + MESSAGE = "COMPONENT declares `cache_on`, so it caches its own output, but its caller passed it content.\n\n" \ "Content and slots set by the caller aren't part of the cache key, so caching them would risk " \ "serving one caller's content to another.\n\n" \ "To fix this issue, either remove `cache_on` from COMPONENT, or move the content into the " \ - "component and derive it from the values declared in `cache_on`.".freeze + "component and derive it from the values declared in `cache_on`." + .freeze def initialize(component_name) super(MESSAGE.gsub("COMPONENT", component_name.to_s)) @@ -270,15 +270,14 @@ def initialize(component_name) class UnknownConfigOptionError < StandardError def initialize(option, renamed_to: nil, removed: false, hint: nil, valid_options: []) - message = - if renamed_to - "`#{option}` was renamed to `#{renamed_to}` in ViewComponent 4.0." - elsif removed - "`#{option}` was removed in ViewComponent 4.0." - else - "`#{option}` isn't a ViewComponent configuration option. " \ - "Valid options are: #{valid_options.join(", ")}." - end + message = if renamed_to + "`#{option}` was renamed to `#{renamed_to}` in ViewComponent 4.0." + elsif removed + "`#{option}` was removed in ViewComponent 4.0." + else + "`#{option}` isn't a ViewComponent configuration option. " \ + "Valid options are: #{valid_options.join(", ")}." + end super([message, hint].compact.join(" ")) end diff --git a/lib/view_component/inline_template.rb b/lib/view_component/inline_template.rb index 95bb2acac..5548c5784 100644 --- a/lib/view_component/inline_template.rb +++ b/lib/view_component/inline_template.rb @@ -1,6 +1,7 @@ # frozen_string_literal: true -module ViewComponent # :nodoc: +# :nodoc: +module ViewComponent module InlineTemplate extend ActiveSupport::Concern diff --git a/lib/view_component/instrumentation.rb b/lib/view_component/instrumentation.rb index 9dbe3241f..a112c14fd 100644 --- a/lib/view_component/instrumentation.rb +++ b/lib/view_component/instrumentation.rb @@ -2,7 +2,8 @@ require "active_support/notifications" -module ViewComponent # :nodoc: +# :nodoc: +module ViewComponent module Instrumentation def self.included(mod) mod.prepend(self) unless self <= ViewComponent::Instrumentation @@ -29,6 +30,7 @@ def render_in(...) payload[:view_identifier] = @__vc_instrumentation_view_identifier result end + ensure @__vc_instrumentation_view_identifier = nil end diff --git a/lib/view_component/preview.rb b/lib/view_component/preview.rb index d3a168542..0f4bf7599 100644 --- a/lib/view_component/preview.rb +++ b/lib/view_component/preview.rb @@ -2,7 +2,8 @@ require "active_support/descendants_tracker" -module ViewComponent # :nodoc: +# :nodoc: +module ViewComponent class Preview if defined?(Rails.application.routes.url_helpers) # Workaround from https://stackoverflow.com/questions/20853526/make-yard-ignore-certain-class-extensions to appease YARD @@ -40,7 +41,9 @@ def all # Returns the arguments for rendering of the component in its layout def render_args(example, params: {}) - raise AbstractController::ActionNotFound, "#{example} is not a valid preview example" unless examples.include?(example.to_s) + unless examples.include?(example.to_s) + raise AbstractController::ActionNotFound, "#{example} is not a valid preview example" + end example_params_names = instance_method(example).parameters.map(&:last) provided_params = params.slice(*example_params_names).to_h.symbolize_keys @@ -80,15 +83,15 @@ def layout(layout_name) # Returns the relative path (from preview_path) to the preview example template if the template exists def preview_example_template_path(example) - preview_path = - Array(preview_paths).detect do |path| - Dir["#{path}/#{preview_name}_preview/#{example}.html.*"].first - end + preview_path = Array(preview_paths).detect do |path| + Dir["#{path}/#{preview_name}_preview/#{example}.html.*"].first + end raise MissingPreviewTemplateError.new(example) if preview_path.nil? path = Dir["#{preview_path}/#{preview_name}_preview/#{example}.html.*"].first - Pathname.new(path) + Pathname + .new(path) .relative_path_from(Pathname.new(preview_path)) .to_s .sub(/\..*$/, "") diff --git a/lib/view_component/serializable.rb b/lib/view_component/serializable.rb index 5dc6560eb..cacc809af 100644 --- a/lib/view_component/serializable.rb +++ b/lib/view_component/serializable.rb @@ -7,7 +7,8 @@ module ViewComponent module Serializable extend ActiveSupport::Concern - class UnserializableError < ArgumentError; end + class UnserializableError < ArgumentError + end class_methods do # Returns a Proxy that captures this class and its initialization arguments, @@ -21,6 +22,7 @@ def render_later(*args, &block) ViewComponent::Serializable::Proxy.new(self, *args) end + ruby2_keywords :render_later end end diff --git a/lib/view_component/serializable/proxy.rb b/lib/view_component/serializable/proxy.rb index be18649eb..b43e0ac43 100644 --- a/lib/view_component/serializable/proxy.rb +++ b/lib/view_component/serializable/proxy.rb @@ -36,6 +36,7 @@ def initialize(component_class, *args) @initialize_args = args @slot_calls = [] end + ruby2_keywords :initialize # Implements the Rails renderable interface @@ -43,6 +44,7 @@ def render_in(view_context, &block) if block raise UnserializableError, "Cannot serialize render_in with a block" end + build_component.render_in(view_context) end @@ -53,6 +55,7 @@ def method_missing(method_name, *args, &block) super end end + ruby2_keywords :method_missing def respond_to_missing?(method_name, include_private = false) diff --git a/lib/view_component/slot.rb b/lib/view_component/slot.rb index df7edd584..e39966b48 100644 --- a/lib/view_component/slot.rb +++ b/lib/view_component/slot.rb @@ -63,29 +63,28 @@ def to_s raise DuplicateSlotContentError.new(self.class.name) end - @content = - if __vc_component_instance? - @__vc_component_instance.__vc_original_view_context = @parent.__vc_original_view_context - - if defined?(@__vc_content_block) - # render_in is faster than `parent.render` - @__vc_component_instance.render_in(view_context) do |*args| - @parent.with_captured_virtual_path(@__vc_content_block_virtual_path) do - @__vc_content_block.call(*args) - end + @content = if __vc_component_instance? + @__vc_component_instance.__vc_original_view_context = @parent.__vc_original_view_context + + if defined?(@__vc_content_block) + # render_in is faster than `parent.render` + @__vc_component_instance.render_in(view_context) do |*args| + @parent.with_captured_virtual_path(@__vc_content_block_virtual_path) do + @__vc_content_block.call(*args) end - else - @__vc_component_instance.render_in(view_context) - end - elsif defined?(@__vc_content) - @__vc_content - elsif defined?(@__vc_content_block) - @parent.with_captured_virtual_path(@__vc_content_block_virtual_path) do - view_context.capture(&@__vc_content_block) end - elsif defined?(@__vc_content_set_by_with_content) - @__vc_content_set_by_with_content + else + @__vc_component_instance.render_in(view_context) end + elsif defined?(@__vc_content) + @__vc_content + elsif defined?(@__vc_content_block) + @parent.with_captured_virtual_path(@__vc_content_block_virtual_path) do + view_context.capture(&@__vc_content_block) + end + elsif defined?(@__vc_content_set_by_with_content) + @__vc_content_set_by_with_content + end @content = @content.to_s end diff --git a/lib/view_component/slotable.rb b/lib/view_component/slotable.rb index 04d5a75c7..d48629c0a 100644 --- a/lib/view_component/slotable.rb +++ b/lib/view_component/slotable.rb @@ -82,19 +82,19 @@ def renders_one(slot_name, callable = nil) setter_method_name = :"with_#{slot_name}" - define_method setter_method_name do |*args, **kwargs, &block| + define_method(setter_method_name) do |*args, **kwargs, &block| __vc_set_slot(slot_name, nil, *args, **kwargs, &block) end - self::GeneratedSlotMethods.define_method slot_name do + self::GeneratedSlotMethods.define_method(slot_name) do __vc_get_slot(slot_name) end - self::GeneratedSlotMethods.define_method :"#{slot_name}?" do + self::GeneratedSlotMethods.define_method(:"#{slot_name}?") do __vc_get_slot(slot_name).present? end - define_method :"with_#{slot_name}_content" do |content| + define_method(:"with_#{slot_name}_content") do |content| send(setter_method_name) { content.to_s } self @@ -152,17 +152,17 @@ def renders_many(slot_name, callable = nil) setter_method_name = :"with_#{singular_name}" - define_method setter_method_name do |*args, **kwargs, &block| + define_method(setter_method_name) do |*args, **kwargs, &block| __vc_set_slot(slot_name, nil, *args, **kwargs, &block) end - define_method :"with_#{singular_name}_content" do |content| + define_method(:"with_#{singular_name}_content") do |content| send(setter_method_name) { content.to_s } self end - define_method :"with_#{slot_name}" do |collection_args = nil, &block| + define_method(:"with_#{slot_name}") do |collection_args = nil, &block| collection_args.map do |args| if args.respond_to?(:to_hash) __vc_set_slot(slot_name, nil, **args, &block) @@ -172,11 +172,11 @@ def renders_many(slot_name, callable = nil) end end - self::GeneratedSlotMethods.define_method slot_name do + self::GeneratedSlotMethods.define_method(slot_name) do __vc_get_slot(slot_name) end - self::GeneratedSlotMethods.define_method :"#{slot_name}?" do + self::GeneratedSlotMethods.define_method(:"#{slot_name}?") do __vc_get_slot(slot_name).present? end @@ -205,7 +205,7 @@ def inherited(child) unless child.const_defined?(:GeneratedSlotMethods, false) generated_slot_methods = Module.new child.const_set(:GeneratedSlotMethods, generated_slot_methods) - child.include generated_slot_methods + child.include(generated_slot_methods) end super @@ -246,15 +246,16 @@ def __vc_register_polymorphic_slot(slot_name, types, collection:) poly_slot_name = nil end - poly_slot_name ||= - if collection - "#{ActiveSupport::Inflector.singularize(slot_name)}_#{poly_type}" - else - "#{slot_name}_#{poly_type}" - end + poly_slot_name ||= if collection + "#{ActiveSupport::Inflector.singularize(slot_name)}_#{poly_type}" + else + "#{slot_name}_#{poly_type}" + end memo[poly_type] = __vc_define_slot( - poly_slot_name, collection: collection, callable: poly_callable + poly_slot_name, + collection: collection, + callable: poly_callable ) setter_method_name = :"with_#{poly_slot_name}" @@ -267,7 +268,7 @@ def __vc_register_polymorphic_slot(slot_name, types, collection:) __vc_set_polymorphic_slot(slot_name, poly_type, *args, **kwargs, &block) end - define_method :"with_#{poly_slot_name}_content" do |content| + define_method(:"with_#{poly_slot_name}_content") do |content| send(setter_method_name) { content.to_s } self @@ -294,10 +295,10 @@ def __vc_define_slot(slot_name, collection:, callable:) # If slot doesn't respond to `render_in`, we assume it's a proc, # define a method, and save a reference to it to call when setting method_name = :"_call_#{slot_name}" - define_method method_name, &callable + define_method(method_name, &callable) slot[:renderable_function] = instance_method(method_name) else - raise(InvalidSlotDefinitionError) + raise InvalidSlotDefinitionError end slot @@ -354,7 +355,8 @@ def __vc_raise_if_slot_name_uncountable(slot_name) def __vc_get_slot(slot_name) @__vc_set_slots ||= {} - content unless defined?(@__vc_content_evaluated) && @__vc_content_evaluated # ensure content is loaded so slots will be defined + # ensure content is loaded so slots will be defined + content unless defined?(@__vc_content_evaluated) && @__vc_content_evaluated # If the slot is set, return it return @__vc_set_slots[slot_name] if @__vc_set_slots[slot_name] @@ -396,6 +398,7 @@ def __vc_dup_for_render slot.__vc_dup(copy) end end + copy.instance_variable_set(variable, slots) end end @@ -426,26 +429,27 @@ def __vc_set_slot(slot_name, slot_definition = nil, *args, **kwargs, &block) # If class if slot_definition[:renderable] slot.__vc_component_instance = slot_definition[:renderable].new(*args, **kwargs) - # If class name as a string + # If class name as a string elsif slot_definition[:renderable_class_name] - slot.__vc_component_instance = - self.class.const_get(slot_definition[:renderable_class_name]).new(*args, **kwargs) - # If passed a lambda + slot.__vc_component_instance = self + .class + .const_get(slot_definition[:renderable_class_name]) + .new(*args, **kwargs) + # If passed a lambda elsif slot_definition[:renderable_function] # Use `bind_call(self)` to ensure lambda is executed in the context of the # current component. This is necessary to allow the lambda to access helper # methods like `content_tag` as well as parent component state. renderable_function = slot_definition[:renderable_function] - renderable_value = - if block - renderable_function.bind_call(self, *args, **kwargs) do |*rargs| - with_captured_virtual_path(captured_block_virtual_path) do - view_context.capture(*rargs, &block) - end + renderable_value = if block + renderable_function.bind_call(self, *args, **kwargs) do |*rargs| + with_captured_virtual_path(captured_block_virtual_path) do + view_context.capture(*rargs, &block) end - else - renderable_function.bind_call(self, *args, **kwargs) end + else + renderable_function.bind_call(self, *args, **kwargs) + end # Function calls can return components, so if it's a component handle it specially if renderable_value.respond_to?(:render_in) diff --git a/lib/view_component/template.rb b/lib/view_component/template.rb index 42439d216..dc20826f0 100644 --- a/lib/view_component/template.rb +++ b/lib/view_component/template.rb @@ -83,7 +83,7 @@ def initialize(component:, inline_template:) component: component, details: details, path: inline_template.path, - lineno: inline_template.lineno, + lineno: inline_template.lineno ) @source = inline_template.source.dup @@ -157,11 +157,15 @@ def compile_to_component @component.silence_redefinition_of_method(call_method_name) # rubocop:disable Style/EvalWithLocation - @component.class_eval <<~RUBY, @path, lineno - def #{call_method_name} - #{compiled_source} - end - RUBY + @component.class_eval( + <<~RUBY, + def #{call_method_name} + #{compiled_source} + end + RUBY + @path, + lineno + ) # rubocop:enable Style/EvalWithLocation @component.define_method(safe_method_name, @component.instance_method(@call_method_name)) @@ -191,12 +195,16 @@ def inline_call? def default_format? format.nil? || format == DEFAULT_FORMAT end + alias_method :html?, :default_format? def call_method_name - @call_method_name ||= - ["call", (normalized_variant_name if variant.present?), (format unless default_format?)] - .compact.join("_").to_sym + @call_method_name ||= ["call", (normalized_variant_name if variant.present?), (format unless default_format?)] + .compact + .join( + "_" + ) + .to_sym end def safe_method_name @@ -231,12 +239,14 @@ def compiled_source this_source = @component.strip_trailing_whitespace? ? original_source.rstrip : original_source short_identifier = defined?(Rails.root) ? @path.sub("#{Rails.root}/", "") : @path - format = self.format || DEFAULT_FORMAT + format = self.format() || DEFAULT_FORMAT type = ActionView::Template::Types[format] - handler.call(DataWithSource.new(format:, identifier: @path, short_identifier:, type:), this_source).tap do |compiled| - CacheDigest.compiled(handler, original_source, compiled) - end + handler + .call(DataWithSource.new(format:, identifier: @path, short_identifier:, type:), this_source) + .tap do |compiled| + CacheDigest.compiled(handler, original_source, compiled) + end end end end diff --git a/lib/view_component/test_helpers.rb b/lib/view_component/test_helpers.rb index 97331a9e9..15e097c6d 100644 --- a/lib/view_component/test_helpers.rb +++ b/lib/view_component/test_helpers.rb @@ -18,7 +18,8 @@ def refute_component_rendered def assert_component_rendered assert_selector("body") end - rescue LoadError # We don't have a test case for running an application without capybara installed. + # We don't have a test case for running an application without capybara installed. + rescue LoadError end # Returns the result of a render_inline call. @@ -244,8 +245,10 @@ def with_request_url(full_path, host: nil, method: nil, protocol: nil) vc_test_request.instance_variable_set(:@port, nil) vc_test_request.path_info = path vc_test_request.path_parameters = Rails.application.routes.recognize_path_with_request(vc_test_request, path, {}) - vc_test_request.set_header("action_dispatch.request.query_parameters", - Rack::Utils.parse_nested_query(query).with_indifferent_access) + vc_test_request.set_header( + "action_dispatch.request.query_parameters", + Rack::Utils.parse_nested_query(query).with_indifferent_access + ) vc_test_request.set_header(Rack::QUERY_STRING, query) old_controller.params = nil if old_controller old_controller&.instance_variable_set(:@_url_options, nil) @@ -311,12 +314,11 @@ def vc_test_controller_class def vc_test_request require "action_controller/test_case" - @vc_test_request ||= - begin - out = ActionDispatch::TestRequest.create - out.session = ActionController::TestSession.new - out - end + @vc_test_request ||= begin + out = ActionDispatch::TestRequest.create + out.session = ActionController::TestSession.new + out + end end # Note: We prefix private methods here to prevent collisions in consumer's tests. @@ -334,6 +336,7 @@ def __vc_test_helpers_preview_class else self.class.name.gsub("Test", "Preview") end + result = result.constantize rescue NameError raise NameError, "`render_preview` expected to find #{result}, but it does not exist." diff --git a/lib/view_component/translatable.rb b/lib/view_component/translatable.rb index 055fd32eb..796aec3ba 100644 --- a/lib/view_component/translatable.rb +++ b/lib/view_component/translatable.rb @@ -15,7 +15,7 @@ module Translatable private_constant :TRANSLATION_EXTENSIONS # Like Rails' translation helper, use a sentinel that survives cache serialization. - MISSING_TRANSLATION = -(2**61) + MISSING_TRANSLATION = -(2 ** 61) private_constant :MISSING_TRANSLATION def self.symbolic_defaults?(options) @@ -36,6 +36,7 @@ def self.translate_with_defaults(translator, key, options) else translator.translate(key, **options, default: [default, MISSING_TRANSLATION]) end + return translated unless translated == MISSING_TRANSLATION end @@ -72,7 +73,7 @@ def __vc_build_i18n_backend end def __vc_i18n_key(key, scope = nil) - scope = scope.join(".") if scope.is_a? Array + scope = scope.join(".") if scope.is_a?(Array) key = key&.to_s unless key.is_a?(String) key = "#{scope}.#{key}" if scope key = "#{__vc_i18n_scope}#{key}" if key.start_with?(".") @@ -118,6 +119,7 @@ def scope_data(data) @__vc_i18n_scope.reverse_each do |part| data = {part => data} end + data end @@ -148,6 +150,7 @@ def translate(key = nil, **options) @view_context.translate(key, locale: locale, **options) end end + alias_method :t, :translate def __vc_i18n_scope diff --git a/performance/boot.rb b/performance/boot.rb index ed1e0c678..da6cf1cec 100644 --- a/performance/boot.rb +++ b/performance/boot.rb @@ -53,10 +53,12 @@ class BootApp < Rails::Application total_seconds = Process.clock_gettime(Process::CLOCK_MONOTONIC) - start total_allocations = GC.stat(:total_allocated_objects) - start_allocations -puts JSON.generate( - "view_component" => view_component, - "rest" => { - "seconds" => total_seconds - view_component["seconds"], - "allocations" => total_allocations - view_component["allocations"] - } +puts( + JSON.generate( + "view_component" => view_component, + "rest" => { + "seconds" => total_seconds - view_component["seconds"], + "allocations" => total_allocations - view_component["allocations"] + } + ) ) diff --git a/performance/compare.rb b/performance/compare.rb index 972501808..ff00ecc4a 100755 --- a/performance/compare.rb +++ b/performance/compare.rb @@ -13,12 +13,14 @@ require "json" -abort "Usage: ruby performance/compare.rb BASE HEAD" unless ARGV.size == 2 +abort("Usage: ruby performance/compare.rb BASE HEAD") unless ARGV.size == 2 -median = ->(values) { values.sort[values.size / 2] } +median = -> (values) { values.sort[values.size / 2] } base, head = ARGV.map do |path| - runs = (File.directory?(path) ? Dir[File.join(path, "*.json")].sort : [path]).map { |file| JSON.parse(File.read(file)) } - abort "No runs found in #{path}" if runs.empty? + runs = (File.directory?(path) ? Dir[File.join(path, "*.json")].sort : [path]).map { |file| + JSON.parse(File.read(file)) + } + abort("No runs found in #{path}") if runs.empty? runs.first.merge( "scenarios" => runs.first["scenarios"].to_h do |name, scenario| @@ -27,37 +29,46 @@ end ) end + threshold = Float(ENV.fetch("THRESHOLD", 0.05)) -puts "### ViewComponent performance (Rails #{head["rails"]}, #{head["ruby"].split.first(2).join(" ")})" +puts("### ViewComponent performance (Rails #{head["rails"]}, #{head["ruby"].split.first(2).join(" ")})") puts -puts "Ratios are component render time / equivalent partial render time; for `cold_digest`, cold component digest time / cold partial digest time; for `boot`, time spent in ViewComponent during boot / the rest of boot; and for `executor`, development executor time with ViewComponent / Rails alone. Lower is faster." +puts( + "Ratios are component render time / equivalent partial render time; for `cold_digest`, cold component digest time / cold partial digest time; for `boot`, time spent in ViewComponent during boot / the rest of boot; and for `executor`, development executor time with ViewComponent / Rails alone. Lower is faster." +) puts -puts "| Scenario | Base ratio | Head ratio | Change | Allocations (base → head) | |" -puts "| --- | ---: | ---: | ---: | ---: | --- |" +puts("| Scenario | Base ratio | Head ratio | Change | Allocations (base → head) | |") +puts("| --- | ---: | ---: | ---: | ---: | --- |") regressions = head["scenarios"].filter_map do |name, current| previous = base["scenarios"][name] unless previous - puts "| #{name} | — | #{format("%.3f", current["ratio"])} | new | #{current["component_allocations"]} | |" + puts("| #{name} | — | #{format("%.3f", current["ratio"])} | new | #{current["component_allocations"]} | |") next end change = current["ratio"] / previous["ratio"] - 1 regressed = current["ratio"] > previous["ratio"] * (1 + threshold) - puts format( - "| %s | %.3f | %.3f | %+.1f%% | %d → %d | %s |", - name, previous["ratio"], current["ratio"], change * 100, - previous["component_allocations"], current["component_allocations"], - regressed ? "❌" : "✅" + puts( + format( + "| %s | %.3f | %.3f | %+.1f%% | %d → %d | %s |", + name, + previous["ratio"], + current["ratio"], + change * 100, + previous["component_allocations"], + current["component_allocations"], + regressed ? "❌" : "✅" + ) ) name if regressed end puts if regressions.empty? - puts "No scenario regressed by more than #{(threshold * 100).round(1)}%." + puts("No scenario regressed by more than #{(threshold * 100).round(1)}%.") else - puts "Regressed by more than #{(threshold * 100).round(1)}%: #{regressions.join(", ")}." - exit 1 + puts("Regressed by more than #{(threshold * 100).round(1)}%: #{regressions.join(", ")}.") + exit(1) end diff --git a/performance/components/inline_component.rb b/performance/components/inline_component.rb index e17e7027b..0e3c4e0ee 100644 --- a/performance/components/inline_component.rb +++ b/performance/components/inline_component.rb @@ -21,7 +21,7 @@ def call safe_join( [ content, - 50.times.map { render NestedComponent.new(name: @name) } + 50.times.map { render(NestedComponent.new(name: @name)) } ], "\n\n" ) diff --git a/performance/components/new_inline_component.rb b/performance/components/new_inline_component.rb index d650379a6..84045da38 100644 --- a/performance/components/new_inline_component.rb +++ b/performance/components/new_inline_component.rb @@ -6,25 +6,29 @@ def initialize(name:) @name = name end - erb_template <<~ERB -

nested hello #{@name}

- ERB + erb_template( + <<~ERB +

nested hello #{@name}

+ ERB + ) end def initialize(name:) @name = name end - erb_template <<~ERB -

hello #{@name}

- <%= - safe_join( - [ - content, - 50.times.map { render NestedComponent.new(name: @name) } - ], - "\n\n" - ) - %> - ERB + erb_template( + <<~ERB +

hello #{@name}

+ <%= + safe_join( + [ + content, + 50.times.map { render NestedComponent.new(name: @name) } + ], + "\n\n" + ) + %> + ERB + ) end diff --git a/performance/components/slots_component.rb b/performance/components/slots_component.rb index ba68839a3..1773699a2 100644 --- a/performance/components/slots_component.rb +++ b/performance/components/slots_component.rb @@ -1,8 +1,8 @@ # frozen_string_literal: true class Performance::SlotsComponent < ViewComponent::Base - renders_one :header, ->(**kwargs) { HeaderComponent.new(**kwargs) } - renders_many :items, ->(**kwargs) { ItemComponent.new(**kwargs) } + renders_one :header, -> (**kwargs) { HeaderComponent.new(**kwargs) } + renders_many :items, -> (**kwargs) { ItemComponent.new(**kwargs) } class HeaderComponent < ViewComponent::Base attr_reader :classes diff --git a/performance/executor.rb b/performance/executor.rb index 3687ce70e..cf796c061 100644 --- a/performance/executor.rb +++ b/performance/executor.rb @@ -12,9 +12,11 @@ ENV["RAILS_ENV"] = "development" require "rails" require "action_controller/railtie" + unless ARGV[1] == "reference" $LOAD_PATH.unshift(ENV.fetch("VIEW_COMPONENT_LIB")) require "view_component" + end class ExecutorApp < Rails::Application @@ -27,6 +29,7 @@ class ExecutorApp < Rails::Application config.secret_key_base = "performance" config.logger = Logger.new(nil) end + ExecutorApp.initialize! raise "templates must not be cached" if ActionView::Base.cache_template_loading @@ -35,9 +38,11 @@ class ExecutorApp < Rails::Application GC.start allocations = GC.stat(:total_allocated_objects) start = clock.call - Array.new(4) do - Thread.new { iterations.times { ExecutorApp.executor.wrap {} } } - end.each(&:value) + Array + .new(4) do + Thread.new { iterations.times { ExecutorApp.executor.wrap { } } } + end + .each(&:value) { "seconds" => (clock.call - start) / (iterations * 4), "allocations" => (GC.stat(:total_allocated_objects) - allocations).fdiv(iterations * 4) @@ -49,7 +54,9 @@ class ExecutorApp < Rails::Application iterations *= 2 while measure.call(iterations)["seconds"] * iterations * 4 < sample_seconds / 4 iterations *= 4 -puts JSON.generate( - "iterations" => iterations * 4, - "samples" => Array.new(Integer(ENV.fetch("PASSES", 15))) { measure.call(iterations) } +puts( + JSON.generate( + "iterations" => iterations * 4, + "samples" => Array.new(Integer(ENV.fetch("PASSES", 15))) { measure.call(iterations) } + ) ) diff --git a/performance/measure.rb b/performance/measure.rb index 6e6706179..a4e9f9f1d 100755 --- a/performance/measure.rb +++ b/performance/measure.rb @@ -35,6 +35,7 @@ class PerformanceApp < Rails::Application config.secret_key_base = "performance" config.logger = Logger.new(nil) end + PerformanceApp.initialize! module Performance @@ -48,6 +49,7 @@ module Performance class BenchmarksController < ActionController::Base end + BenchmarksController.view_paths = [File.expand_path("views", __dir__)] view = BenchmarksController.new.view_context @@ -73,18 +75,21 @@ class BenchmarksController < ActionController::Base iterations.times(&block) (clock.call - start) / iterations end + allocations = lambda do |block| block.call before = GC.stat(:total_allocated_objects) block.call GC.stat(:total_allocated_objects) - before end + iterations_for = lambda do |block| iterations = 1 iterations *= 2 while time.call(block, iterations) * iterations < sample_seconds / 4 iterations * 4 end -median = ->(values) { values.sort[values.size / 2] } + +median = -> (values) { values.sort[values.size / 2] } measure = lambda do |name, reference, scenario| [reference, scenario].each { |block| 3.times(&block) } @@ -99,6 +104,7 @@ class BenchmarksController < ActionController::Base scenario_time = time.call(scenario, scenario_iterations) reference_time = time.call(reference, reference_iterations) end + [reference_time, scenario_time] end @@ -113,7 +119,15 @@ class BenchmarksController < ActionController::Base "reference_allocations" => allocations.call(reference), "component_allocations" => allocations.call(scenario) } - puts format("%-20s ratio %.3f component %.3fms partial %.3fms", name, ratio, result["component_ms"], result["reference_ms"]) + puts( + format( + "%-20s ratio %.3f component %.3fms partial %.3fms", + name, + ratio, + result["component_ms"], + result["reference_ms"] + ) + ) result end @@ -128,9 +142,12 @@ class BenchmarksController < ActionController::Base # Every component has a Slim counterpart, so non-ERB templates are covered too. render_call = lambda do |i| case i % 3 - when 0 then "render Sidecar#{i}Component.new(name: 'x')" - when 1 then "render(Inline#{i}Component.new) { 'x' }" - else "render Slots#{i}Component.new" + when 0 + "render Sidecar#{i}Component.new(name: 'x')" + when 1 + "render(Inline#{i}Component.new) { 'x' }" + else + "render Slots#{i}Component.new" end end @@ -143,61 +160,84 @@ class BenchmarksController < ActionController::Base shared_renders = shared_components.flat_map do |i| [render_call.call(i), "render Slim#{i}Component.new(name: 'x')"] end - File.write(File.join(components, "shared_component_helpers.rb"), <<~RUBY) - module SharedComponentHelpers - def shared_components - #{shared_renders.map { |render| " #{render}" }.join("\n")} + + File.write( + File.join(components, "shared_component_helpers.rb"), + <<~RUBY + module SharedComponentHelpers + def shared_components + #{shared_renders.map { |render| " #{render}" }.join("\n")} + end end - end - RUBY + RUBY + ) component_count.times do |i| rendered = render_call.call(i.zero? ? 1 : (i - 1) / 2) case i % 3 when 0 - File.write(File.join(components, "sidecar#{i}_component.rb"), <<~RUBY) - class Sidecar#{i}Component < ViewComponent::Base - include SharedComponentHelpers - - def initialize(name:) - @name = name + File.write( + File.join(components, "sidecar#{i}_component.rb"), + <<~RUBY + class Sidecar#{i}Component < ViewComponent::Base + include SharedComponentHelpers + + def initialize(name:) + @name = name + end end - end - RUBY + RUBY + ) File.write(File.join(components, "sidecar#{i}_component.html.erb"), "

<%= @name %>

<%= #{rendered} %>\n") when 1 - File.write(File.join(components, "inline#{i}_component.rb"), <<~RUBY) - class Inline#{i}Component < ViewComponent::Base - include SharedComponentHelpers + File.write( + File.join(components, "inline#{i}_component.rb"), + <<~RUBY + class Inline#{i}Component < ViewComponent::Base + include SharedComponentHelpers - erb_template "

<%= content %>

<%= #{rendered} %>" - end - RUBY + erb_template "

<%= content %>

<%= #{rendered} %>" + end + RUBY + ) else - File.write(File.join(components, "slots#{i}_component.rb"), <<~RUBY) - class Slots#{i}Component < ViewComponent::Base - include SharedComponentHelpers - - renders_one :header - renders_many :items - end - RUBY - File.write(File.join(components, "slots#{i}_component.html.erb"), "<%= header %><% items.each do |item| %><%= item %><% end %><%= #{rendered} %>\n") + File.write( + File.join(components, "slots#{i}_component.rb"), + <<~RUBY + class Slots#{i}Component < ViewComponent::Base + include SharedComponentHelpers + + renders_one :header + renders_many :items + end + RUBY + ) + File.write( + File.join(components, "slots#{i}_component.html.erb"), + "<%= header %><% items.each do |item| %><%= item %><% end %><%= #{rendered} %>\n" + ) end - File.write(File.join(components, "slim#{i}_component.rb"), <<~RUBY) - class Slim#{i}Component < ViewComponent::Base - include SharedComponentHelpers + File.write( + File.join(components, "slim#{i}_component.rb"), + <<~RUBY + class Slim#{i}Component < ViewComponent::Base + include SharedComponentHelpers - def initialize(name:) - @name = name + def initialize(name:) + @name = name + end end - end - RUBY - File.write(File.join(components, "slim#{i}_component.html.slim"), "p = @name\n== render Slim#{i.zero? ? 1 : (i - 1) / 2}Component.new(name: 'x')\n") + RUBY + ) + File.write( + File.join(components, "slim#{i}_component.html.slim"), + "p = @name\n== render Slim#{i.zero? ? 1 : (i - 1) / 2}Component.new(name: 'x')\n" + ) end require File.join(components, "shared_component_helpers") + Dir[File.join(components, "*_component.rb")].sort.each { |file| require file } # New lookup contexts are essential: existing contexts retain their digest @@ -207,16 +247,23 @@ def initialize(name:) finder = ActionView::LookupContext.new(BenchmarksController.view_paths, formats: [:html]) block.call(finder) end + digest_reference = proc do cold_digest.call { |finder| ActionView::Digestor.digest(name: "benchmarks/_partial", finder: finder) } end + digest_scenario = proc do cold_digest.call { |finder| Sidecar0Component.cache_digest(finder: finder) } end + results["cold_digest"] = measure.call("cold_digest", digest_reference, digest_scenario) boot = lambda do - output = IO.popen({"VIEW_COMPONENT_LIB" => view_component_lib}, [RbConfig.ruby, File.expand_path("boot.rb", __dir__), root], &:read) + output = IO.popen( + {"VIEW_COMPONENT_LIB" => view_component_lib}, + [RbConfig.ruby, File.expand_path("boot.rb", __dir__), root], + &:read + ) raise "boot failed" unless $?.success? JSON.parse(output) end @@ -232,7 +279,15 @@ def initialize(name:) "reference_allocations" => median.call(samples.map { |sample| sample["rest"]["allocations"] }), "component_allocations" => median.call(samples.map { |sample| sample["view_component"]["allocations"] }) } - puts format("%-20s ratio %.3f view_component %.3fms rest of boot %.3fms", "boot", result["ratio"], result["component_ms"], result["reference_ms"]) + puts( + format( + "%-20s ratio %.3f view_component %.3fms rest of boot %.3fms", + "boot", + result["ratio"], + result["component_ms"], + result["reference_ms"] + ) + ) results["boot"] = result # Non-template directories also contribute to the polling watcher's glob cost. @@ -249,6 +304,7 @@ def initialize(name:) raise "executor benchmark failed" unless $?.success? JSON.parse(output) end + reference_run, component_run = executor_runs reference_samples, component_samples = executor_runs.map { |run| run.fetch("samples") } ratios = reference_samples.zip(component_samples).map { |ref, component| component["seconds"] / ref["seconds"] } @@ -261,7 +317,15 @@ def initialize(name:) "reference_allocations" => median.call(reference_samples.map { |sample| sample["allocations"] }), "component_allocations" => median.call(component_samples.map { |sample| sample["allocations"] }) } - puts format("%-20s ratio %.3f view_component %.3fms rails %.3fms", "executor", result["ratio"], result["component_ms"], result["reference_ms"]) + puts( + format( + "%-20s ratio %.3f view_component %.3fms rails %.3fms", + "executor", + result["ratio"], + result["component_ms"], + result["reference_ms"] + ) + ) results["executor"] = result end diff --git a/script/console b/script/console index b6af72bdc..9658647bd 100755 --- a/script/console +++ b/script/console @@ -5,4 +5,5 @@ require "bundler/setup" require "view_component" require "irb" + IRB.start(__FILE__) diff --git a/script/format b/script/format new file mode 100755 index 000000000..58bdb2627 --- /dev/null +++ b/script/format @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +set -euo pipefail + +cd "$(dirname "$0")/.." +git ls-files -z -- '*.rb' '*.rake' '*.gemspec' '*.gemfile' '*Gemfile' '*Rakefile' Appraisals script/console | + xargs -0 rubyfmt --fail-fast "$@" diff --git a/script/regression_check.rb b/script/regression_check.rb index d3b62d0ca..325651cb8 100644 --- a/script/regression_check.rb +++ b/script/regression_check.rb @@ -17,7 +17,8 @@ module RegressionCheck RUNNER = File.expand_path("regression_check/runner.rb", __dir__) CHECKER_DIGEST = Digest::SHA256.hexdigest(File.read(__FILE__) + File.read(RUNNER)) - class Error < StandardError; end + class Error < StandardError + end class TestDefinitions < Prism::Visitor attr_reader :tests, :unsupported @@ -63,8 +64,10 @@ def visit_call_node(node) else @visibility[-1] = node.name end + return end + if node.name == :test && node.block argument = node.arguments&.arguments&.first if argument.is_a?(Prism::StringNode) && !node.receiver @@ -75,6 +78,7 @@ def visit_call_node(node) elsif [:it, :specify, :define_method].include?(node.name) @unsupported << "#{node.name} definition at line #{node.location.start_line}" end + super end @@ -94,6 +98,7 @@ def add(name, node) if @tests.key?(key) @unsupported << "duplicate test identity #{key}" end + @tests[key] = { "name" => name, "line" => node.location.start_line, @@ -117,7 +122,12 @@ def initialize(base:, output:, head: "HEAD", timeout: 90, install: false, root: @bundle_path = File.expand_path(bundle_path, Bundler.root) if bundle_path @report = { "checker_digest" => CHECKER_DIGEST, - "base" => @base, "head" => @head, "tests" => [], "notes" => [], "files" => [], "changed_files" => [] + "base" => @base, + "head" => @head, + "tests" => [], + "notes" => [], + "files" => [], + "changed_files" => [] } end @@ -142,6 +152,7 @@ def run end end end + write_report @report end @@ -174,6 +185,7 @@ def select_tests @report["notes"] << "Unsupported test file: #{path}" next end + old = TestDefinitions.new(before) current = TestDefinitions.new(after) current.unsupported.each { |reason| @report["notes"] << "#{path}: #{reason}" } @@ -182,12 +194,15 @@ def select_tests next if previous && previous["source"] == test["source"] test.except("source").merge( - "definition" => key, "change" => previous ? "modified" : "added" + "definition" => key, + "change" => previous ? "modified" : "added" ) end + @report["files"] << {"path" => path, "selected" => tests.length} selected[path] = tests unless tests.empty? end + selected end @@ -204,14 +219,19 @@ def specification(directory) @specifications[directory] ||= begin output, status = Bundler.with_unbundled_env do Open3.capture2e( - RbConfig.ruby, "-rjson", "-e", <<~RUBY, chdir: directory + RbConfig.ruby, + "-rjson", + "-e", + <<~RUBY, spec = Gem::Specification.load("view_component.gemspec") abort "Cannot load gemspec" unless spec bundler = spec.dependencies.find { |dependency| dependency.name == "bundler" } puts JSON.generate(files: spec.files, bundler: bundler&.requirement&.as_list) RUBY + chdir: directory ) end + raise Error, "Cannot load gemspec: #{output}" unless status.success? JSON.parse(output) @@ -223,7 +243,8 @@ def packaged_files(directory) raise Error, "Unsafe packaged path: #{path}" if Pathname.new(path).absolute? || path.split("/").include?("..") File.file?(File.join(directory, path)) && - path.start_with?("app/", "lib/") && !path.start_with?("app/views/test_mailer/") + path.start_with?("app/", "lib/") && + !path.start_with?("app/views/test_mailer/") end end @@ -242,9 +263,13 @@ def restore_implementation(directory, scratch) FileUtils.rm(destination) end end + @report["implementation_files"] = (head_files | base_files).sort - if git("diff", "--name-only", @base, @head, "--", "Gemfile", "view_component.gemspec", "gemfiles").length.positive? - @report["notes"] << "Dependencies changed. Both runs use the PR's dependencies; this does not compare dependency changes." + if git("diff", "--name-only", @base, @head, "--", "Gemfile", "view_component.gemspec", "gemfiles") + .length + .positive? + @report["notes"] << + "Dependencies changed. Both runs use the PR's dependencies; this does not compare dependency changes." end end @@ -257,7 +282,11 @@ def run_file(directory, file, tests, version, index) FileUtils.rm_f([result, "#{result}.tmp"]) env = test_environment(directory) status, timed_out = run_process( - env, [*bundle_command(directory), "exec", RbConfig.ruby, RUNNER, file, input, result], directory, log, @timeout + env, + [*bundle_command(directory), "exec", RbConfig.ruby, RUNNER, file, input, result], + directory, + log, + @timeout ) data = File.exist?(result) ? JSON.parse(File.read(result)) : {"tests" => []} data.merge("timeout" => timed_out, "exit_code" => status&.exitstatus, "log" => File.basename(log)) @@ -268,6 +297,7 @@ def test_environment(directory) if Pathname.new(gemfile).absolute? gemfile = Pathname.new(gemfile).relative_path_from(Pathname.new(@root)).to_s end + environment = { "BUNDLE_GEMFILE" => File.expand_path(gemfile, directory), "RAILS_ENV" => "test", @@ -288,9 +318,16 @@ def install_dependencies(directory) version = bundler_version(directory) requirements = version ? [version] : specification(directory)["bundler"] if requirements && Gem::Specification.find_all_by_name("bundler", Gem::Requirement.new(requirements)).empty? - status, _ = run_process(env, ["gem", "install", "bundler", "--version", requirements.join(", "), "--no-document"], directory, log, 180) + status, _ = run_process( + env, + ["gem", "install", "bundler", "--version", requirements.join(", "), "--no-document"], + directory, + log, + 180 + ) raise Error, "Bundler #{requirements.join(", ")} installation failed; see #{log}" unless status&.success? end + command = bundle_command(directory) status, timed_out = run_process(env, [*command, "install", "--quiet"], directory, log, 300) raise Error, "Dependency installation #{timed_out ? "timed out" : "failed"}; see #{log}" unless status&.success? @@ -303,7 +340,11 @@ def bundler_version(directory) requirement = specification(directory)["bundler"] if requirement - Gem::Specification.find_all_by_name("bundler", Gem::Requirement.new(requirement)).max_by(&:version)&.version&.to_s + Gem::Specification + .find_all_by_name("bundler", Gem::Requirement.new(requirement)) + .max_by(&:version) + &.version + &.to_s end end @@ -319,6 +360,7 @@ def run_process(env, command, directory, log, timeout) pid = Bundler.with_unbundled_env do Process.spawn(env, *command, chdir: directory, out: io, err: io, pgroup: true) end + deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout loop do waited = Process.waitpid2(pid, Process::WNOHANG) @@ -326,15 +368,18 @@ def run_process(env, command, directory, log, timeout) status = waited.last break end + if Process.clock_gettime(Process::CLOCK_MONOTONIC) >= deadline timed_out = true Process.kill("KILL", -pid) Process.waitpid(pid) break end - sleep 0.05 + + sleep(0.05) end end + [status, timed_out] end @@ -344,16 +389,29 @@ def compare(file, tests, head, base) tests.each do |definition| matches = head_tests.values.select { |test| test["definition"] == definition["definition"] } if matches.empty? - @report["tests"] << definition.merge("file" => file, "status" => "inconclusive", - "reason" => head["timeout"] ? "Head timed out" : "Test did not run on head", "head_log" => head["log"]) + @report["tests"] << + definition.merge( + "file" => file, + "status" => "inconclusive", + "reason" => head["timeout"] ? "Head timed out" : "Test did not run on head", + "head_log" => head["log"] + ) end + matches.each do |head_test| base_test = base_tests[head_test["id"]] status, reason = classify(head_test, base_test, head, base) - @report["tests"] << definition.merge( - "file" => file, "id" => head_test["id"], "status" => status, "reason" => reason, - "head" => head_test, "base" => base_test, "head_log" => head["log"], "base_log" => base["log"] - ) + @report["tests"] << + definition.merge( + "file" => file, + "id" => head_test["id"], + "status" => status, + "reason" => reason, + "head" => head_test, + "base" => base_test, + "head_log" => head["log"], + "base_log" => base["log"] + ) end end end @@ -365,20 +423,28 @@ def classify(head_test, base_test, head, base) if head["exit_code"] != 0 && head["tests"].none? { |test| ["failed", "error"].include?(test["status"]) } return ["inconclusive", "Head failed outside the selected tests"] end + return ["head_failed", "Test does not pass on head"] if ["failed", "error"].include?(head_test["status"]) - return ["inconclusive", "Test skipped or made no assertions on head"] if head_test["status"] != "passed" || head_test["assertions"].zero? + if head_test["status"] != "passed" || head_test["assertions"].zero? + return ["inconclusive", "Test skipped or made no assertions on head"] + end + return ["inconclusive", "Base timed out"] if base["timeout"] return ["inconclusive", "Base test run did not complete"] unless base["completed"] return ["inconclusive", "Base process did not complete normally"] unless [0, 1].include?(base["exit_code"]) if base["exit_code"] != 0 && base["tests"].none? { |test| ["failed", "error"].include?(test["status"]) } return ["inconclusive", "Base failed outside the selected tests"] end + return ["inconclusive", "Test did not run on base"] unless base_test case base_test["status"] - when "failed" then ["demonstrated", "Passes on head; assertion fails without the implementation"] - when "passed" then ["not_demonstrated", "Also passes without the implementation"] - else ["inconclusive", "Base #{base_test["status"]}: inspect the recorded exception"] + when "failed" + ["demonstrated", "Passes on head; assertion fails without the implementation"] + when "passed" + ["not_demonstrated", "Also passes without the implementation"] + else + ["inconclusive", "Base #{base_test["status"]}: inspect the recorded exception"] end end @@ -386,8 +452,10 @@ def write_report @report["counts"] = @report["tests"].group_by { |test| test["status"] }.transform_values(&:length) File.write(File.join(@output, "results.json"), JSON.pretty_generate(@report) + "\n") lines = [ - "## Regression check", "", - "Base: `#{@base}`; head: `#{@head}`.", "", + "## Regression check", + "", + "Base: `#{@base}`; head: `#{@head}`.", + "", "| Test | Change | Result | Detail |", "| --- | --- | --- | --- |" ] @@ -395,12 +463,15 @@ def write_report values = [test["id"] || "#{test["file"]}:#{test["line"]}", test["change"], test["status"], test["reason"]] lines << "| #{values.map { |value| RegressionCheck.table_cell(value) }.join(" | ")} |" end + lines << "" << "No added or modified tests were selected." if @report["tests"].empty? @report["notes"].each { |note| lines << "" << "- #{note}" } - lines << "" << "Assertion failures demonstrate a difference, not necessarily a bug. Errors, skips, timeouts, and missing results are inconclusive." + lines << + "" << + "Assertion failures demonstrate a difference, not necessarily a bug. Errors, skips, timeouts, and missing results are inconclusive." summary = lines.join("\n") + "\n" File.write(File.join(@output, "summary.md"), summary) - puts summary + puts(summary) end end @@ -411,21 +482,23 @@ def self.table_cell(value) def self.main(argv) options = {head: "HEAD", output: "tmp/regression-check", timeout: 90} strict = false - OptionParser.new do |parser| - parser.banner = "Usage: ruby script/regression_check.rb --base REV [options]" - parser.on("--base REV") { |value| options[:base] = value } - parser.on("--head REV") { |value| options[:head] = value } - parser.on("--output DIR") { |value| options[:output] = value } - parser.on("--timeout SECONDS", Integer) { |value| options[:timeout] = value } - parser.on("--install") { options[:install] = true } - parser.on("--strict") { strict = true } - end.parse!(argv) + OptionParser + .new do |parser| + parser.banner = "Usage: ruby script/regression_check.rb --base REV [options]" + parser.on("--base REV") { |value| options[:base] = value } + parser.on("--head REV") { |value| options[:head] = value } + parser.on("--output DIR") { |value| options[:output] = value } + parser.on("--timeout SECONDS", Integer) { |value| options[:timeout] = value } + parser.on("--install") { options[:install] = true } + parser.on("--strict") { strict = true } + end + .parse!(argv) raise Error, "--base is required" unless options[:base] raise Error, "--timeout must be positive" unless options[:timeout].positive? exit_code(Check.new(**options).run, strict: strict) rescue Error, OptionParser::ParseError => error - warn error.message + warn(error.message) 1 end @@ -436,4 +509,4 @@ def self.exit_code(report, strict:) end end -exit RegressionCheck.main(ARGV) if $PROGRAM_NAME == __FILE__ +exit(RegressionCheck.main(ARGV)) if $PROGRAM_NAME == __FILE__ diff --git a/script/regression_check/runner.rb b/script/regression_check/runner.rb index 77a79b850..292c722d8 100644 --- a/script/regression_check/runner.rb +++ b/script/regression_check/runner.rb @@ -23,8 +23,10 @@ definitions["#{klass.name}##{name}"] = definition["definition"] if definition definition end + [klass, selected] end + selected_methods.each { |klass, methods| klass.define_singleton_method(:runnable_methods) { methods } } reporter_class = Class.new(Minitest::AbstractReporter) do @@ -43,11 +45,15 @@ else "failed" end - @results << { - "id" => id, "definition" => definitions.fetch(id), "status" => status, - "assertions" => result.assertions, - "failures" => result.failures.map { |failure| {"class" => failure.class.name, "message" => failure.message} } - } + + @results << + { + "id" => id, + "definition" => definitions.fetch(id), + "status" => status, + "assertions" => result.assertions, + "failures" => result.failures.map { |failure| {"class" => failure.class.name, "message" => failure.message} } + } write_results(false) end @@ -65,6 +71,7 @@ Minitest.singleton_class.define_method(:plugin_regression_check_init) do |_options| reporter << reporter_class.new end + Minitest.extensions << "regression_check" ARGV.replace(["--seed", "0"]) Minitest.autorun diff --git a/script/regression_check_history.rb b/script/regression_check_history.rb index 9cdb0cb89..ef76d7c91 100644 --- a/script/regression_check_history.rb +++ b/script/regression_check_history.rb @@ -4,44 +4,61 @@ require_relative "regression_check" options = {limit: 100, output: "tmp/regression-history", timeout: 90} -OptionParser.new do |parser| - parser.banner = "Usage: ruby script/regression_check_history.rb [options]" - parser.on("--limit NUMBER", Integer) { |value| options[:limit] = value } - parser.on("--output DIR") { |value| options[:output] = value } - parser.on("--timeout SECONDS", Integer) { |value| options[:timeout] = value } -end.parse! -abort "--limit must be between 1 and 100" unless (1..100).cover?(options[:limit]) +OptionParser + .new do |parser| + parser.banner = "Usage: ruby script/regression_check_history.rb [options]" + parser.on("--limit NUMBER", Integer) { |value| options[:limit] = value } + parser.on("--output DIR") { |value| options[:output] = value } + parser.on("--timeout SECONDS", Integer) { |value| options[:timeout] = value } + end + .parse! +abort("--limit must be between 1 and 100") unless (1..100).cover?(options[:limit]) output = File.expand_path(options[:output]) FileUtils.mkdir_p(output) metadata = File.join(output, "pull_requests.json") unless File.exist?(metadata) json, status = Open3.capture2e( - "gh", "api", "--method", "GET", "repos/ViewComponent/view_component/pulls", - "-f", "state=all", "-f", "sort=created", "-f", "direction=desc", "-f", "per_page=#{options[:limit]}" + "gh", + "api", + "--method", + "GET", + "repos/ViewComponent/view_component/pulls", + "-f", + "state=all", + "-f", + "sort=created", + "-f", + "direction=desc", + "-f", + "per_page=#{options[:limit]}" ) - abort json unless status.success? + abort(json) unless status.success? pulls = JSON.parse(json).map do |pr| pr.slice("number", "title", "html_url", "state", "merged_at", "created_at").merge( - "base_sha" => pr.fetch("base").fetch("sha"), "head_sha" => pr.fetch("head").fetch("sha") + "base_sha" => pr.fetch("base").fetch("sha"), + "head_sha" => pr.fetch("head").fetch("sha") ) end + File.write(metadata, JSON.pretty_generate(pulls) + "\n") end + pulls = JSON.parse(File.read(metadata)).first(options[:limit]) pulls.each_slice(10) do |batch| refs = batch.map { |pr| "+refs/pull/#{pr.fetch("number")}/head:refs/regression-check/#{pr.fetch("number")}" } log, status = Open3.capture2e("git", "fetch", "--no-tags", "origin", *refs) - abort log unless status.success? + abort(log) unless status.success? end results = pulls.map do |pr| directory = File.join(output, pr.fetch("number").to_s) result_path = File.join(directory, "results.json") report = File.exist?(result_path) ? JSON.parse(File.read(result_path)) : nil - unless report && report["checker_digest"] == RegressionCheck::CHECKER_DIGEST && + unless report && + report["checker_digest"] == RegressionCheck::CHECKER_DIGEST && report["head"] == pr.fetch("head_sha") - puts "Checking ##{pr.fetch("number")}: #{pr.fetch("title")}" + puts("Checking ##{pr.fetch("number")}: #{pr.fetch("title")}") begin [pr.fetch("head_sha"), pr.fetch("base_sha")].each do |sha| _, status = Open3.capture2e("git", "cat-file", "-e", "#{sha}^{commit}") @@ -50,33 +67,52 @@ raise RegressionCheck::Error, log unless status.success? end end - report = RegressionCheck::Check.new( - base: pr.fetch("base_sha"), head: pr.fetch("head_sha"), output: directory, - timeout: options[:timeout], install: true - ).run + + report = RegressionCheck::Check + .new( + base: pr.fetch("base_sha"), + head: pr.fetch("head_sha"), + output: directory, + timeout: options[:timeout], + install: true + ) + .run rescue RegressionCheck::Error => error report = { - "checker_digest" => RegressionCheck::CHECKER_DIGEST, "head" => pr.fetch("head_sha"), - "tests" => [], "counts" => {}, "notes" => [], "error" => error.message + "checker_digest" => RegressionCheck::CHECKER_DIGEST, + "head" => pr.fetch("head_sha"), + "tests" => [], + "counts" => {}, + "notes" => [], + "error" => error.message } FileUtils.mkdir_p(directory) File.write(result_path, JSON.pretty_generate(report) + "\n") - warn "##{pr.fetch("number")}: #{error.message}" + warn("##{pr.fetch("number")}: #{error.message}") end end + pr.merge("report" => report) end File.write(File.join(output, "results.json"), JSON.pretty_generate(results) + "\n") -counts = results.flat_map { |pr| pr.fetch("report").fetch("tests") }.group_by { |test| test.fetch("status") }.transform_values(&:length) +counts = results + .flat_map { |pr| pr.fetch("report").fetch("tests") } + .group_by { |test| test.fetch("status") } + .transform_values(&:length) selected_prs = results.count { |pr| pr.fetch("report").fetch("tests").any? } errors = results.count { |pr| pr.fetch("report")["error"] } lines = [ - "# Historical regression check", "", - "Latest #{pulls.length} pull requests by creation time, including open and closed pull requests. PR metadata is frozen in `pull_requests.json`.", "", - "Ruby #{RUBY_VERSION}; Rails 8.1 appraisal from each PR. Tests use each PR's dependencies.", "", - "#{selected_prs} PRs had selected tests; #{errors} PRs could not complete dependency setup.", "", - "Test results: #{counts.map { |status, count| "#{count} #{status}" }.join(", ")}.", "", + "# Historical regression check", + "", + "Latest #{pulls.length} pull requests by creation time, including open and closed pull requests. PR metadata is frozen in `pull_requests.json`.", + "", + "Ruby #{RUBY_VERSION}; Rails 8.1 appraisal from each PR. Tests use each PR's dependencies.", + "", + "#{selected_prs} PRs had selected tests; #{errors} PRs could not complete dependency setup.", + "", + "Test results: #{counts.map { |status, count| "#{count} #{status}" }.join(", ")}.", + "", "| PR | Demonstrated | Also passes on base | Inconclusive | Head failed | Notes |", "| --- | --- | --- | --- | --- | --- |" ] @@ -92,13 +128,16 @@ ] lines << "| #{values.map { |value| RegressionCheck.table_cell(value) }.join(" | ")} |" end + lines << "" << "## Tests that also pass without the implementation" << "" results.each do |pr| tests = pr.fetch("report").fetch("tests").select { |test| test.fetch("status") == "not_demonstrated" } next if tests.empty? - lines << "- [##{pr.fetch("number")}](#{pr.fetch("html_url")}): #{tests.map { |test| "`#{test.fetch("id")}` (#{test.fetch("change")})" }.join(", ")}" + lines << + "- [##{pr.fetch("number")}](#{pr.fetch("html_url")}): #{tests.map { |test| "`#{test.fetch("id")}` (#{test.fetch("change")})" }.join(", ")}" end + lines << "" << "## Implementation changes without selected tests" << "" results.each do |pr| report = pr.fetch("report") @@ -107,10 +146,14 @@ paths = report.fetch("changed_files", []).map { |file| file.fetch("path") }.select do |path| path.start_with?("app/", "lib/") && !path.start_with?("app/views/test_mailer/") end + next if paths.empty? lines << "- [##{pr.fetch("number")}](#{pr.fetch("html_url")}): #{paths.map { |path| "`#{path}`" }.join(", ")}" end -lines << "" << "Passing on base is a review signal, not proof of missing coverage. Pre-fix exceptions, unsupported definitions, dependency problems, and historical head failures require manual review." + +lines << + "" << + "Passing on base is a review signal, not proof of missing coverage. Pre-fix exceptions, unsupported definitions, dependency problems, and historical head failures require manual review." File.write(File.join(output, "summary.md"), lines.join("\n") + "\n") -puts lines.join("\n") +puts(lines.join("\n")) diff --git a/script/sync_contributors.rb b/script/sync_contributors.rb index 215593d8a..69a5cfb99 100755 --- a/script/sync_contributors.rb +++ b/script/sync_contributors.rb @@ -8,7 +8,8 @@ def fetch_contributors all_contributors = [] page = 1 - per_page = 100 # Maximum allowed by GitHub API + # Maximum allowed by GitHub API + per_page = 100 loop do uri = URI("https://api.github.com/repos/viewcomponent/view_component/contributors") @@ -24,8 +25,8 @@ def fetch_contributors if response.code == "200" JSON.parse(response.body) else - puts "Error fetching contributors (page #{page}): #{response.code} #{response.message}" - exit 1 + puts("Error fetching contributors (page #{page}): #{response.code} #{response.message}") + exit(1) end end @@ -33,7 +34,7 @@ def fetch_contributors break if contributors.empty? all_contributors.concat(contributors) - puts "Fetched page #{page} with #{contributors.length} contributors" + puts("Fetched page #{page} with #{contributors.length} contributors") # Break if we got less than the full page size (last page) break if contributors.length < per_page @@ -46,9 +47,11 @@ def fetch_contributors # Transform contributors data for YAML output def transform_contributors(contributors) - usernames = contributors.map do |contributor| - contributor["login"].downcase - end.sort + usernames = contributors + .map do |contributor| + contributor["login"].downcase + end + .sort {"usernames" => usernames} end @@ -61,23 +64,23 @@ def write_contributors_yaml(data) FileUtils.mkdir_p(File.dirname(output_path)) File.write(output_path, data.to_yaml) - puts "Contributors synced to #{output_path}" - puts "Found #{data["usernames"].length} contributors" + puts("Contributors synced to #{output_path}") + puts("Found #{data["usernames"].length} contributors") end # Main execution begin - puts "Fetching contributors from GitHub API..." + puts("Fetching contributors from GitHub API...") contributors = fetch_contributors - puts "Transforming contributor data..." + puts("Transforming contributor data...") transformed_data = transform_contributors(contributors) - puts "Writing to YAML file..." + puts("Writing to YAML file...") write_contributors_yaml(transformed_data) - puts "Successfully synced contributors!" + puts("Successfully synced contributors!") rescue => e - puts "Error: #{e.message}" - exit 1 + puts("Error: #{e.message}") + exit(1) end diff --git a/spec/components/feature_spec.rb b/spec/components/feature_spec.rb index d6f8a27f9..bd1eb2983 100644 --- a/spec/components/feature_spec.rb +++ b/spec/components/feature_spec.rb @@ -1,22 +1,22 @@ require "spec_helper" -RSpec.feature "Feature specs for isolated view components" do +RSpec.feature("Feature specs for isolated view components") do # Ruby head ships a net-protocol whose Net::BufferedIO#readuntil signature # doesn't match Ruby head's IO, which prevents Capybara from booting its # server. Skip these specs on Ruby head until upstream catches up. if RUBY_VERSION.start_with?("4.1.") - before { skip "Skipping feature specs on Ruby head (net-protocol/Capybara incompatible)" } + before { skip("Skipping feature specs on Ruby head (net-protocol/Capybara incompatible)") } end - scenario "page is a Capybara::Session" do - expect(page).to be_a Capybara::Session + scenario("page is a Capybara::Session") do + expect(page).to(be_a(Capybara::Session)) end - scenario "page responds to visit" do - expect(page).to respond_to :visit + scenario("page responds to visit") do + expect(page).to(respond_to(:visit)) end - scenario "visit the isolated, rendered component" do + scenario("visit the isolated, rendered component") do with_rendered_component_path(render_inline(MyComponent.new)) do |path| visit(path) end diff --git a/spec/components/previews/preview_component_spec.rb b/spec/components/previews/preview_component_spec.rb index b5b8a754b..2b93fc928 100644 --- a/spec/components/previews/preview_component_spec.rb +++ b/spec/components/previews/preview_component_spec.rb @@ -6,7 +6,7 @@ it "renders the preview" do render_preview(:default) - expect(page).to have_css "h1", text: "Lorem Ipsum" + expect(page).to(have_css("h1", text: "Lorem Ipsum")) end end @@ -16,6 +16,6 @@ end it "raises an error" do - expect { render_preview(:default) }.to raise_error(/expected a described_class/) + expect { render_preview(:default) }.to(raise_error(/expected a described_class/)) end end diff --git a/spec/components/system_spec.rb b/spec/components/system_spec.rb index e23beb317..821f30e77 100644 --- a/spec/components/system_spec.rb +++ b/spec/components/system_spec.rb @@ -5,28 +5,28 @@ # doesn't match Ruby head's IO, which prevents Capybara from booting its # server. Skip these specs on Ruby head until upstream catches up. if RUBY_VERSION.start_with?("4.1.") - before { skip "Skipping system specs on Ruby head (net-protocol/Capybara incompatible)" } + before { skip("Skipping system specs on Ruby head (net-protocol/Capybara incompatible)") } end before do driven_by(:system_test_driver) end - scenario "page is a Capybara::Session" do - expect(page).to be_a Capybara::Session + scenario("page is a Capybara::Session") do + expect(page).to(be_a(Capybara::Session)) end - scenario "page responds to visit" do - expect(page).to respond_to :visit + scenario("page responds to visit") do + expect(page).to(respond_to(:visit)) end - scenario "visit the isolated, rendered component" do + scenario("visit the isolated, rendered component") do with_rendered_component_path(render_inline(SimpleJavascriptInteractionWithJsIncludedComponent.new)) do |path| - visit path + visit(path) - assert find("[data-hidden-field]", visible: false) + assert(find("[data-hidden-field]", visible: false)) find("[data-button]", text: "Click Me To Reveal Something Cool").click - assert find("[data-hidden-field]", visible: true) + assert(find("[data-hidden-field]", visible: true)) end end end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 55850f655..4f01967fc 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -22,6 +22,7 @@ def self.warn(message) ENV["RAILS_ENV"] = "test" require "view_component/deprecation" + ViewComponent::Deprecation.behavior = :silence require File.expand_path("../../test/sandbox/config/environment.rb", __FILE__) @@ -38,7 +39,7 @@ def self.warn(message) end RSpec.configure do |config| - config.include ViewComponent::TestHelpers - config.include ViewComponent::SystemSpecHelpers, type: :feature - config.include ViewComponent::SystemSpecHelpers, type: :system + config.include(ViewComponent::TestHelpers) + config.include(ViewComponent::SystemSpecHelpers, type: :feature) + config.include(ViewComponent::SystemSpecHelpers, type: :system) end diff --git a/test/docs_rake_task_test.rb b/test/docs_rake_task_test.rb index f88592636..66988fbae 100644 --- a/test/docs_rake_task_test.rb +++ b/test/docs_rake_task_test.rb @@ -4,7 +4,7 @@ class DocsRakeTaskTest < ActiveSupport::TestCase def test_rake_task - load "Rakefile" + load("Rakefile") assert_nothing_raised do Rake::Task["docs:build"].invoke diff --git a/test/isolated/template_caching_test.rb b/test/isolated/template_caching_test.rb index 7350f37b3..01aaca14f 100644 --- a/test/isolated/template_caching_test.rb +++ b/test/isolated/template_caching_test.rb @@ -21,11 +21,11 @@ def test_executor_does_not_check_for_template_changes_when_templates_are_not_cac watcher.define_singleton_method(:execute_if_updated) { checks += 1 } ViewComponent::CompileCache.stub(:template_watcher, watcher) do app = boot_app("development") - refute ActionView::Base.cache_template_loading - Thread.new { app.executor.wrap {} }.value + refute(ActionView::Base.cache_template_loading) + Thread.new { app.executor.wrap { } }.value end - assert_equal 0, checks + assert_equal(0, checks) end def test_reloader_checks_for_template_changes_when_templates_are_not_cached @@ -34,9 +34,9 @@ def test_reloader_checks_for_template_changes_when_templates_are_not_cached watcher.expect(:execute_if_updated, nil) ViewComponent::CompileCache.stub(:template_watcher, watcher) do app = boot_app("development") - refute ActionView::Base.cache_template_loading - assert_includes app.reloaders, watcher - app.reloader.wrap {} + refute(ActionView::Base.cache_template_loading) + assert_includes(app.reloaders, watcher) + app.reloader.wrap { } end watcher.verify @@ -50,9 +50,10 @@ def test_reloader_watches_autoload_paths_given_as_pathnames app = boot_app("development", root: root) do config.autoload_paths << Pathname.new(root).join("lib/components") end - refute ActionView::Base.cache_template_loading - app.reloader.wrap {} + refute(ActionView::Base.cache_template_loading) + + app.reloader.wrap { } end end @@ -60,18 +61,22 @@ def test_reloader_watches_autoload_paths_given_as_pathnames # so the executor must not read it on every request when templates are cached. def test_executor_does_nothing_when_templates_are_cached app = boot_app("production") - assert ActionView::Base.cache_template_loading + assert(ActionView::Base.cache_template_loading) reads = 0 - ActionView::Resolver.singleton_class.prepend(Module.new do - define_method(:caching?) do - reads += 1 - super() + ActionView::Resolver.singleton_class.prepend( + Module.new do + define_method(:caching?) do + reads += 1 + super() + end end - end) - ViewComponent::CompileCache.stub(:template_watcher, ->(*) { flunk "templates were watched" }) { app.executor.wrap {} } + ) + ViewComponent::CompileCache.stub(:template_watcher, -> (*) { flunk("templates were watched") }) { + app.executor.wrap { } + } - assert_equal 0, reads + assert_equal(0, reads) end def test_template_changes_are_not_reflected_on_new_request_when_templates_are_cached @@ -81,15 +86,21 @@ def test_template_changes_are_not_reflected_on_new_request_when_templates_are_ca app = boot_app("production", root: root) app.routes.draw do - get "/", to: ->(_env) { [200, {"content-type" => "text/html"}, [ActionController::Base.render(GreetingComponent.new)]] } + get( + "/", + to: -> (_env) { + [200, {"content-type" => "text/html"}, [ActionController::Base.render(GreetingComponent.new)]] + } + ) end + request = Rack::MockRequest.new(app) - assert_equal "
Hello
", request.get("/").body.strip + assert_equal("
Hello
", request.get("/").body.strip) write_file(root, "app/components/greeting_component.html.erb", "
Goodbye
") - assert_equal "
Hello
", request.get("/").body.strip + assert_equal("
Hello
", request.get("/").body.strip) end end @@ -101,8 +112,8 @@ def test_component_digests_are_computed_at_boot_when_templates_are_cached boot_app("production", root: root) finder = ActionView::LookupContext.new(ActionController::Base.view_paths, formats: [:html]) - assert GreetingComponent.__vc_cache_digest_source - assert finder.digest_cache["view_component/cache_digest/greeting_component.html"] + assert(GreetingComponent.__vc_cache_digest_source) + assert(finder.digest_cache["view_component/cache_digest/greeting_component.html"]) end end @@ -113,22 +124,26 @@ def test_new_variant_templates_are_discovered_on_the_next_development_request app = boot_app("development", root: root) { config.hosts.clear } request = component_request(app, "GreetingComponent", variants: [:phone]) - assert_equal "
Default
", request.get("/").body.strip + assert_equal("
Default
", request.get("/").body.strip) write_file(root, "app/components/greeting_component.html+phone.erb", "
Phone
") - assert_equal "
Phone
", request.get("/").body.strip + assert_equal("
Phone
", request.get("/").body.strip) end end def test_cached_component_template_edits_are_visible_on_the_next_development_request Dir.mktmpdir do |root| - write_file(root, "app/components/greeting_component.rb", <<~RUBY) - class GreetingComponent < ViewComponent::Base - cache_on :identity - def identity = "greeting" - end - RUBY + write_file( + root, + "app/components/greeting_component.rb", + <<~RUBY + class GreetingComponent < ViewComponent::Base + cache_on :identity + def identity = "greeting" + end + RUBY + ) write_file(root, "app/components/greeting_component.html.erb", "
Before
") app = boot_app("development", root: root) do @@ -137,13 +152,14 @@ def identity = "greeting" config.cache_store = :memory_store config.file_watcher = ActiveSupport::FileUpdateChecker end + request = component_request(app, "GreetingComponent", variants: []) - assert_equal "
Before
", request.get("/").body.strip + assert_equal("
Before
", request.get("/").body.strip) write_file(root, "app/components/greeting_component.html.erb", "
After
") - assert_equal "
After
", request.get("/").body.strip + assert_equal("
After
", request.get("/").body.strip) end end @@ -155,11 +171,11 @@ def test_removed_variant_templates_are_forgotten_on_the_next_development_request app = boot_app("development", root: root) { config.hosts.clear } request = component_request(app, "GreetingComponent", variants: [:phone]) - assert_equal "
Phone
", request.get("/").body.strip + assert_equal("
Phone
", request.get("/").body.strip) File.delete(File.join(root, "app/components/greeting_component.html+phone.erb")) - assert_equal "
Default
", request.get("/").body.strip + assert_equal("
Default
", request.get("/").body.strip) end end @@ -167,19 +183,23 @@ def test_parent_rendering_discovers_new_variant_templates Dir.mktmpdir do |root| write_file(root, "app/components/greeting_component.rb", "class GreetingComponent < ViewComponent::Base; end") write_file(root, "app/components/greeting_component.html.erb", "
Default
") - write_file(root, "app/components/child_component.rb", <<~RUBY) - class ChildComponent < GreetingComponent - erb_template "
<% render_parent %>
" - end - RUBY + write_file( + root, + "app/components/child_component.rb", + <<~RUBY + class ChildComponent < GreetingComponent + erb_template "
<% render_parent %>
" + end + RUBY + ) app = boot_app("development", root: root) { config.hosts.clear } request = component_request(app, "ChildComponent", variants: [:phone]) - assert_equal "
Default
", request.get("/").body.strip + assert_equal("
Default
", request.get("/").body.strip) write_file(root, "app/components/greeting_component.html+phone.erb", "
Phone
") - assert_equal "
Phone
", request.get("/").body.strip + assert_equal("
Phone
", request.get("/").body.strip) end end @@ -191,13 +211,13 @@ def test_compilation_recovers_after_a_duplicate_template_is_removed boot_app("development", root: root) GreetingComponent.__vc_compile - refute GreetingComponent.__vc_compiled? + refute(GreetingComponent.__vc_compiled?) File.delete(File.join(root, "app/components/greeting_component/greeting_component.html.erb")) ViewComponent::CompileCache.invalidate! GreetingComponent.__vc_compile - assert GreetingComponent.__vc_compiled? + assert(GreetingComponent.__vc_compiled?) end end @@ -209,11 +229,11 @@ def test_inherited_templates_discover_new_parent_variants app = boot_app("development", root: root) { config.hosts.clear } request = component_request(app, "ChildComponent", variants: [:phone]) - assert_equal "
Default
", request.get("/").body.strip + assert_equal("
Default
", request.get("/").body.strip) write_file(root, "app/components/greeting_component.html+phone.erb", "
Phone
") - assert_equal "
Phone
", request.get("/").body.strip + assert_equal("
Phone
", request.get("/").body.strip) end end @@ -228,12 +248,13 @@ def test_inherited_templates_reload_outside_development_and_test config.file_watcher = ActiveSupport::FileUpdateChecker config.hosts.clear end + request = component_request(app, "ChildComponent", variants: []) - assert_equal "
Before
", request.get("/").body.strip + assert_equal("
Before
", request.get("/").body.strip) write_file(root, "app/components/greeting_component.html.erb", "
After parent edit
") - assert_equal "
After parent edit
", request.get("/").body.strip + assert_equal("
After parent edit
", request.get("/").body.strip) end end @@ -245,14 +266,18 @@ def test_compilation_and_digest_precomputation_share_template_source_reads reads = 0 read = File.method(:read) - File.stub(:read, lambda { |path, *args, **kwargs| - reads += 1 if path == template_path - read.call(path, *args, **kwargs) - }) { boot_app("production", root: root) } - - assert_equal 1, reads - assert GreetingComponent.__vc_cache_digest_source - assert_equal "
Hello
", ActionController::Base.render(GreetingComponent.new).strip + File + .stub( + :read, + lambda { |path, *args, **kwargs| + reads += 1 if path == template_path + read.call(path, *args, **kwargs) + } + ) { boot_app("production", root: root) } + + assert_equal(1, reads) + assert(GreetingComponent.__vc_cache_digest_source) + assert_equal("
Hello
", ActionController::Base.render(GreetingComponent.new).strip) end end @@ -267,8 +292,8 @@ def test_component_renders_do_not_log_missing_templates_at_boot log = StringIO.new boot_app("production", root: root) { config.logger = Logger.new(log) } - assert ParentComponent.__vc_cache_digest_source - refute_match "Couldn't find template", log.string + assert(ParentComponent.__vc_cache_digest_source) + refute_match("Couldn't find template", log.string) end end @@ -279,20 +304,24 @@ def test_component_digests_are_not_computed_at_boot_when_templates_are_not_cache boot_app("development", root: root) - assert_nil GreetingComponent.__vc_cache_digest_source + assert_nil(GreetingComponent.__vc_cache_digest_source) end end def test_facade_renders_do_not_log_missing_templates_at_boot Dir.mktmpdir do |root| - write_file(root, "app/models/design_system.rb", <<~RUBY) - class DesignSystem - module Methods - def button(...) = ChildComponent.new(...) + write_file( + root, + "app/models/design_system.rb", + <<~RUBY + class DesignSystem + module Methods + def button(...) = ChildComponent.new(...) + end + extend Methods end - extend Methods - end - RUBY + RUBY + ) write_file(root, "app/components/child_component.rb", "class ChildComponent < ViewComponent::Base; end") write_file(root, "app/components/child_component.html.erb", "
Child
") write_file(root, "app/components/parent_component.rb", "class ParentComponent < ViewComponent::Base; end") @@ -301,26 +330,30 @@ def button(...) = ChildComponent.new(...) log = StringIO.new boot_app("production", root: root) { config.logger = Logger.new(log) } - assert ParentComponent.__vc_cache_digest_source - refute_match "Couldn't find template", log.string - assert_equal "
Child
", ActionController::Base.render(ParentComponent.new).strip + assert(ParentComponent.__vc_cache_digest_source) + refute_match("Couldn't find template", log.string) + assert_equal("
Child
", ActionController::Base.render(ParentComponent.new).strip) end end def test_missing_literal_and_explicit_dependencies_still_log_at_boot Dir.mktmpdir do |root| write_file(root, "app/components/parent_component.rb", "class ParentComponent < ViewComponent::Base; end") - write_file(root, "app/components/parent_component.html.erb", <<~ERB) - <%# Template Dependency: buttons/button %> - <%= render UI.button %> - <%= render "missing/partial" %> - ERB + write_file( + root, + "app/components/parent_component.html.erb", + <<~ERB + <%# Template Dependency: buttons/button %> + <%= render UI.button %> + <%= render "missing/partial" %> + ERB + ) log = StringIO.new boot_app("production", root: root) { config.logger = Logger.new(log) } - assert_match "Couldn't find template for digesting: buttons/button", log.string - assert_match "Couldn't find template for digesting: missing/partial", log.string + assert_match("Couldn't find template for digesting: buttons/button", log.string) + assert_match("Couldn't find template for digesting: missing/partial", log.string) end end @@ -328,27 +361,33 @@ def test_missing_literal_and_explicit_dependencies_still_log_at_boot def component_request(app, component_name, variants:) app.routes.prepend do - get "/", to: lambda { |_env| - context = ActionController::Base.new.view_context - context.lookup_context.variants = variants - [200, {"content-type" => "text/html"}, [component_name.constantize.new.render_in(context)]] - } + get( + "/", + to: lambda { |_env| + context = ActionController::Base.new.view_context + context.lookup_context.variants = variants + [200, {"content-type" => "text/html"}, [component_name.constantize.new.render_in(context)]] + } + ) end - app.routes.draw {} + + app.routes.draw { } Rack::MockRequest.new(app) end def boot_app(env, root: __dir__, &configure) Rails.env = env - Class.new(Rails::Application) do - config.root = root - config.eager_load = env == "production" - config.enable_reloading = env == "development" - config.secret_key_base = "test" - config.logger = Logger.new(nil) - class_eval(&configure) if configure - end.tap(&:initialize!) + Class + .new(Rails::Application) do + config.root = root + config.eager_load = env == "production" + config.enable_reloading = env == "development" + config.secret_key_base = "test" + config.logger = Logger.new(nil) + class_eval(&configure) if configure + end + .tap(&:initialize!) end def write_file(root, path, content) diff --git a/test/sandbox/app/components/action_list_component.rb b/test/sandbox/app/components/action_list_component.rb index eeabca655..c0ac6fc44 100644 --- a/test/sandbox/app/components/action_list_component.rb +++ b/test/sandbox/app/components/action_list_component.rb @@ -5,11 +5,13 @@ class ActionListComponent < ViewComponent::Base renders_many :items, MenuItemComponent - erb_template <<~ERB -
    - <% items.each do |item| %> - <%= item %> - <% end %> -
- ERB + erb_template( + <<~ERB +
    + <% items.each do |item| %> + <%= item %> + <% end %> +
+ ERB + ) end diff --git a/test/sandbox/app/components/action_menu_component.rb b/test/sandbox/app/components/action_menu_component.rb index 5d90c88be..e91ea8e68 100644 --- a/test/sandbox/app/components/action_menu_component.rb +++ b/test/sandbox/app/components/action_menu_component.rb @@ -5,9 +5,11 @@ class ActionMenuComponent < ViewComponent::Base renders_one :list, ActionListComponent - erb_template <<~ERB -
- <%= list %> -
- ERB + erb_template( + <<~ERB +
+ <%= list %> +
+ ERB + ) end diff --git a/test/sandbox/app/components/action_menu_panel_wrapper_component.rb b/test/sandbox/app/components/action_menu_panel_wrapper_component.rb index a18d662ea..818ea8e97 100644 --- a/test/sandbox/app/components/action_menu_panel_wrapper_component.rb +++ b/test/sandbox/app/components/action_menu_panel_wrapper_component.rb @@ -2,6 +2,6 @@ class ActionMenuPanelWrapperComponent < ViewComponent::Base def call - render "shared/action_menu_panel" + render("shared/action_menu_panel") end end diff --git a/test/sandbox/app/components/cache_digest_namespace/parent_component.rb b/test/sandbox/app/components/cache_digest_namespace/parent_component.rb index f9955d488..cd34ce747 100644 --- a/test/sandbox/app/components/cache_digest_namespace/parent_component.rb +++ b/test/sandbox/app/components/cache_digest_namespace/parent_component.rb @@ -3,7 +3,7 @@ module CacheDigestNamespace class ParentComponent < ViewComponent::Base def call - render ChildComponent.new + render(ChildComponent.new) end end end diff --git a/test/sandbox/app/components/cacheable_call_component.rb b/test/sandbox/app/components/cacheable_call_component.rb index c96b354fb..c498c2808 100644 --- a/test/sandbox/app/components/cacheable_call_component.rb +++ b/test/sandbox/app/components/cacheable_call_component.rb @@ -3,6 +3,6 @@ # Renders a child component from a `call` method rather than a template. class CacheableCallComponent < ViewComponent::Base def call - render CacheableChildComponent.new + render(CacheableChildComponent.new) end end diff --git a/test/sandbox/app/components/cacheable_call_partial_component.rb b/test/sandbox/app/components/cacheable_call_partial_component.rb index bac3d7b83..08bbf7a5a 100644 --- a/test/sandbox/app/components/cacheable_call_partial_component.rb +++ b/test/sandbox/app/components/cacheable_call_partial_component.rb @@ -2,6 +2,6 @@ class CacheableCallPartialComponent < ViewComponent::Base def call - render "integration_examples/erb_partial" + render("integration_examples/erb_partial") end end diff --git a/test/sandbox/app/components/cacheable_dynamic_constant_component.rb b/test/sandbox/app/components/cacheable_dynamic_constant_component.rb index c2abfc505..9e039a99c 100644 --- a/test/sandbox/app/components/cacheable_dynamic_constant_component.rb +++ b/test/sandbox/app/components/cacheable_dynamic_constant_component.rb @@ -10,6 +10,6 @@ def initialize(component: CacheableChildComponent) end def call - render @component.new + render(@component.new) end end diff --git a/test/sandbox/app/components/cacheable_inline_partial_component.rb b/test/sandbox/app/components/cacheable_inline_partial_component.rb index 4ed0356c2..ec28a4ed3 100644 --- a/test/sandbox/app/components/cacheable_inline_partial_component.rb +++ b/test/sandbox/app/components/cacheable_inline_partial_component.rb @@ -1,7 +1,9 @@ # frozen_string_literal: true class CacheableInlinePartialComponent < ViewComponent::Base - erb_template <<~ERB -
<%= render "integration_examples/erb_partial" %>
- ERB + erb_template( + <<~ERB +
<%= render "integration_examples/erb_partial" %>
+ ERB + ) end diff --git a/test/sandbox/app/components/cacheable_inline_template_component.rb b/test/sandbox/app/components/cacheable_inline_template_component.rb index 5ae31be2b..ffc9edb00 100644 --- a/test/sandbox/app/components/cacheable_inline_template_component.rb +++ b/test/sandbox/app/components/cacheable_inline_template_component.rb @@ -2,7 +2,9 @@ # Renders a child component from an inline template rather than a sidecar file. class CacheableInlineTemplateComponent < ViewComponent::Base - erb_template <<~ERB -
<%= render CacheableChildComponent.new %>
- ERB + erb_template( + <<~ERB +
<%= render CacheableChildComponent.new %>
+ ERB + ) end diff --git a/test/sandbox/app/components/cacheable_plain_dependency_component.rb b/test/sandbox/app/components/cacheable_plain_dependency_component.rb index 32f5182fd..b5d96ab14 100644 --- a/test/sandbox/app/components/cacheable_plain_dependency_component.rb +++ b/test/sandbox/app/components/cacheable_plain_dependency_component.rb @@ -8,6 +8,6 @@ def initialize(component: ErbComponent) end def call - render @component.new(message: "plain") + render(@component.new(message: "plain")) end end diff --git a/test/sandbox/app/components/cacheable_raising_ruby_dependency_component.rb b/test/sandbox/app/components/cacheable_raising_ruby_dependency_component.rb index 4d9d6096b..0088d761a 100644 --- a/test/sandbox/app/components/cacheable_raising_ruby_dependency_component.rb +++ b/test/sandbox/app/components/cacheable_raising_ruby_dependency_component.rb @@ -2,6 +2,6 @@ class CacheableRaisingRubyDependencyComponent < ViewComponent::Base def call - render CacheDigestFixtures::RaisingRubyDependency.new + render(CacheDigestFixtures::RaisingRubyDependency.new) end end diff --git a/test/sandbox/app/components/cacheable_slot_class_name_component.rb b/test/sandbox/app/components/cacheable_slot_class_name_component.rb index 034c2e000..ad415ab44 100644 --- a/test/sandbox/app/components/cacheable_slot_class_name_component.rb +++ b/test/sandbox/app/components/cacheable_slot_class_name_component.rb @@ -6,7 +6,9 @@ class CacheableSlotClassNameComponent < ViewComponent::Base renders_one :header, "HTTPUntrackedComponent" renders_many :items, types: {child: "UntrackedChildComponent"} - erb_template <<~ERB -
<%= header %><% items.each do |item| %><%= item %><% end %>
- ERB + erb_template( + <<~ERB +
<%= header %><% items.each do |item| %><%= item %><% end %>
+ ERB + ) end diff --git a/test/sandbox/app/components/container_component.rb b/test/sandbox/app/components/container_component.rb index f06f9428d..13f2dc7d7 100644 --- a/test/sandbox/app/components/container_component.rb +++ b/test/sandbox/app/components/container_component.rb @@ -2,6 +2,6 @@ class ContainerComponent < ViewComponent::Base def call - render HelpersProxyComponent.new + render(HelpersProxyComponent.new) end end diff --git a/test/sandbox/app/components/content_eval_component.rb b/test/sandbox/app/components/content_eval_component.rb index 77e0ba220..38491fcee 100644 --- a/test/sandbox/app/components/content_eval_component.rb +++ b/test/sandbox/app/components/content_eval_component.rb @@ -2,7 +2,8 @@ class ContentEvalComponent < ViewComponent::Base def call - content # evaluate content - content_tag :h1, "content!" + # evaluate content + content + content_tag(:h1, "content!") end end diff --git a/test/sandbox/app/components/controller_inline_with_block_component.rb b/test/sandbox/app/components/controller_inline_with_block_component.rb index 176eb1f49..7d2af75c3 100644 --- a/test/sandbox/app/components/controller_inline_with_block_component.rb +++ b/test/sandbox/app/components/controller_inline_with_block_component.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true class ControllerInlineWithBlockComponent < ViewComponent::Base - renders_one :slot, ->(name:) { tag.div name, id: "slot" } + renders_one :slot, -> (name:) { tag.div name, id: "slot" } def initialize(message:) @message = message diff --git a/test/sandbox/app/components/deep_navigation_wrapper_component.rb b/test/sandbox/app/components/deep_navigation_wrapper_component.rb index cf69fbd99..7dbfb20f7 100644 --- a/test/sandbox/app/components/deep_navigation_wrapper_component.rb +++ b/test/sandbox/app/components/deep_navigation_wrapper_component.rb @@ -2,6 +2,6 @@ class DeepNavigationWrapperComponent < ViewComponent::Base def call - render "shared/deep_navigation" + render("shared/deep_navigation") end end diff --git a/test/sandbox/app/components/default_form_builder_component.rb b/test/sandbox/app/components/default_form_builder_component.rb index d23d005a9..950adc20f 100644 --- a/test/sandbox/app/components/default_form_builder_component.rb +++ b/test/sandbox/app/components/default_form_builder_component.rb @@ -1,3 +1,4 @@ # frozen_string_literal: true -class DefaultFormBuilderComponent < ViewComponent::Base; end +class DefaultFormBuilderComponent < ViewComponent::Base +end diff --git a/test/sandbox/app/components/inline_component.rb b/test/sandbox/app/components/inline_component.rb index 4044137d9..2cb9e2bc4 100644 --- a/test/sandbox/app/components/inline_component.rb +++ b/test/sandbox/app/components/inline_component.rb @@ -2,10 +2,10 @@ class InlineComponent < ViewComponent::Base def call - text_field_tag :name + text_field_tag(:name) end def call_email - text_field_tag :email + text_field_tag(:email) end end diff --git a/test/sandbox/app/components/inline_trailing_whitespace_component.rb b/test/sandbox/app/components/inline_trailing_whitespace_component.rb index 1814985aa..a03f18a8c 100644 --- a/test/sandbox/app/components/inline_trailing_whitespace_component.rb +++ b/test/sandbox/app/components/inline_trailing_whitespace_component.rb @@ -3,8 +3,10 @@ class InlineTrailingWhitespaceComponent < ViewComponent::Base strip_trailing_whitespace - erb_template <<~ERB + erb_template( + <<~ERB -

Template does not contain any trailing whitespace

- ERB +

Template does not contain any trailing whitespace

+ ERB + ) end diff --git a/test/sandbox/app/components/inline_variant_component.rb b/test/sandbox/app/components/inline_variant_component.rb index 6794f2e1d..6ecfab86b 100644 --- a/test/sandbox/app/components/inline_variant_component.rb +++ b/test/sandbox/app/components/inline_variant_component.rb @@ -5,6 +5,6 @@ def call end def call_inline_variant - text_field_tag :inline_variant + text_field_tag(:inline_variant) end end diff --git a/test/sandbox/app/components/item_component.rb b/test/sandbox/app/components/item_component.rb index 6794ea7c9..5665708b1 100644 --- a/test/sandbox/app/components/item_component.rb +++ b/test/sandbox/app/components/item_component.rb @@ -5,7 +5,9 @@ class ItemComponent < ViewComponent::Base option :item - erb_template <<~ERB - <%= item.name %> - ERB + erb_template( + <<~ERB + <%= item.name %> + ERB + ) end diff --git a/test/sandbox/app/components/lambda_slot_component.rb b/test/sandbox/app/components/lambda_slot_component.rb index 5eae74cc0..71af46e8c 100644 --- a/test/sandbox/app/components/lambda_slot_component.rb +++ b/test/sandbox/app/components/lambda_slot_component.rb @@ -1,7 +1,10 @@ # frozen_string_literal: true class LambdaSlotComponent < ViewComponent::Base - renders_one :header, ->(classes:, &block) do - content_tag :h1, class: classes, &block - end + renders_one( + :header, + -> (classes:, &block) do + content_tag :h1, class: classes, &block + end + ) end diff --git a/test/sandbox/app/components/lambda_slot_inner_component.rb b/test/sandbox/app/components/lambda_slot_inner_component.rb index 69e1b929f..94df0a727 100644 --- a/test/sandbox/app/components/lambda_slot_inner_component.rb +++ b/test/sandbox/app/components/lambda_slot_inner_component.rb @@ -1,13 +1,18 @@ # frozen_string_literal: true class LambdaSlotInnerComponent < ViewComponent::Base - renders_one :aside, ->(&block) do - content_tag :div, class: "lambda-slot-aside", &block - end + renders_one( + :aside, + -> (&block) do + content_tag :div, class: "lambda-slot-aside", &block + end + ) - erb_template <<~ERB -
- <%= aside %> -
- ERB + erb_template( + <<~ERB +
+ <%= aside %> +
+ ERB + ) end diff --git a/test/sandbox/app/components/lambda_slot_outer_component.rb b/test/sandbox/app/components/lambda_slot_outer_component.rb index 5fe396337..e6046d0dc 100644 --- a/test/sandbox/app/components/lambda_slot_outer_component.rb +++ b/test/sandbox/app/components/lambda_slot_outer_component.rb @@ -3,9 +3,11 @@ class LambdaSlotOuterComponent < ViewComponent::Base renders_one :inner, LambdaSlotInnerComponent - erb_template <<~ERB -
- <%= inner %> -
- ERB + erb_template( + <<~ERB +
+ <%= inner %> +
+ ERB + ) end diff --git a/test/sandbox/app/components/lambda_slot_passthrough_component.rb b/test/sandbox/app/components/lambda_slot_passthrough_component.rb index e17acbc98..c555e51e3 100644 --- a/test/sandbox/app/components/lambda_slot_passthrough_component.rb +++ b/test/sandbox/app/components/lambda_slot_passthrough_component.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true class LambdaSlotPassthroughComponent < ViewComponent::Base - renders_one :lambda_slot, ->(&block) { self.class.new(&block) } + renders_one :lambda_slot, -> (&block) { self.class.new(&block) } end diff --git a/test/sandbox/app/components/lambda_slot_translation_wrapper_component.rb b/test/sandbox/app/components/lambda_slot_translation_wrapper_component.rb index a01a641a5..abb3ca516 100644 --- a/test/sandbox/app/components/lambda_slot_translation_wrapper_component.rb +++ b/test/sandbox/app/components/lambda_slot_translation_wrapper_component.rb @@ -2,6 +2,6 @@ class LambdaSlotTranslationWrapperComponent < ViewComponent::Base def call - render "shared/lambda_slot_translation" + render("shared/lambda_slot_translation") end end diff --git a/test/sandbox/app/components/menu_item_component.rb b/test/sandbox/app/components/menu_item_component.rb index 49481b0b9..e7fa16cb4 100644 --- a/test/sandbox/app/components/menu_item_component.rb +++ b/test/sandbox/app/components/menu_item_component.rb @@ -3,9 +3,11 @@ # Simplified MenuItem component inspired by Primer::Alpha::ActionList::Item # Used to test deeply nested translation scoping class MenuItemComponent < ViewComponent::Base - erb_template <<~ERB - - ERB + erb_template( + <<~ERB + + ERB + ) end diff --git a/test/sandbox/app/components/nav_component.rb b/test/sandbox/app/components/nav_component.rb index 0ae50bd89..876801f27 100644 --- a/test/sandbox/app/components/nav_component.rb +++ b/test/sandbox/app/components/nav_component.rb @@ -4,9 +4,11 @@ class NavComponent < ViewComponent::Base renders_one :action_menu, ActionMenuComponent - erb_template <<~ERB - - ERB + erb_template( + <<~ERB + + ERB + ) end diff --git a/test/sandbox/app/components/nested_shared_state/table_component.rb b/test/sandbox/app/components/nested_shared_state/table_component.rb index 7117ad2af..b85775541 100644 --- a/test/sandbox/app/components/nested_shared_state/table_component.rb +++ b/test/sandbox/app/components/nested_shared_state/table_component.rb @@ -2,15 +2,18 @@ module NestedSharedState class TableComponent < ViewComponent::Base - renders_one :header, ->(arg = nil, **system_arguments, &block) do - header_system_arguments = system_arguments - header_system_arguments[:selectable] = @selectable + renders_one( + :header, + -> (arg = nil, **system_arguments, &block) do + header_system_arguments = system_arguments + header_system_arguments[:selectable] = @selectable - header_system_arguments[:data] ||= {} - header_system_arguments[:data][:argument] = arg if arg.present? + header_system_arguments[:data] ||= {} + header_system_arguments[:data][:argument] = arg if arg.present? - NestedSharedState::HeaderComponent.new(**header_system_arguments) - end + NestedSharedState::HeaderComponent.new(**header_system_arguments) + end + ) def initialize(selectable: false) @selectable = selectable diff --git a/test/sandbox/app/components/polymorphic_content_slot_component.rb b/test/sandbox/app/components/polymorphic_content_slot_component.rb index 9829636e0..94775429e 100644 --- a/test/sandbox/app/components/polymorphic_content_slot_component.rb +++ b/test/sandbox/app/components/polymorphic_content_slot_component.rb @@ -1,13 +1,16 @@ # frozen_string_literal: true class PolymorphicContentSlotComponent < ViewComponent::Base - renders_one :leading_visual, types: { - icon: lambda { |title| - content_tag("h1") do - title - end + renders_one( + :leading_visual, + types: { + icon: lambda { |title| + content_tag("h1") do + title + end + } } - } + ) def before_render content diff --git a/test/sandbox/app/components/polymorphic_slot_component.rb b/test/sandbox/app/components/polymorphic_slot_component.rb index bbe15ef28..225da37ea 100644 --- a/test/sandbox/app/components/polymorphic_slot_component.rb +++ b/test/sandbox/app/components/polymorphic_slot_component.rb @@ -1,35 +1,44 @@ # frozen_string_literal: true class PolymorphicSlotComponent < ViewComponent::Base - renders_many :fields, types: { - foo: {renders: "FooItem", as: :foo_field}, - bar: { - renders: lambda { |class_names: "", **_system_arguments| - classes = (class_names.split(" ") + ["bar"]).join(" ") - content_tag(:div, class: classes) do - "bar item" - end - }, + renders_many( + :fields, + types: { + foo: {renders: "FooItem", as: :foo_field}, + bar: { + renders: lambda { |class_names: "", **_system_arguments| + classes = (class_names.split(" ") + ["bar"]).join(" ") + content_tag(:div, class: classes) do + "bar item" + end + }, - as: :bar_field + as: :bar_field + } } - } + ) - renders_one :header, types: { - standard: lambda { |&block| content_tag(:div, class: "standard", &block) }, - special: lambda { |&block| content_tag(:div, class: "special", &block) } - } + renders_one( + :header, + types: { + standard: lambda { |&block| content_tag(:div, class: "standard", &block) }, + special: lambda { |&block| content_tag(:div, class: "special", &block) } + } + ) - renders_many :items, types: { - passthrough: "PassthroughItem", - foo: "FooItem", - bar: lambda { |class_names: "", **_system_arguments| - classes = (class_names.split(" ") + ["bar"]).join(" ") - content_tag(:div, class: classes) do - "bar item" - end + renders_many( + :items, + types: { + passthrough: "PassthroughItem", + foo: "FooItem", + bar: lambda { |class_names: "", **_system_arguments| + classes = (class_names.split(" ") + ["bar"]).join(" ") + content_tag(:div, class: classes) do + "bar item" + end + } } - } + ) class PassthroughItem < ViewComponent::Base def call diff --git a/test/sandbox/app/components/section_component.rb b/test/sandbox/app/components/section_component.rb index efb76274e..457a01724 100644 --- a/test/sandbox/app/components/section_component.rb +++ b/test/sandbox/app/components/section_component.rb @@ -4,9 +4,11 @@ class SectionComponent < ViewComponent::Base renders_one :nav, NavComponent - erb_template <<~ERB -
- <%= nav %> -
- ERB + erb_template( + <<~ERB +
+ <%= nav %> +
+ ERB + ) end diff --git a/test/sandbox/app/components/serializable_component.rb b/test/sandbox/app/components/serializable_component.rb index 403a70187..4eb35cd6d 100644 --- a/test/sandbox/app/components/serializable_component.rb +++ b/test/sandbox/app/components/serializable_component.rb @@ -28,14 +28,16 @@ def initialize(title, count: 0) @count = count end - erb_template <<~ERB -
-

<%= @title %>

- <%= @count %> - <%= header %> - <% items.each do |item| %> -
<%= item %>
- <% end %> -
- ERB + erb_template( + <<~ERB +
+

<%= @title %>

+ <%= @count %> + <%= header %> + <% items.each do |item| %> +
<%= item %>
+ <% end %> +
+ ERB + ) end diff --git a/test/sandbox/app/components/sleep_component.rb b/test/sandbox/app/components/sleep_component.rb index acde6e989..af9f9f52f 100644 --- a/test/sandbox/app/components/sleep_component.rb +++ b/test/sandbox/app/components/sleep_component.rb @@ -6,7 +6,7 @@ def initialize(seconds:) end def call - sleep @seconds + sleep(@seconds) "sleep!" end end diff --git a/test/sandbox/app/components/slot_partial_helper_component.rb b/test/sandbox/app/components/slot_partial_helper_component.rb index 57da0bb63..35c6efd9d 100644 --- a/test/sandbox/app/components/slot_partial_helper_component.rb +++ b/test/sandbox/app/components/slot_partial_helper_component.rb @@ -4,11 +4,13 @@ class SlotPartialHelperComponent < ViewComponent::Base renders_one :header, PartialHelperComponent def call - content_tag :h1 do - safe_join([ - helpers.expensive_message, - header.to_s - ]) + content_tag(:h1) do + safe_join( + [ + helpers.expensive_message, + header.to_s + ] + ) end end end diff --git a/test/sandbox/app/components/slotable_default_component.rb b/test/sandbox/app/components/slotable_default_component.rb index c32660d91..130845434 100644 --- a/test/sandbox/app/components/slotable_default_component.rb +++ b/test/sandbox/app/components/slotable_default_component.rb @@ -1,7 +1,9 @@ class SlotableDefaultComponent < ViewComponent::Base - erb_template <<~ERB -

<%= header %>

- ERB + erb_template( + <<~ERB +

<%= header %>

+ ERB + ) renders_one :header diff --git a/test/sandbox/app/components/slotable_default_instance_component.rb b/test/sandbox/app/components/slotable_default_instance_component.rb index 012016eec..7b56a4bc3 100644 --- a/test/sandbox/app/components/slotable_default_instance_component.rb +++ b/test/sandbox/app/components/slotable_default_instance_component.rb @@ -1,7 +1,9 @@ class SlotableDefaultInstanceComponent < ViewComponent::Base - erb_template <<~ERB -

<%= header %>

- ERB + erb_template( + <<~ERB +

<%= header %>

+ ERB + ) renders_one :header diff --git a/test/sandbox/app/components/slots_component.rb b/test/sandbox/app/components/slots_component.rb index beb5fec93..6a3babe3f 100644 --- a/test/sandbox/app/components/slots_component.rb +++ b/test/sandbox/app/components/slots_component.rb @@ -3,19 +3,25 @@ class SlotsComponent < ViewComponent::Base renders_one :title renders_one :subtitle - renders_one :footer, ->(classes: "", &block) do - content_tag :footer, class: "footer #{classes}" do - block.call if block + renders_one( + :footer, + -> (classes: "", &block) do + content_tag :footer, class: "footer #{classes}" do + block.call if block + end end - end + ) renders_many :posts, PostComponent renders_many :tabs - renders_many :items, ->(highlighted: false) do - MyHighlightComponent.new(highlighted: highlighted) - end + renders_many( + :items, + -> (highlighted: false) do + MyHighlightComponent.new(highlighted: highlighted) + end + ) renders_one :extra, "ExtraComponent" def initialize(classes: "") diff --git a/test/sandbox/app/components/slots_render_predicate_component.rb b/test/sandbox/app/components/slots_render_predicate_component.rb index 46721c914..75492a6bb 100644 --- a/test/sandbox/app/components/slots_render_predicate_component.rb +++ b/test/sandbox/app/components/slots_render_predicate_component.rb @@ -8,14 +8,14 @@ def render? end def call - content_tag :div do + content_tag(:div) do title.to_s end end class PredicateTitleComponent < ViewComponent::Base def call - content_tag :h1, content + content_tag(:h1, content) end end end diff --git a/test/sandbox/app/components/slots_with_empty_lambda_component.rb b/test/sandbox/app/components/slots_with_empty_lambda_component.rb index 129a557b3..92c983e7e 100644 --- a/test/sandbox/app/components/slots_with_empty_lambda_component.rb +++ b/test/sandbox/app/components/slots_with_empty_lambda_component.rb @@ -1,10 +1,13 @@ # frozen_string_literal: true class SlotsWithEmptyLambdaComponent < ViewComponent::Base - renders_many :items, -> do - @item_count += 1 - Item.new("Title #{@item_count}") - end + renders_many( + :items, + -> do + @item_count += 1 + Item.new("Title #{@item_count}") + end + ) def initialize @item_count = 0 diff --git a/test/sandbox/app/components/slots_without_content_block_component.rb b/test/sandbox/app/components/slots_without_content_block_component.rb index 1a33ebd0f..79b46f61a 100644 --- a/test/sandbox/app/components/slots_without_content_block_component.rb +++ b/test/sandbox/app/components/slots_without_content_block_component.rb @@ -9,7 +9,7 @@ def initialize(title) end def call - content_tag :h1, @title + content_tag(:h1, @title) end end end diff --git a/test/sandbox/app/controllers/integration_examples_controller.rb b/test/sandbox/app/controllers/integration_examples_controller.rb index 125fa43ed..968cc9bc9 100644 --- a/test/sandbox/app/controllers/integration_examples_controller.rb +++ b/test/sandbox/app/controllers/integration_examples_controller.rb @@ -12,10 +12,12 @@ def controller_inline end def controller_inline_with_block - render(ControllerInlineWithBlockComponent.new(message: "bar").tap do |c| - c.with_slot(name: "baz") - c.with_content("bam") - end) + render( + ControllerInlineWithBlockComponent.new(message: "bar").tap do |c| + c.with_slot(name: "baz") + c.with_content("bam") + end + ) end def controller_inline_baseline @@ -73,6 +75,6 @@ def multiple_formats_component end def turbo_stream - respond_to { |format| format.turbo_stream { render TurboStreamComponent.new } } + respond_to { |format| format.turbo_stream { render(TurboStreamComponent.new) } } end end diff --git a/test/sandbox/app/controllers/my_preview_controller.rb b/test/sandbox/app/controllers/my_preview_controller.rb index 4bd0d028c..8ba85a9c9 100644 --- a/test/sandbox/app/controllers/my_preview_controller.rb +++ b/test/sandbox/app/controllers/my_preview_controller.rb @@ -2,6 +2,6 @@ class MyPreviewController < ViewComponentsController def index - render plain: "Custom controller" + render(plain: "Custom controller") end end diff --git a/test/sandbox/app/helpers/cacheable_child_helper.rb b/test/sandbox/app/helpers/cacheable_child_helper.rb index 356bef163..29662961c 100644 --- a/test/sandbox/app/helpers/cacheable_child_helper.rb +++ b/test/sandbox/app/helpers/cacheable_child_helper.rb @@ -3,6 +3,6 @@ # A helper that renders a component, for components to include. module CacheableChildHelper def cacheable_child - render CacheableChildComponent.new + render(CacheableChildComponent.new) end end diff --git a/test/sandbox/config/application.rb b/test/sandbox/config/application.rb index d01622174..a0d657264 100644 --- a/test/sandbox/config/application.rb +++ b/test/sandbox/config/application.rb @@ -3,7 +3,9 @@ require File.expand_path("boot", __dir__) require "active_model/railtie" -require "action_cable/engine" # Remove when hotwired/turbo-rails#74 is resolved + +# Remove when hotwired/turbo-rails#74 is resolved +require "action_cable/engine" require "action_controller/railtie" require "action_mailer/railtie" require "action_view/railtie" diff --git a/test/sandbox/config/boot.rb b/test/sandbox/config/boot.rb index b17aa7433..a2539dbdf 100644 --- a/test/sandbox/config/boot.rb +++ b/test/sandbox/config/boot.rb @@ -2,4 +2,4 @@ require "rubygems" -$:.unshift File.expand_path("../../../../../../lib", __FILE__) +$:.unshift(File.expand_path("../../../../../../lib", __FILE__)) diff --git a/test/sandbox/config/environment.rb b/test/sandbox/config/environment.rb index ab70f8137..ba0bce750 100644 --- a/test/sandbox/config/environment.rb +++ b/test/sandbox/config/environment.rb @@ -1,4 +1,5 @@ # frozen_string_literal: true require File.expand_path("../application", __FILE__) + Sandbox::Application.initialize! diff --git a/test/sandbox/config/initializers/zzz_complete_initialization.rb b/test/sandbox/config/initializers/zzz_complete_initialization.rb index 0e29db199..61c6176a6 100644 --- a/test/sandbox/config/initializers/zzz_complete_initialization.rb +++ b/test/sandbox/config/initializers/zzz_complete_initialization.rb @@ -3,7 +3,7 @@ # FRAMEWORK_LOAD_POINTS ought to be empty - we shouldn't have # autoloaded ActionView::Base during initialization, for example. FRAMEWORK_LOAD_POINTS.each do |framework, caller| - warn "#{framework} loaded too soon, from:" - warn caller - exit 1 + warn("#{framework} loaded too soon, from:") + warn(caller) + exit(1) end diff --git a/test/sandbox/config/routes.rb b/test/sandbox/config/routes.rb index 2c6ed95bc..e076f4c69 100644 --- a/test/sandbox/config/routes.rb +++ b/test/sandbox/config/routes.rb @@ -1,52 +1,53 @@ # frozen_string_literal: true Sandbox::Application.routes.draw do - root to: "integration_examples#index" - get :slots, to: "integration_examples#slots" - get :empty_slot, to: "integration_examples#empty_slot" - get :partial, to: "integration_examples#partial" - get :content, to: "integration_examples#content" - get :variants, to: "integration_examples#variants" - get :products, to: "integration_examples#products" - get "products/:id", to: "integration_examples#products" - get :inline_products, to: "integration_examples#inline_products" - get :cached, to: "integration_examples#cached" - get :render_check, to: "integration_examples#render_check" - get :controller_inline, to: "integration_examples#controller_inline" - get :controller_inline_with_block, to: "integration_examples#controller_inline_with_block" - get :controller_inline_baseline, to: "integration_examples#controller_inline_baseline" - get :controller_to_string, to: "integration_examples#controller_to_string" - get :controller_inline_baseline_with_layout, to: "integration_examples#controller_inline_baseline_with_layout" - get :controller_to_string_with_layout, to: "integration_examples#controller_to_string_with_layout" - get :layout_default, to: "layouts#default" - get :layout_global_for_action, to: "layouts#global_for_action" - get :layout_explicit_in_action, to: "layouts#explicit_in_action" - get :layout_disabled_in_action, to: "layouts#disabled_in_action" - get :layout_with_content_for, to: "layouts#with_content_for" - get :nested_haml, to: "integration_examples#nested_haml" - get :link_to_helper, to: "integration_examples#link_to_helper" - get :cached_capture, to: "integration_examples#cached_capture" - get :cached_partial, to: "integration_examples#cached_partial" - get :cached_component, to: "integration_examples#cached_component" - get :cached_nested_component, to: "integration_examples#cached_nested_component" - get :cached_untracked_component, to: "integration_examples#cached_untracked_component" - get :cache_block_component, to: "integration_examples#cache_block_component" - get :inherited_sidecar, to: "integration_examples#inherited_sidecar" - get :inherited_from_uncompilable_component, to: "integration_examples#inherited_from_uncompilable_component" - get :unsafe_component, to: "integration_examples#unsafe_component" - get :unsafe_preamble_component, to: "integration_examples#unsafe_preamble_component" - get :unsafe_postamble_component, to: "integration_examples#unsafe_postamble_component" - get :multiple_formats_component, to: "integration_examples#multiple_formats_component" - get :slotable_default_override, to: "integration_examples#slotable_default_override" - get :virtual_path_reset, to: "integration_examples#virtual_path_reset" - post :create, to: "integration_examples#create" - get :translations_in_block, to: "integration_examples#translations_in_block" + root(to: "integration_examples#index") + get(:slots, to: "integration_examples#slots") + get(:empty_slot, to: "integration_examples#empty_slot") + get(:partial, to: "integration_examples#partial") + get(:content, to: "integration_examples#content") + get(:variants, to: "integration_examples#variants") + get(:products, to: "integration_examples#products") + get("products/:id", to: "integration_examples#products") + get(:inline_products, to: "integration_examples#inline_products") + get(:cached, to: "integration_examples#cached") + get(:render_check, to: "integration_examples#render_check") + get(:controller_inline, to: "integration_examples#controller_inline") + get(:controller_inline_with_block, to: "integration_examples#controller_inline_with_block") + get(:controller_inline_baseline, to: "integration_examples#controller_inline_baseline") + get(:controller_to_string, to: "integration_examples#controller_to_string") + get(:controller_inline_baseline_with_layout, to: "integration_examples#controller_inline_baseline_with_layout") + get(:controller_to_string_with_layout, to: "integration_examples#controller_to_string_with_layout") + get(:layout_default, to: "layouts#default") + get(:layout_global_for_action, to: "layouts#global_for_action") + get(:layout_explicit_in_action, to: "layouts#explicit_in_action") + get(:layout_disabled_in_action, to: "layouts#disabled_in_action") + get(:layout_with_content_for, to: "layouts#with_content_for") + get(:nested_haml, to: "integration_examples#nested_haml") + get(:link_to_helper, to: "integration_examples#link_to_helper") + get(:cached_capture, to: "integration_examples#cached_capture") + get(:cached_partial, to: "integration_examples#cached_partial") + get(:cached_component, to: "integration_examples#cached_component") + get(:cached_nested_component, to: "integration_examples#cached_nested_component") + get(:cached_untracked_component, to: "integration_examples#cached_untracked_component") + get(:cache_block_component, to: "integration_examples#cache_block_component") + get(:inherited_sidecar, to: "integration_examples#inherited_sidecar") + get(:inherited_from_uncompilable_component, to: "integration_examples#inherited_from_uncompilable_component") + get(:unsafe_component, to: "integration_examples#unsafe_component") + get(:unsafe_preamble_component, to: "integration_examples#unsafe_preamble_component") + get(:unsafe_postamble_component, to: "integration_examples#unsafe_postamble_component") + get(:multiple_formats_component, to: "integration_examples#multiple_formats_component") + get(:slotable_default_override, to: "integration_examples#slotable_default_override") + get(:virtual_path_reset, to: "integration_examples#virtual_path_reset") + post(:create, to: "integration_examples#create") + get(:translations_in_block, to: "integration_examples#translations_in_block") - resources :posts + resources(:posts) constraints(lambda { |request| request.env["warden"].authenticate! }) do - get :constraints_with_env, to: "integration_examples#index" + get(:constraints_with_env, to: "integration_examples#index") end - get :helpers_proxy_component, to: "integration_examples#helpers_proxy_component" - get :turbo_stream, to: "integration_examples#turbo_stream" + + get(:helpers_proxy_component, to: "integration_examples#helpers_proxy_component") + get(:turbo_stream, to: "integration_examples#turbo_stream") end diff --git a/test/sandbox/test/base_test.rb b/test/sandbox/test/base_test.rb index c1f802541..f59077bf7 100644 --- a/test/sandbox/test/base_test.rb +++ b/test/sandbox/test/base_test.rb @@ -33,6 +33,7 @@ def skip_templates_parses_all_types_of_paths else assert_equal(template[:variant], expected[index][:variant]) end + assert_equal(template[:handler], expected[index][:handler]) end end @@ -40,21 +41,20 @@ def skip_templates_parses_all_types_of_paths def test_calling_helpers_outside_render_raises component = ViewComponent::Base.new - err = - assert_raises ViewComponent::HelpersCalledBeforeRenderError do - component.helpers - end - assert_includes err.message, "can't be used before rendering" + err = assert_raises(ViewComponent::HelpersCalledBeforeRenderError) do + component.helpers + end + + assert_includes(err.message, "can't be used before rendering") end def test_calling_controller_outside_render_raises component = ViewComponent::Base.new - err = - assert_raises ViewComponent::ControllerCalledBeforeRenderError do - component.controller - end + err = assert_raises(ViewComponent::ControllerCalledBeforeRenderError) do + component.controller + end - assert_includes err.message, "can't be used before rendering" + assert_includes(err.message, "can't be used before rendering") end def test_sidecar_files @@ -64,7 +64,7 @@ def test_sidecar_files [ "#{root}/app/components/template_and_sidecar_directory_template_component.html.erb", "#{root}/app/components/template_and_sidecar_directory_template_component/" \ - "template_and_sidecar_directory_template_component.html.erb" + "template_and_sidecar_directory_template_component.html.erb" ], TemplateAndSidecarDirectoryTemplateComponent.sidecar_files(["erb"]) ) @@ -96,14 +96,14 @@ def test_sidecar_files_are_looked_up_once_while_eager_loading template = File.join(directory, "temporary_component.html.erb") ViewComponent::CompileCache.with_sidecar_files_cache do - assert_empty component.__vc_sidecar_files(["erb"]) + assert_empty(component.__vc_sidecar_files(["erb"])) File.write(template, "
") - assert_empty component.__vc_sidecar_files(["erb"]) - assert_empty component.sidecar_files(["erb"]) + assert_empty(component.__vc_sidecar_files(["erb"])) + assert_empty(component.sidecar_files(["erb"])) end - assert_equal [template], component.__vc_sidecar_files(["erb"]) + assert_equal([template], component.__vc_sidecar_files(["erb"])) end end @@ -118,7 +118,7 @@ def test_cached_sidecar_directory_listings_preserve_file_discovery expected = components.map { |component| component.sidecar_files(extensions) } ViewComponent::CompileCache.with_sidecar_files_cache do - assert_equal expected, components.map { |component| component.__vc_sidecar_files(extensions) } + assert_equal(expected, components.map { |component| component.__vc_sidecar_files(extensions) }) end end @@ -127,6 +127,7 @@ def test_sidecar_directory_listings_are_shared_across_components_and_extensions paths = %w[first_component.html.erb first_component.yml second_component.html+phone.erb].map do |name| File.join(directory, name).tap { |path| File.write(path, "") } end + scans = 0 glob = Dir.method(:glob) @@ -137,9 +138,15 @@ def test_sidecar_directory_listings_are_shared_across_components_and_extensions Dir.stub(:glob, scan) do ViewComponent::CompileCache.with_sidecar_files_cache do - assert_equal paths.first(2).sort, ViewComponent::CompileCache.sidecar_files_matching("#{directory}/first_component.*") - assert_equal [paths.last], ViewComponent::CompileCache.sidecar_files_matching("#{directory}/second_component.*") - assert_equal 1, scans + assert_equal( + paths.first(2).sort, + ViewComponent::CompileCache.sidecar_files_matching("#{directory}/first_component.*") + ) + assert_equal( + [paths.last], + ViewComponent::CompileCache.sidecar_files_matching("#{directory}/second_component.*") + ) + assert_equal(1, scans) end end end @@ -150,16 +157,16 @@ def test_sidecar_directory_listings_are_discarded_after_an_error pattern = "#{directory}/temporary_component.*" assert_raises(RuntimeError) do ViewComponent::CompileCache.with_sidecar_files_cache do - assert_empty ViewComponent::CompileCache.sidecar_files_matching(pattern) + assert_empty(ViewComponent::CompileCache.sidecar_files_matching(pattern)) raise "compilation failed" end end template = File.join(directory, "temporary_component.html.erb") File.write(template, "") - assert_equal [template], ViewComponent::CompileCache.sidecar_files_matching(pattern) + assert_equal([template], ViewComponent::CompileCache.sidecar_files_matching(pattern)) ViewComponent::CompileCache.with_sidecar_files_cache do - assert_equal [template], ViewComponent::CompileCache.sidecar_files_matching(pattern) + assert_equal([template], ViewComponent::CompileCache.sidecar_files_matching(pattern)) end end end @@ -169,12 +176,21 @@ def test_cached_sidecar_directory_listings_preserve_glob_matching %w[example.html.erb example.part.html.erb example_other.html.erb .example.html.erb].each do |name| File.write(File.join(directory, name), "") end - patterns = %w[example.* example.part.* example_other.* .example.* example{,_other}.* missing.* subdirectory/example.*] + + patterns = %w[ + example.* + example.part.* + example_other.* + .example.* + example{,_other}.* + missing.* + subdirectory/example.* + ] .map { |name| File.join(directory, name) } expected = patterns.map { |pattern| Dir[pattern] } ViewComponent::CompileCache.with_sidecar_files_cache do - assert_equal expected, patterns.map { |pattern| ViewComponent::CompileCache.sidecar_files_matching(pattern) } + assert_equal(expected, patterns.map { |pattern| ViewComponent::CompileCache.sidecar_files_matching(pattern) }) end end end @@ -188,15 +204,15 @@ def test_source_file_contents_are_shared_only_while_eager_loading ViewComponent::CompileCache.read_file(path).replace("modified by a template handler") File.write(path, "edited") - assert_equal "original", ViewComponent::CompileCache.read_file(path) + assert_equal("original", ViewComponent::CompileCache.read_file(path)) end - assert_equal "edited", ViewComponent::CompileCache.read_file(path) + assert_equal("edited", ViewComponent::CompileCache.read_file(path)) File.write(path, "edited again") - assert_equal "edited again", ViewComponent::CompileCache.read_file(path) + assert_equal("edited again", ViewComponent::CompileCache.read_file(path)) ViewComponent::CompileCache.with_sidecar_files_cache do - assert_equal "edited again", ViewComponent::CompileCache.read_file(path) + assert_equal("edited again", ViewComponent::CompileCache.read_file(path)) end end end @@ -208,13 +224,13 @@ def test_source_file_contents_are_discarded_after_an_error assert_raises(RuntimeError) do ViewComponent::CompileCache.with_sidecar_files_cache do - assert_equal "original", ViewComponent::CompileCache.read_file(path) + assert_equal("original", ViewComponent::CompileCache.read_file(path)) raise "compilation failed" end end File.write(path, "edited") - assert_equal "edited", ViewComponent::CompileCache.read_file(path) + assert_equal("edited", ViewComponent::CompileCache.read_file(path)) end end @@ -225,25 +241,26 @@ def test_nested_file_caches_preserve_the_outer_cache ViewComponent::CompileCache.with_sidecar_files_cache do parser = ViewComponent::CompileCache.path_parser - assert_equal "original", ViewComponent::CompileCache.read_file(path) + assert_equal("original", ViewComponent::CompileCache.read_file(path)) ViewComponent::CompileCache.with_sidecar_files_cache do - assert_same parser, ViewComponent::CompileCache.path_parser + assert_same(parser, ViewComponent::CompileCache.path_parser) File.write(path, "edited") - assert_equal "original", ViewComponent::CompileCache.read_file(path) + assert_equal("original", ViewComponent::CompileCache.read_file(path)) end - assert_same parser, ViewComponent::CompileCache.path_parser - assert_equal "original", ViewComponent::CompileCache.read_file(path) + assert_same(parser, ViewComponent::CompileCache.path_parser) + assert_equal("original", ViewComponent::CompileCache.read_file(path)) assert_raises(RuntimeError) do ViewComponent::CompileCache.with_sidecar_files_cache { raise "nested failure" } end - assert_same parser, ViewComponent::CompileCache.path_parser - assert_equal "original", ViewComponent::CompileCache.read_file(path) + + assert_same(parser, ViewComponent::CompileCache.path_parser) + assert_equal("original", ViewComponent::CompileCache.read_file(path)) end - assert_equal "edited", ViewComponent::CompileCache.read_file(path) + assert_equal("edited", ViewComponent::CompileCache.read_file(path)) end end @@ -251,13 +268,13 @@ def test_template_path_parser_is_shared_only_while_eager_loading parser = nil ViewComponent::CompileCache.with_sidecar_files_cache do parser = ViewComponent::CompileCache.path_parser - assert_same parser, ViewComponent::CompileCache.path_parser + assert_same(parser, ViewComponent::CompileCache.path_parser) details = parser.parse("example.en.html+phone.erb").details - assert_equal [:en, :html, :phone, :erb], [details.locale, details.format, details.variant, details.handler] + assert_equal([:en, :html, :phone, :erb], [details.locale, details.format, details.variant, details.handler]) end - refute_same parser, ViewComponent::CompileCache.path_parser - refute_same ViewComponent::CompileCache.path_parser, ViewComponent::CompileCache.path_parser + refute_same(parser, ViewComponent::CompileCache.path_parser) + refute_same(ViewComponent::CompileCache.path_parser, ViewComponent::CompileCache.path_parser) end def test_template_path_parser_is_discarded_after_an_error @@ -269,44 +286,50 @@ def test_template_path_parser_is_discarded_after_an_error end end - refute_same parser, ViewComponent::CompileCache.path_parser + refute_same(parser, ViewComponent::CompileCache.path_parser) end def test_compiled_status_tracks_cache_invalidation MyComponent.__vc_compile - assert_predicate MyComponent, :__vc_compiled? + assert_predicate(MyComponent, :__vc_compiled?) ViewComponent::CompileCache.invalidate_class!(MyComponent) - refute_predicate MyComponent, :__vc_compiled? + refute_predicate(MyComponent, :__vc_compiled?) MyComponent.__vc_compile - assert_predicate MyComponent, :__vc_compiled? + assert_predicate(MyComponent, :__vc_compiled?) end def test_default_output_preamble_and_postamble component = MyComponent.new [component.output_preamble, component.output_postamble].each do |output| - assert_empty output - assert_predicate output, :html_safe? - assert_predicate output, :frozen? + assert_empty(output) + assert_predicate(output, :html_safe?) + assert_predicate(output, :frozen?) end end def test_html_safe_output_does_not_need_a_blankness_check output = "

safe

".html_safe - output.stub(:blank?, -> { flunk "HTML-safe output should not be scanned for whitespace" }) do - assert_same output, MyComponent.new.send(:__vc_maybe_escape_html, output) { flunk "HTML-safe output should not warn" } + output.stub(:blank?, -> { flunk("HTML-safe output should not be scanned for whitespace") }) do + assert_same( + output, + MyComponent.new.send(:__vc_maybe_escape_html, output) { flunk("HTML-safe output should not warn") } + ) end end def test_does_not_render_additional_newline_with_render_in without_template_annotations do ActionView::Template::Handlers::ERB.strip_trailing_newlines = true - rendered_output = Array.new(2) { - DisplayInlineComponent.new.render_in(ActionController::Base.new.view_context) - }.join - assert_includes rendered_output, "Hello, world!Hello, world!" + rendered_output = Array + .new(2) { + DisplayInlineComponent.new.render_in(ActionController::Base.new.view_context) + } + .join + assert_includes(rendered_output, "Hello, world!Hello, world!") end + ensure ActionView::Template::Handlers::ERB.strip_trailing_newlines = false end @@ -321,15 +344,16 @@ def test_render_looks_up_the_overridden_virtual_path_once lookups += 1 "custom/component" end + component.define_singleton_method(:before_render) do paths = [@virtual_path, @view_context.instance_variable_get(:@virtual_path)] end component.render_in(view_context) - assert_equal 1, lookups - assert_equal ["custom/component", "custom/component"], paths - assert_equal "original", view_context.instance_variable_get(:@virtual_path) + assert_equal(1, lookups) + assert_equal(["custom/component", "custom/component"], paths) + assert_equal("original", view_context.instance_variable_get(:@virtual_path)) end def test_evaled_component @@ -345,17 +369,23 @@ def initialize(cta: nil, title:) end RUBY - eval(source) # rubocop:disable Security/Eval + # rubocop:disable Security/Eval + eval(source) + # rubocop:enable Security/Eval end def test_no_method_error_does_not_reference_helper_if_view_context_not_present exception = assert_raises(NoMethodError) { Class.new(ViewComponent::Base).new.current_user } - exception_message_regex = Regexp.new <<~MESSAGE.chomp, Regexp::MULTILINE - undefined method `current_user' for .* - - You may be trying to call a method provided as a view helper. Did you mean `helpers.current_user`? - MESSAGE - assert !exception_message_regex.match?(exception.message) + exception_message_regex = Regexp.new( + <<~MESSAGE + undefined method `current_user' for .* + + You may be trying to call a method provided as a view helper. Did you mean `helpers.current_user`? + MESSAGE + .chomp, + Regexp::MULTILINE + ) + assert(!exception_message_regex.match?(exception.message)) end def test_no_method_error_references_helper_if_view_context_present @@ -367,16 +397,19 @@ def current_user } exception = assert_raises(NameError) { ReferencesMethodOnHelpersComponent.new.render_in(view_context) } exception_advice = "You may be trying to call a method provided as a view helper. Did you mean `helpers.current_user`?" - assert exception.message.include?(exception_advice) + assert(exception.message.include?(exception_advice)) end def test_no_method_error_does_not_reference_missing_helper view_context = ActionController::Base.new.view_context exception = assert_raises(NameError) { ReferencesMethodOnHelpersComponent.new.render_in(view_context) } - exception_message_regex = Regexp.new <<~MESSAGE.chomp - You may be trying to call a method provided as a view helper\\. Did you mean `helpers.current_user`\\?$ - MESSAGE - assert !exception_message_regex.match?(exception.message) + exception_message_regex = Regexp.new( + <<~MESSAGE + You may be trying to call a method provided as a view helper\\. Did you mean `helpers.current_user`\\?$ + MESSAGE + .chomp + ) + assert(!exception_message_regex.match?(exception.message)) end module TestModuleWithoutConfig @@ -419,10 +452,10 @@ class SomeComponent < ViewComponent::Base end def test_uses_module_configuration - assert_equal true, TestModuleWithoutConfig::SomeComponent.instrumentation_enabled - assert_equal false, TestModuleWithConfig::SomeComponent.instrumentation_enabled - assert_equal false, TestAlreadyConfigurableModule::SomeComponent.instrumentation_enabled - assert_equal false, TestAlreadyConfiguredModule::SomeComponent.instrumentation_enabled + assert_equal(true, TestModuleWithoutConfig::SomeComponent.instrumentation_enabled) + assert_equal(false, TestModuleWithConfig::SomeComponent.instrumentation_enabled) + assert_equal(false, TestAlreadyConfigurableModule::SomeComponent.instrumentation_enabled) + assert_equal(false, TestAlreadyConfiguredModule::SomeComponent.instrumentation_enabled) end def test_after_compile_hook_called_on_compile @@ -439,14 +472,14 @@ def after_compile end end - erb_template "" + erb_template("") end self.class.const_set(:TempHookComponent, klass) ViewComponent::CompileCache.invalidate_class!(klass) ViewComponent::Compiler.new(klass).compile(force: true) - assert_equal 1, klass.calls + assert_equal(1, klass.calls) ensure self.class.send(:remove_const, :TempHookComponent) if self.class.const_defined?(:TempHookComponent) ViewComponent::CompileCache.invalidate_class!(klass) if defined?(klass) @@ -466,7 +499,7 @@ def after_compile end end - erb_template "" + erb_template("") end self.class.const_set(:TempHookCachedComponent, klass) @@ -474,11 +507,11 @@ def after_compile compiler = ViewComponent::Compiler.new(klass) compiler.compile(force: true) - assert_equal 1, klass.calls + assert_equal(1, klass.calls) # compile again without force -> should not call hook again compiler.compile - assert_equal 1, klass.calls + assert_equal(1, klass.calls) ensure self.class.send(:remove_const, :TempHookCachedComponent) if self.class.const_defined?(:TempHookCachedComponent) ViewComponent::CompileCache.invalidate_class!(klass) if defined?(klass) diff --git a/test/sandbox/test/better_html_test.rb b/test/sandbox/test/better_html_test.rb index f1e1aabad..b6604ec00 100644 --- a/test/sandbox/test/better_html_test.rb +++ b/test/sandbox/test/better_html_test.rb @@ -9,7 +9,10 @@ class BetterHtmlTest < ActiveSupport::TestCase include BetterHtml::TestHelper::SafeErbTester ERB_GLOB = Rails.root.join( - "app", "views", "**", "{*.htm,*.html,*.htm.erb,*.html.erb,*.html+*.erb}" + "app", + "views", + "**", + "{*.htm,*.html,*.htm.erb,*.html.erb,*.html+*.erb}" ) Dir[ERB_GLOB].each do |filename| diff --git a/test/sandbox/test/cacheable_integration_test.rb b/test/sandbox/test/cacheable_integration_test.rb index 82e71afba..22b3d044a 100644 --- a/test/sandbox/test/cacheable_integration_test.rb +++ b/test/sandbox/test/cacheable_integration_test.rb @@ -20,74 +20,74 @@ def teardown end def test_renders_a_component_inside_a_cache_block - get "/cached_component" + get("/cached_component") - assert_response :success + assert_response(:success) assert_select(".cacheable", text: "cached") end def test_cache_block_is_invalidated_when_the_component_template_changes - get "/cached_component" + get("/cached_component") assert_select(".cacheable", text: "cached") - modify_file "app/components/cacheable_component.html.erb", "
changed
\n" do + modify_file("app/components/cacheable_component.html.erb", "
changed
\n") do clear_digest_cache with_new_cache do - get "/cached_component" + get("/cached_component") assert_select(".cacheable", text: "changed") end end end def test_cache_block_is_invalidated_when_the_component_ruby_file_changes - get "/cached_component" + get("/cached_component") assert_select(".cacheable", text: "cached") before = fragment_digest_for("integration_examples/cached_component") original = File.read(Rails.root.join("app/components/cacheable_component.rb")) - modify_file "app/components/cacheable_component.rb", original + "\n# a comment\n" do + modify_file("app/components/cacheable_component.rb", original + "\n# a comment\n") do clear_digest_cache - refute_equal before, fragment_digest_for("integration_examples/cached_component") + refute_equal(before, fragment_digest_for("integration_examples/cached_component")) end end def test_cache_block_is_invalidated_when_a_nested_component_changes - get "/cached_nested_component" + get("/cached_nested_component") assert_select(".cacheable-child", text: "child") before = fragment_digest_for("integration_examples/cached_nested_component") - modify_file "app/components/cacheable_child_component.html.erb", "changed\n" do + modify_file("app/components/cacheable_child_component.html.erb", "changed\n") do clear_digest_cache - refute_equal before, fragment_digest_for("integration_examples/cached_nested_component") + refute_equal(before, fragment_digest_for("integration_examples/cached_nested_component")) end end def test_cache_block_digest_is_unaffected_by_unrelated_components before = fragment_digest_for("integration_examples/cached_component") - modify_file "app/components/erb_component.html.erb", "
unrelated change
\n" do + modify_file("app/components/erb_component.html.erb", "
unrelated change
\n") do clear_digest_cache - assert_equal before, fragment_digest_for("integration_examples/cached_component") + assert_equal(before, fragment_digest_for("integration_examples/cached_component")) end end def test_cache_block_is_invalidated_when_an_untracked_component_changes - get "/cached_untracked_component" + get("/cached_untracked_component") assert_select(".untracked-child", text: "untracked") before = fragment_digest_for("integration_examples/cached_untracked_component") - modify_file "app/components/untracked_child_component.html.erb", "changed\n" do + modify_file("app/components/untracked_child_component.html.erb", "changed\n") do clear_digest_cache - refute_equal before, fragment_digest_for("integration_examples/cached_untracked_component") + refute_equal(before, fragment_digest_for("integration_examples/cached_untracked_component")) with_new_cache do - get "/cached_untracked_component" + get("/cached_untracked_component") assert_select(".untracked-child", text: "changed") end @@ -95,13 +95,13 @@ def test_cache_block_is_invalidated_when_an_untracked_component_changes end def test_cache_block_is_invalidated_when_a_transitive_untracked_component_changes - get "/cached_untracked_component" + get("/cached_untracked_component") assert_select(".http-untracked", text: "HTTP") - modify_file "app/components/http_untracked_component.html.erb", "changed\n" do + modify_file("app/components/http_untracked_component.html.erb", "changed\n") do clear_digest_cache with_new_cache do - get "/cached_untracked_component" + get("/cached_untracked_component") assert_select(".http-untracked", text: "changed") end @@ -109,21 +109,21 @@ def test_cache_block_is_invalidated_when_a_transitive_untracked_component_change end def test_renders_a_cache_block_held_by_a_component_template - get "/cache_block_component" + get("/cache_block_component") - assert_response :success + assert_response(:success) assert_select(".cache-block .cacheable-child", text: "child") end def test_fragment_inside_a_component_template_is_invalidated_when_its_template_changes - get "/cache_block_component" + get("/cache_block_component") assert_select(".cache-block .cacheable-child", text: "child") template = "<% cache \"cache-block-fragment\" do %>\n
changed
\n<% end %>\n" - modify_file "app/components/cache_block_component.html.erb", template do + modify_file("app/components/cache_block_component.html.erb", template) do clear_digest_cache with_new_cache do - get "/cache_block_component" + get("/cache_block_component") assert_select(".cache-block", text: "changed") end @@ -134,30 +134,30 @@ def test_fragment_inside_a_component_template_is_invalidated_when_an_ancestor_ch before = fragment_key_for("/cache_block_component") original = File.read(Rails.root.join("app/components/cache_block_base_component.rb")) - modify_file "app/components/cache_block_base_component.rb", original + "\n# a comment\n" do + modify_file("app/components/cache_block_base_component.rb", original + "\n# a comment\n") do clear_digest_cache - refute_equal before, fragment_key_for("/cache_block_component") + refute_equal(before, fragment_key_for("/cache_block_component")) end end def test_fragment_inside_a_component_template_is_invalidated_when_a_rendered_component_changes before = fragment_key_for("/cache_block_component") - modify_file "app/components/cacheable_child_component.html.erb", "changed\n" do + modify_file("app/components/cacheable_child_component.html.erb", "changed\n") do clear_digest_cache - refute_equal before, fragment_key_for("/cache_block_component") + refute_equal(before, fragment_key_for("/cache_block_component")) end end def test_fragment_inside_a_component_template_is_unaffected_by_unrelated_components before = fragment_key_for("/cache_block_component") - modify_file "app/components/erb_component.html.erb", "
unrelated change
\n" do + modify_file("app/components/erb_component.html.erb", "
unrelated change
\n") do clear_digest_cache - assert_equal before, fragment_key_for("/cache_block_component") + assert_equal(before, fragment_key_for("/cache_block_component")) end end @@ -180,18 +180,18 @@ def test_digest_does_not_depend_on_when_the_component_registered fragment_digest_for("integration_examples/cached_component") end - assert_equal registered_first, registered_late + assert_equal(registered_first, registered_late) end def test_component_output_is_cached_between_requests - get "/cached_component" + get("/cached_component") assert_select(".cacheable", text: "cached") # The component's own `cache_on` entry is written on first render. component = CacheableComponent.new(title: "cached") context = controller.view_context context.lookup_context.formats = [:html] - refute_nil Rails.cache.read(component.cache_key(context)) + refute_nil(Rails.cache.read(component.cache_key(context))) end private @@ -211,7 +211,7 @@ def fragment_digest_for(virtual_path) # The key of the fragment the component's own template caches during the # given request. def fragment_key_for(path) - capture_fragment_key { with_new_cache { get path } } + capture_fragment_key { with_new_cache { get(path) } } end def with_registry(entries) diff --git a/test/sandbox/test/cacheable_review_test.rb b/test/sandbox/test/cacheable_review_test.rb index 630fd726e..6b9af78b6 100644 --- a/test/sandbox/test/cacheable_review_test.rb +++ b/test/sandbox/test/cacheable_review_test.rb @@ -22,13 +22,13 @@ def test_formats_do_not_share_a_cache_entry with_caching do with_format(:html) do render_inline(FormatSensitiveCacheableComponent.new) - assert_text "html" + assert_text("html") end with_format(:json) do render_inline(FormatSensitiveCacheableComponent.new) - assert_text "json" + assert_text("json") end end end @@ -37,7 +37,7 @@ def test_cache_key_differs_by_format html_key = with_format(:html) { FormatSensitiveCacheableComponent.new.cache_key(vc_test_controller.view_context) } json_key = with_format(:json) { FormatSensitiveCacheableComponent.new.cache_key(vc_test_controller.view_context) } - refute_equal html_key, json_key + refute_equal(html_key, json_key) end # Issue 2: the key array is compacted as a whole, so a nil in one position is @@ -46,23 +46,23 @@ def test_nil_cache_on_values_do_not_collide_positionally left = PositionalCacheKeyComponent.new(first: nil, second: "same") right = PositionalCacheKeyComponent.new(first: "same", second: nil) - refute_equal left.cache_key, right.cache_key + refute_equal(left.cache_key, right.cache_key) end def test_nil_and_empty_cache_on_values_do_not_collide nils = PositionalCacheKeyComponent.new(first: nil, second: nil) empties = PositionalCacheKeyComponent.new(first: "", second: "") - refute_equal nils.cache_key, empties.cache_key + refute_equal(nils.cache_key, empties.cache_key) end def test_cache_on_values_preserve_argument_boundaries with_caching do render_inline(PositionalCacheKeyComponent.new(first: "a/b", second: "c")) - assert_text "a/b-c" + assert_text("a/b-c") render_inline(PositionalCacheKeyComponent.new(first: "a", second: "b/c")) - assert_text "a-b/c" + assert_text("a-b/c") end end @@ -70,14 +70,14 @@ def test_cache_on_array_values_preserve_argument_boundaries left = PositionalCacheKeyComponent.new(first: %w[a b], second: ["c"]) right = PositionalCacheKeyComponent.new(first: ["a"], second: %w[b c]) - refute_equal left.cache_key, right.cache_key + refute_equal(left.cache_key, right.cache_key) end def test_nil_cache_on_values_do_not_collide_with_the_nil_marker nil_value = PositionalCacheKeyComponent.new(first: nil, second: "same") marker = PositionalCacheKeyComponent.new(first: "__vc_nil", second: "same") - refute_equal nil_value.cache_key, marker.cache_key + refute_equal(nil_value.cache_key, marker.cache_key) end def test_cache_on_preserves_versioned_record_keys @@ -85,7 +85,7 @@ def test_cache_on_preserves_versioned_record_keys before = PositionalCacheKeyComponent.new(first: record, second: "same").cache_key record.cache_key_with_version = "records/1-v2" - refute_equal before, PositionalCacheKeyComponent.new(first: record, second: "same").cache_key + refute_equal(before, PositionalCacheKeyComponent.new(first: record, second: "same").cache_key) end # Issue 3: there's no way to skip caching for a single render. A false or nil @@ -96,7 +96,7 @@ def test_caching_can_be_disabled_per_render render_inline(ConditionalCacheProbeComponent.new(cacheable: false)) render_inline(ConditionalCacheProbeComponent.new(cacheable: false)) - assert_equal 2, ConditionalCacheProbeComponent.render_count + assert_equal(2, ConditionalCacheProbeComponent.render_count) end end @@ -105,7 +105,7 @@ def test_caching_still_applies_when_the_condition_is_met render_inline(ConditionalCacheProbeComponent.new(cacheable: true)) render_inline(ConditionalCacheProbeComponent.new(cacheable: true)) - assert_equal 1, ConditionalCacheProbeComponent.render_count + assert_equal(1, ConditionalCacheProbeComponent.render_count) end end @@ -114,7 +114,7 @@ def test_cache_hits_do_not_allow_reusing_component_instances render_inline(CacheableComponent.new(title: "cached")) component = CacheableComponent.new(title: "cached") render_inline(component) - assert_text "cached" + assert_text("cached") assert_raises(ViewComponent::ReusedInstanceError) { render_inline(component) } end @@ -135,14 +135,14 @@ def self.name "ProcConditionCacheProbeComponent" end - cache_on :identity, if: -> { false } + cache_on(:identity, if: -> { false }) end with_caching do render_inline(component.new(cacheable: true)) render_inline(component.new(cacheable: true)) - assert_equal 2, component.render_count + assert_equal(2, component.render_count) end end @@ -152,14 +152,14 @@ def self.name "UnlessConditionCacheProbeComponent" end - cache_on :identity, unless: :cacheable? + cache_on(:identity, unless: :cacheable?) end with_caching do render_inline(component.new(cacheable: true)) render_inline(component.new(cacheable: true)) - assert_equal 2, component.render_count + assert_equal(2, component.render_count) end end @@ -174,36 +174,36 @@ def self.name render_inline(component.new(cacheable: false)) render_inline(component.new(cacheable: false)) - assert_equal 2, component.render_count + assert_equal(2, component.render_count) end end def test_cache_on_is_available_without_including_the_module component = Class.new(ViewComponent::Base) - refute_predicate component, :__vc_caches_output? + refute_predicate(component, :__vc_caches_output?) - component.cache_on :identity + component.cache_on(:identity) - assert_predicate component, :__vc_caches_output? - refute_predicate ViewComponent::Base, :__vc_caches_output? + assert_predicate(component, :__vc_caches_output?) + refute_predicate(ViewComponent::Base, :__vc_caches_output?) end def test_including_the_module_explicitly_is_harmless component = Class.new(ViewComponent::Base) do - include ViewComponent::Cacheable + include(ViewComponent::Cacheable) - cache_on :identity + cache_on(:identity) end - assert_equal 1, component.ancestors.count(ViewComponent::Cacheable) - assert_equal [:identity], component.__vc_cache_on + assert_equal(1, component.ancestors.count(ViewComponent::Cacheable)) + assert_equal([:identity], component.__vc_cache_on) end def test_cache_on_rejects_unknown_options error = assert_raises(ArgumentError) do Class.new(ViewComponent::Base) do - cache_on :identity, when: :something + cache_on(:identity, when: :something) end end @@ -216,7 +216,7 @@ def self.name "MissingConditionCacheProbeComponent" end - cache_on :identity, if: :nonexistent? + cache_on(:identity, if: :nonexistent?) end with_caching do @@ -224,7 +224,7 @@ def self.name render_inline(component.new(cacheable: true)) end - assert_includes error.message, "nonexistent?" + assert_includes(error.message, "nonexistent?") end end @@ -243,7 +243,7 @@ def test_cache_on_rejects_a_block def test_cache_on_rejects_a_proc_with_a_useful_error error = assert_raises(ArgumentError) do Class.new(ViewComponent::Base) do - cache_on -> { :identity } + cache_on(-> { :identity }) end end diff --git a/test/sandbox/test/cacheable_test.rb b/test/sandbox/test/cacheable_test.rb index 79a84edf5..18697a941 100644 --- a/test/sandbox/test/cacheable_test.rb +++ b/test/sandbox/test/cacheable_test.rb @@ -29,68 +29,68 @@ def test_registering_an_unchanged_component_leaves_memoized_digests_alone CacheableComponent.cache_digest memoized = digest_cache_size - assert_operator memoized, :>, 0 + assert_operator(memoized, :>, 0) ViewComponent::CacheDigest.register(CacheableComponent) - assert_equal memoized, digest_cache_size + assert_equal(memoized, digest_cache_size) end def test_registering_a_new_component_expires_memoized_digests clear_digest_cache CacheableComponent.cache_digest - assert_operator digest_cache_size, :>, 0 + assert_operator(digest_cache_size, :>, 0) ViewComponent::CacheDigest.registry.delete("cacheable_component") ViewComponent::CacheDigest.register(CacheableComponent) - assert_equal 0, digest_cache_size + assert_equal(0, digest_cache_size) end def test_only_components_declaring_cache_on_cache_their_output - assert_predicate CacheableComponent, :__vc_caches_output? - refute_predicate ErbComponent, :__vc_caches_output? + assert_predicate(CacheableComponent, :__vc_caches_output?) + refute_predicate(ErbComponent, :__vc_caches_output?) end def test_cache_on_declares_key_methods - assert_equal [:title], CacheableComponent.__vc_cache_on + assert_equal([:title], CacheableComponent.__vc_cache_on) end def test_component_without_cache_on_does_not_cache_output - refute_predicate CacheableParentComponent, :__vc_caches_output? - assert_predicate CacheableComponent, :__vc_caches_output? + refute_predicate(CacheableParentComponent, :__vc_caches_output?) + assert_predicate(CacheableComponent, :__vc_caches_output?) end def test_cache_digest_is_computable_outside_a_request digest = CacheableComponent.cache_digest - assert_kind_of String, digest - refute_empty digest + assert_kind_of(String, digest) + refute_empty(digest) end def test_cache_digest_raises_when_a_ruby_dependency_fails_to_load error = assert_raises(RuntimeError) { CacheableRaisingRubyDependencyComponent.cache_digest } - assert_equal "raising Ruby dependency", error.message + assert_equal("raising Ruby dependency", error.message) end def test_cache_digest_raises_when_a_template_dependency_fails_to_load error = assert_raises(RuntimeError) { CacheableRaisingTemplateDependencyComponent.cache_digest } - assert_equal "raising template dependency", error.message + assert_equal("raising template dependency", error.message) end def test_cache_digest_raises_when_an_explicit_dependency_fails_to_load error = assert_raises(RuntimeError) { CacheableRaisingExplicitDependencyComponent.cache_digest } - assert_equal "raising Ruby dependency", error.message + assert_equal("raising Ruby dependency", error.message) end def test_cache_digest_raises_when_a_digest_source_cannot_be_read error = assert_raises(Errno::EISDIR) { CacheableUnreadableDigestSourceComponent.cache_digest } - assert_includes error.message, "cacheable_unreadable_digest_source_component.yml" + assert_includes(error.message, "cacheable_unreadable_digest_source_component.yml") end def test_digest_source_hashes_binary_ruby_files_without_scanning_them @@ -101,10 +101,10 @@ def test_digest_source_hashes_binary_ruby_files_without_scanning_them component.stub(:identifier, path) do File.binwrite(path, "\xFF\xFE render Template Dependency:".b) source = ViewComponent::CacheDigest::Resolver.instance.source_for(component) - assert_includes source, "Resolved Dependency: #{path} #{ActiveSupport::Digest.hexdigest(File.binread(path))}" + assert_includes(source, "Resolved Dependency: #{path} #{ActiveSupport::Digest.hexdigest(File.binread(path))}") File.binwrite(path, "\xFF\xFD".b) - refute_equal source, ViewComponent::CacheDigest::Resolver.instance.source_for(component) + refute_equal(source, ViewComponent::CacheDigest::Resolver.instance.source_for(component)) end end end @@ -143,7 +143,7 @@ def test_cache_digest_changes_when_a_child_component_ruby_file_changes def test_cache_digest_tracks_lexically_namespaced_children render_inline(CacheDigestNamespace::ParentComponent.new) - assert_text "namespaced child" + assert_text("namespaced child") assert_digest_changes( "app/components/cache_digest_namespace/child_component.html.erb", @@ -163,16 +163,16 @@ def call RUBY dependencies, partials = ViewComponent::CacheDigest.renders_in(source, "test/template") - assert_includes dependencies, "view_component/cache_digest/cache_digest_namespace/child_component" - refute_includes dependencies, "view_component/cache_digest/child_component" - assert_empty partials + assert_includes(dependencies, "view_component/cache_digest/cache_digest_namespace/child_component") + refute_includes(dependencies, "view_component/cache_digest/child_component") + assert_empty(partials) end def test_absolute_dependencies_ignore_lexical_nesting source = "module CacheDigestNamespace; render ::ChildComponent.new; end" dependencies, = ViewComponent::CacheDigest.renders_in(source, "test/template") - assert_equal ["view_component/cache_digest/child_component"], dependencies + assert_equal(["view_component/cache_digest/child_component"], dependencies) end def test_dependency_discovery_restores_lexical_scope_after_nested_bodies @@ -187,20 +187,23 @@ class ParentComponent RUBY dependencies, partials = ViewComponent::CacheDigest.renders_in(source, "test/template") - assert_equal [ - "view_component/cache_digest/cache_digest_namespace/parent_component", - "view_component/cache_digest/cache_digest_namespace/child_component", - "view_component/cache_digest/child_component" - ], dependencies - assert_empty partials + assert_equal( + [ + "view_component/cache_digest/cache_digest_namespace/parent_component", + "view_component/cache_digest/cache_digest_namespace/child_component", + "view_component/cache_digest/child_component" + ], + dependencies + ) + assert_empty(partials) end def test_qualified_class_declarations_do_not_add_enclosing_namespaces_to_nesting source = "class CacheDigestNamespace::ParentComponent; render ChildComponent.new; end" dependencies, = ViewComponent::CacheDigest.renders_in(source, "test/template") - assert_includes dependencies, "view_component/cache_digest/child_component" - refute_includes dependencies, "view_component/cache_digest/cache_digest_namespace/child_component" + assert_includes(dependencies, "view_component/cache_digest/child_component") + refute_includes(dependencies, "view_component/cache_digest/cache_digest_namespace/child_component") end def test_template_dependencies_resolve_constants_in_the_component @@ -212,28 +215,28 @@ def test_template_dependencies_resolve_constants_in_the_component "test/template" ) - assert_equal ["view_component/cache_digest/cache_digest_namespace/child_component"], dependencies + assert_equal(["view_component/cache_digest/cache_digest_namespace/child_component"], dependencies) end def test_dependency_lookup_finds_inherited_constants source = "class CacheDigestNamespace::InheritedTemplateComponent; render Child.new; end" dependencies, = ViewComponent::CacheDigest.renders_in(source, "test/template") - assert_includes dependencies, "view_component/cache_digest/cache_digest_namespace/child_component" + assert_includes(dependencies, "view_component/cache_digest/cache_digest_namespace/child_component") end def test_dependency_lookup_respects_non_component_constants_shadowing_components source = "class CacheDigestNamespace::TemplateComponent; value = ErbComponent; end" dependencies, = ViewComponent::CacheDigest.renders_in(source, "test/template") - refute_includes dependencies, "view_component/cache_digest/erb_component" + refute_includes(dependencies, "view_component/cache_digest/erb_component") end def test_qualified_dependency_lookup_does_not_fall_back_to_top_level_constants source = "module CacheDigestNamespace; value = TemplateComponent::MyComponent; end" dependencies, = ViewComponent::CacheDigest.renders_in(source, "test/template") - refute_includes dependencies, "view_component/cache_digest/my_component" + refute_includes(dependencies, "view_component/cache_digest/my_component") end def test_cache_digest_changes_when_an_untracked_child_template_changes @@ -253,8 +256,8 @@ def test_cache_digest_changes_when_an_untracked_child_ruby_file_changes end def test_cache_digest_changes_when_a_transitive_untracked_dependency_changes - refute_predicate UntrackedChildComponent, :__vc_caches_output? - refute_predicate HTTPUntrackedComponent, :__vc_caches_output? + refute_predicate(UntrackedChildComponent, :__vc_caches_output?) + refute_predicate(HTTPUntrackedComponent, :__vc_caches_output?) assert_digest_changes( "app/components/http_untracked_component.html.erb", @@ -298,38 +301,42 @@ def test_declared_component_class_names_resolve_to_the_component template = build_template("<%# Template Dependency: CacheableChildComponent %>") dependencies = ActionView::DependencyTracker.find_dependencies("test/template", template, []) - assert_includes dependencies, "view_component/cache_digest/cacheable_child_component" + assert_includes(dependencies, "view_component/cache_digest/cacheable_child_component") # The raw class name would resolve to nothing, so it's replaced rather than added. - refute_includes dependencies, "CacheableChildComponent" + refute_includes(dependencies, "CacheableChildComponent") end def test_declared_template_paths_are_left_alone template = build_template("<%# Template Dependency: integration_examples/erb_partial %>") dependencies = ActionView::DependencyTracker.find_dependencies("test/template", template, []) - assert_includes dependencies, "integration_examples/erb_partial" + assert_includes(dependencies, "integration_examples/erb_partial") end def test_declared_names_that_are_not_components_are_left_alone - assert_empty ViewComponent::CacheDigest.explicit_component_dependencies( - "# Template Dependency: NotAConstantAnywhere" + assert_empty( + ViewComponent::CacheDigest.explicit_component_dependencies( + "# Template Dependency: NotAConstantAnywhere" + ) ) - assert_empty ViewComponent::CacheDigest.explicit_component_dependencies( - "# Template Dependency: ActiveSupport::Digest" + assert_empty( + ViewComponent::CacheDigest.explicit_component_dependencies( + "# Template Dependency: ActiveSupport::Digest" + ) ) - assert_empty ViewComponent::CacheDigest.explicit_component_dependencies("no declarations here") + assert_empty(ViewComponent::CacheDigest.explicit_component_dependencies("no declarations here")) end def test_declared_components_resolve_without_opting_into_caching - refute_predicate ErbComponent, :__vc_caches_output? + refute_predicate(ErbComponent, :__vc_caches_output?) with_registry("cacheable_component" => "CacheableComponent") do template = build_template("<%# Template Dependency: ErbComponent %>") dependencies = ActionView::DependencyTracker.find_dependencies("test/template", template, []) - assert_includes dependencies, "view_component/cache_digest/erb_component" - refute_includes dependencies, "ErbComponent" - assert_equal ErbComponent, ViewComponent::CacheDigest.component_for("view_component/cache_digest/erb_component") + assert_includes(dependencies, "view_component/cache_digest/erb_component") + refute_includes(dependencies, "ErbComponent") + assert_equal(ErbComponent, ViewComponent::CacheDigest.component_for("view_component/cache_digest/erb_component")) end end @@ -353,10 +360,14 @@ def test_declared_components_register_acronym_names_and_custom_virtual_paths ], dependencies ) - assert_equal HTTPUntrackedComponent, + assert_equal( + HTTPUntrackedComponent, ViewComponent::CacheDigest.component_for("view_component/cache_digest/http_untracked_component") - assert_equal UntrackedChildComponent, + ) + assert_equal( + UntrackedChildComponent, ViewComponent::CacheDigest.component_for("view_component/cache_digest/custom/untracked_child") + ) end end @@ -482,12 +493,12 @@ def test_digest_builds_each_component_once resolver = ViewComponent::CacheDigest::Resolver.instance source_for = resolver.method(:source_for) - resolver.stub(:source_for, ->(component) { built << component && source_for.call(component) }) do + resolver.stub(:source_for, -> (component) { built << component && source_for.call(component) }) do CacheableDiamondComponent.cache_digest end - assert_equal built.uniq, built - assert_includes built, CacheableChildComponent + assert_equal(built.uniq, built) + assert_includes(built, CacheableChildComponent) ensure clear_digest_cache end @@ -504,23 +515,24 @@ def test_cold_digest_shares_sidecar_directory_listings Dir.stub(:glob, scan) { CacheableDiamondComponent.cache_digest } - assert_equal 1, scans + assert_equal(1, scans) ensure clear_digest_cache end def test_file_caching_preserves_the_digest clear_digest_cache - uncached = ->(&block) { block.call } - without_memoization = ->(_key, &block) { block.call } + uncached = -> (&block) { block.call } + without_memoization = -> (_key, &block) { block.call } expected = ViewComponent::CompileCache.stub(:with_sidecar_files_cache, uncached) do ViewComponent::CacheDigest.stub(:memoize, without_memoization) do CacheableDiamondComponent.cache_digest end end + clear_digest_cache - assert_equal expected, CacheableDiamondComponent.cache_digest + assert_equal(expected, CacheableDiamondComponent.cache_digest) ensure clear_digest_cache end @@ -534,23 +546,26 @@ def test_shared_source_files_are_hashed_once_per_computation hashes += 1 if content.b == source hexdigest.call(content) end + expected = resolver.source_for(CacheableComponent) ActiveSupport::Digest.stub(:hexdigest, hash_source) do ViewComponent::CacheDigest.memoizing do - assert_equal expected, resolver.source_for(CacheableComponent) + assert_equal(expected, resolver.source_for(CacheableComponent)) resolver.source_for(CacheableSubclassComponent) - assert_equal 1, hashes + assert_equal(1, hashes) end - assert_equal expected, resolver.source_for(CacheableComponent) - assert_equal 2, hashes + assert_equal(expected, resolver.source_for(CacheableComponent)) + assert_equal(2, hashes) end end def test_cold_digests_share_ruby_reads_between_hashing_and_dependency_discovery - skip "Text reads can change source bytes" if File::ALT_SEPARATOR || - (Encoding.default_internal && Encoding.default_internal != Encoding.default_external) + if File::ALT_SEPARATOR || + (Encoding.default_internal && Encoding.default_internal != Encoding.default_external) + skip("Text reads can change source bytes") + end clear_digest_cache path = CacheableComponent.identifier @@ -558,22 +573,29 @@ def test_cold_digests_share_ruby_reads_between_hashing_and_dependency_discovery read = File.method(:read) binread = File.method(:binread) - File.stub(:read, lambda { |filename, *args| - reads += 1 if filename == path - read.call(filename, *args) - }) do - File.stub(:binread, lambda { |filename, *args| + File.stub( + :read, + lambda { |filename, *args| reads += 1 if filename == path - binread.call(filename, *args) - }) do + read.call(filename, *args) + } + ) do + File.stub( + :binread, + lambda { |filename, *args| + reads += 1 if filename == path + binread.call(filename, *args) + } + ) do CacheableComponent.cache_digest - assert_equal 1, reads + assert_equal(1, reads) clear_digest_cache CacheableComponent.cache_digest - assert_equal 2, reads + assert_equal(2, reads) end end + ensure clear_digest_cache end @@ -583,8 +605,8 @@ def test_source_hashes_use_binary_reads_when_text_reads_transcode expected = ActiveSupport::Digest.hexdigest(File.binread(path)) Encoding.stub(:default_internal, Encoding::UTF_16LE) do - File.stub(:read, ->(*) { flunk "read transcoded source" }) do - assert_equal expected, ViewComponent::CacheDigest::Resolver.instance.send(:file_digest, path) + File.stub(:read, -> (*) { flunk("read transcoded source") }) do + assert_equal(expected, ViewComponent::CacheDigest::Resolver.instance.send(:file_digest, path)) end end end @@ -596,7 +618,7 @@ def test_shared_source_reads_preserve_encoded_bytes_and_line_endings expected = ActiveSupport::Digest.hexdigest(File.binread(path)) ViewComponent::CompileCache.with_sidecar_files_cache do - assert_equal expected, ViewComponent::CacheDigest::Resolver.instance.send(:file_digest, path) + assert_equal(expected, ViewComponent::CacheDigest::Resolver.instance.send(:file_digest, path)) end end end @@ -618,18 +640,20 @@ def test_digest_recomputes_when_digests_expire_while_the_tree_is_built ViewComponent::CacheDigest.registry.delete("cacheable_component") ViewComponent::CacheDigest.register(CacheableComponent) end + source_for.call(component) end resolver.stub(:source_for, expire) do - assert_equal expected, CacheableDiamondComponent.cache_digest + assert_equal(expected, CacheableDiamondComponent.cache_digest) end + ensure clear_digest_cache end def test_modules_with_temporary_names_are_not_digested - skip "Module#set_temporary_name requires Ruby 3.3+" unless Module.method_defined?(:set_temporary_name) + skip("Module#set_temporary_name requires Ruby 3.3+") unless Module.method_defined?(:set_temporary_name) component = CacheableHelperComponent.dup resolver = ViewComponent::CacheDigest::Resolver.instance @@ -639,7 +663,7 @@ def test_modules_with_temporary_names_are_not_digested ["ViewComponent::Properties(Extension)", "MissingNamespace::Properties(Extension)"].each do |name| mod.set_temporary_name(name) - assert_equal source, resolver.source_for(component) + assert_equal(source, resolver.source_for(component)) end end @@ -648,8 +672,8 @@ def test_modules_with_temporary_names_are_not_digested def test_modules_view_component_includes_are_not_digested source = ViewComponent::CacheDigest::Resolver.instance.source_for(CacheableComponent) - assert_includes source, "app/components/cacheable_component.rb" - refute_includes source, ViewComponent::CacheDigest::Resolver::VIEW_COMPONENT_LIB + assert_includes(source, "app/components/cacheable_component.rb") + refute_includes(source, ViewComponent::CacheDigest::Resolver::VIEW_COMPONENT_LIB) end # A component names itself and its superclass in its own source, but both @@ -657,8 +681,8 @@ def test_modules_view_component_includes_are_not_digested def test_a_component_does_not_depend_on_itself_or_its_superclasses source = ViewComponent::CacheDigest::Resolver.instance.source_for(CacheableSubclassComponent) - refute_includes source, "Template Dependency: view_component/cache_digest/cacheable_component" - refute_includes source, "Template Dependency: view_component/cache_digest/cacheable_subclass_component" + refute_includes(source, "Template Dependency: view_component/cache_digest/cacheable_component") + refute_includes(source, "Template Dependency: view_component/cache_digest/cacheable_subclass_component") end def test_components_referenced_outside_render_calls_are_found_in_ruby_source @@ -734,7 +758,9 @@ def call RUBY assert_empty( - ViewComponent::CacheDigest::Resolver.instance.send(:ruby_dependencies, source, "view_component/cache_digest/post_component") + ViewComponent::CacheDigest::Resolver + .instance + .send(:ruby_dependencies, source, "view_component/cache_digest/post_component") ) end @@ -742,7 +768,9 @@ def test_literal_relative_partial_paths_are_kept_in_ruby_source assert_equal( ["view_component/cache_digest/bare_name"], ViewComponent::CacheDigest::Resolver.instance.send( - :ruby_dependencies, 'render "bare_name"', "view_component/cache_digest/post_component" + :ruby_dependencies, + "render \"bare_name\"", + "view_component/cache_digest/post_component" ) ) end @@ -751,19 +779,19 @@ def test_facade_dependencies_are_filtered_in_ruby_and_each_template_language resolver = ViewComponent::CacheDigest::Resolver.instance virtual_path = "view_component/cache_digest/post_component" - assert_empty resolver.send(:ruby_dependencies, "render UI.button", virtual_path) + assert_empty(resolver.send(:ruby_dependencies, "render UI.button", virtual_path)) { erb: "<%= render UI.button %>", haml: "= render UI.button", slim: "= render UI.button" }.each do |extension, source| - assert_empty resolver.send(:template_dependencies, CacheableComponent, source, extension, virtual_path) + assert_empty(resolver.send(:template_dependencies, CacheableComponent, source, extension, virtual_path)) end end def test_partial_paths_are_not_extracted_from_sources_without_render - assert_equal [[], []], ViewComponent::CacheDigest.renders_in("def call; end", "a/b") + assert_equal([[], []], ViewComponent::CacheDigest.renders_in("def call; end", "a/b")) end # Action View has shipped the parser as a class (7.1, main) and as a module @@ -772,52 +800,52 @@ def test_partial_paths_are_not_extracted_from_sources_without_render def test_render_parser_supports_both_action_view_shapes parser_class = Class.new - assert_equal parser_class, ViewComponent::CacheDigest.resolve_render_parser(parser_class) + assert_equal(parser_class, ViewComponent::CacheDigest.resolve_render_parser(parser_class)) default = Class.new parser_module = Module.new parser_module.const_set(:Default, default) - assert_equal default, ViewComponent::CacheDigest.resolve_render_parser(parser_module) + assert_equal(default, ViewComponent::CacheDigest.resolve_render_parser(parser_module)) end def test_render_parser_is_resolved_for_the_running_action_view - assert_respond_to ViewComponent::CacheDigest::RENDER_PARSER, :new + assert_respond_to(ViewComponent::CacheDigest::RENDER_PARSER, :new) end def test_cache_digest_is_unaffected_by_unrelated_changes clear_digest_cache before = CacheableComponent.cache_digest - modify_file "app/components/erb_component.html.erb", "
unrelated
\n" do + modify_file("app/components/erb_component.html.erb", "
unrelated
\n") do clear_digest_cache - assert_equal before, CacheableComponent.cache_digest + assert_equal(before, CacheableComponent.cache_digest) end end def test_digests_of_different_components_differ - refute_equal CacheableComponent.cache_digest, CacheableParentComponent.cache_digest + refute_equal(CacheableComponent.cache_digest, CacheableParentComponent.cache_digest) end def test_cache_key_includes_cache_on_values a = CacheableComponent.new(title: "a").cache_key b = CacheableComponent.new(title: "b").cache_key - refute_equal a, b + refute_equal(a, b) end def test_cache_key_includes_the_digest key = CacheableComponent.new(title: "a").cache_key - assert_includes key, CacheableComponent.cache_digest + assert_includes(key, CacheableComponent.cache_digest) end # A `cache` block in a component template is digested from the component's # own path, which resolves to no template: component templates aren't in the # view paths. Without a digest of its own the fragment never invalidates. def test_a_cache_block_in_a_component_template_is_digested - refute_predicate CacheBlockComponent, :__vc_caches_output? + refute_predicate(CacheBlockComponent, :__vc_caches_output?) with_caching do key = capture_fragment_key { render_inline(CacheBlockComponent.new) } @@ -862,14 +890,14 @@ def test_digest_path_for_anything_else_is_left_to_rails def test_undefined_cache_on_method_raises component = Class.new(CacheableComponent) do - cache_on :nonexistent + cache_on(:nonexistent) end error = assert_raises(ViewComponent::UndefinedCacheKeyMethodError) do component.new(title: "a").cache_key end - assert_includes error.message, "nonexistent" + assert_includes(error.message, "nonexistent") end def test_renders_normally_when_caching_is_disabled @@ -881,7 +909,7 @@ def test_renders_normally_when_caching_is_disabled def test_nothing_is_written_to_the_cache_when_caching_is_disabled render_inline(CacheableComponent.new(title: "hello")) - assert_nil Rails.cache.read(CacheableComponent.new(title: "hello").cache_key(vc_test_controller.view_context)) + assert_nil(Rails.cache.read(CacheableComponent.new(title: "hello").cache_key(vc_test_controller.view_context))) end def test_output_is_served_from_the_cache_on_a_second_render @@ -891,7 +919,7 @@ def test_output_is_served_from_the_cache_on_a_second_render # Change the template underneath a warm cache. The digest is memoized, so # a second render of the same key must return the cached markup. - modify_file "app/components/cacheable_component.html.erb", "
ignored
\n" do + modify_file("app/components/cacheable_component.html.erb", "
ignored
\n") do render_inline(CacheableComponent.new(title: "first")) assert_selector(".cacheable", text: "first") @@ -907,7 +935,7 @@ def test_cache_hits_preserve_the_callers_virtual_path 2.times do CacheableComponent.new(title: "same").render_in(context) - assert_equal "pages/show", context.instance_variable_get(:@virtual_path) + assert_equal("pages/show", context.instance_variable_get(:@virtual_path)) end end end @@ -920,7 +948,7 @@ def test_rejected_cached_content_preserves_the_callers_virtual_path CacheableComponent.new(title: "same").render_in(context) { "content" } end - assert_equal "pages/show", context.instance_variable_get(:@virtual_path) + assert_equal("pages/show", context.instance_variable_get(:@virtual_path)) end def test_different_cache_on_values_produce_different_output @@ -937,12 +965,12 @@ def test_cached_output_respects_the_ordered_variant_fallbacks with_caching do with_variant(:unknown, :phone, :tablet) do render_inline(CacheableVariantsComponent.new) - assert_text "Phone" + assert_text("Phone") end with_variant(:unknown, :tablet, :phone) do render_inline(CacheableVariantsComponent.new) - assert_text "Tablet" + assert_text("Tablet") end end end @@ -954,7 +982,7 @@ def test_cached_output_is_html_safe render_inline(CacheableComponent.new(title: "bold")) - assert_equal first, page.native.to_html + assert_equal(first, page.native.to_html) assert_no_selector("b") end end @@ -964,7 +992,10 @@ def test_components_without_cache_on_are_not_output_cached render_inline(CacheableParentComponent.new) assert_selector(".cacheable-child", text: "child") - modify_file "app/components/cacheable_child_component.html.erb", "changed\n" do + modify_file( + "app/components/cacheable_child_component.html.erb", + "changed\n" + ) do with_new_cache do render_inline(CacheableParentComponent.new) @@ -972,6 +1003,7 @@ def test_components_without_cache_on_are_not_output_cached end end end + ensure recompile(CacheableChildComponent) end @@ -981,7 +1013,7 @@ def test_passing_a_block_to_a_cached_component_raises render_inline(CacheableComponent.new(title: "a")) { "content" } end - assert_includes error.message, "CacheableComponent" + assert_includes(error.message, "CacheableComponent") end def test_passing_with_content_to_a_cached_component_raises @@ -995,7 +1027,7 @@ def test_setting_a_slot_on_a_cached_component_raises render_inline(CacheableSlotComponent.new(title: "a").tap { |c| c.with_header { "set" } }) end - assert_includes error.message, "CacheableSlotComponent" + assert_includes(error.message, "CacheableSlotComponent") end # A slot the component fills in for itself isn't caller-provided, so it's @@ -1011,8 +1043,10 @@ def test_default_filled_slots_are_cached with_caching do render_inline(CacheableSlotComponent.new(title: "cached")) - refute_nil Rails.cache.read( - CacheableSlotComponent.new(title: "cached").cache_key(vc_test_controller.view_context) + refute_nil( + Rails.cache.read( + CacheableSlotComponent.new(title: "cached").cache_key(vc_test_controller.view_context) + ) ) end end @@ -1020,13 +1054,13 @@ def test_default_filled_slots_are_cached def test_reading_a_default_slot_does_not_make_it_caller_supplied CacheableSlotComponent.__vc_compile(raise_errors: true) component = CacheableSlotComponent.new(title: "cached") - assert_same component.header, component.header + assert_same(component.header, component.header) with_caching do render_inline(component) assert_selector(".header", text: "default header") - refute_nil Rails.cache.read(component.cache_key(vc_test_controller.view_context)) + refute_nil(Rails.cache.read(component.cache_key(vc_test_controller.view_context))) end end @@ -1051,23 +1085,23 @@ def test_anonymous_components_are_not_registered Class.new(CacheableComponent) - assert_equal before, ViewComponent::CacheDigest.registry + assert_equal(before, ViewComponent::CacheDigest.registry) end def test_virtual_path_for_returns_nil_without_a_virtual_path - assert_nil ViewComponent::CacheDigest.virtual_path_for(Class.new(CacheableComponent)) + assert_nil(ViewComponent::CacheDigest.virtual_path_for(Class.new(CacheableComponent))) end def test_component_for_ignores_paths_outside_the_prefix - assert_nil ViewComponent::CacheDigest.component_for("integration_examples/cached_component") + assert_nil(ViewComponent::CacheDigest.component_for("integration_examples/cached_component")) end def test_component_for_returns_nil_for_unregistered_paths - assert_nil ViewComponent::CacheDigest.component_for("view_component/cache_digest/nope") + assert_nil(ViewComponent::CacheDigest.component_for("view_component/cache_digest/nope")) end def test_dependencies_are_not_scanned_for_sources_without_render - assert_empty component_dependencies_in(build_template("no calls here")) + assert_empty(component_dependencies_in(build_template("no calls here"))) end def test_dependencies_are_found_for_component_renders @@ -1085,8 +1119,8 @@ def test_template_dependencies_reuse_sources_compiled_at_boot ViewComponent::CacheDigest.compiled_source(template) end - assert_equal "precompiled", compiled - refute_equal "precompiled", ViewComponent::CacheDigest.compiled_source(template) + assert_equal("precompiled", compiled) + refute_equal("precompiled", ViewComponent::CacheDigest.compiled_source(template)) end def test_dependencies_are_found_for_components_that_did_not_opt_in @@ -1106,19 +1140,23 @@ def test_discovered_components_register_acronym_names_and_custom_virtual_paths ["view_component/cache_digest/http_untracked_component", "view_component/cache_digest/custom/untracked_child"], dependencies ) - assert_equal "HTTPUntrackedComponent", ViewComponent::CacheDigest.registry["http_untracked_component"] - assert_equal "UntrackedChildComponent", ViewComponent::CacheDigest.registry["custom/untracked_child"] - assert_equal HTTPUntrackedComponent, + assert_equal("HTTPUntrackedComponent", ViewComponent::CacheDigest.registry["http_untracked_component"]) + assert_equal("UntrackedChildComponent", ViewComponent::CacheDigest.registry["custom/untracked_child"]) + assert_equal( + HTTPUntrackedComponent, ViewComponent::CacheDigest.component_for("view_component/cache_digest/http_untracked_component") - assert_equal UntrackedChildComponent, + ) + assert_equal( + UntrackedChildComponent, ViewComponent::CacheDigest.component_for("view_component/cache_digest/custom/untracked_child") - refute_predicate HTTPUntrackedComponent, :__vc_caches_output? - refute_predicate UntrackedChildComponent, :__vc_caches_output? + ) + refute_predicate(HTTPUntrackedComponent, :__vc_caches_output?) + refute_predicate(UntrackedChildComponent, :__vc_caches_output?) end end def test_dependencies_ignore_constants_that_are_not_components - assert_empty component_dependencies_in(build_template("<%= render IntegrationExamplesController %>")) + assert_empty(component_dependencies_in(build_template("<%= render IntegrationExamplesController %>"))) end def test_dependency_discovery_works_without_any_registered_components @@ -1126,15 +1164,15 @@ def test_dependency_discovery_works_without_any_registered_components source = "<%# Template Dependency: UntrackedChildComponent %><%= render HTTPUntrackedComponent.new %>" dependencies = ActionView::DependencyTracker.find_dependencies("test/template", build_template(source), []) - assert_includes dependencies, "view_component/cache_digest/http_untracked_component" - assert_includes dependencies, "view_component/cache_digest/custom/untracked_child" - refute_predicate HTTPUntrackedComponent, :__vc_caches_output? - refute_predicate UntrackedChildComponent, :__vc_caches_output? + assert_includes(dependencies, "view_component/cache_digest/http_untracked_component") + assert_includes(dependencies, "view_component/cache_digest/custom/untracked_child") + refute_predicate(HTTPUntrackedComponent, :__vc_caches_output?) + refute_predicate(UntrackedChildComponent, :__vc_caches_output?) end end def test_templates_without_renders_are_not_compiled - ViewComponent::CacheDigest.stub(:compiled_source, ->(*) { flunk "compiled the template" }) do + ViewComponent::CacheDigest.stub(:compiled_source, -> (*) { flunk("compiled the template") }) do assert_empty( ActionView::DependencyTracker.find_dependencies("test/template", build_template("no calls here"), []) ) @@ -1150,14 +1188,23 @@ def test_static_erb_markup_is_not_compiled_for_dependencies "Hello<%= @message %>" ] - ViewComponent::CacheDigest.stub(:compiled_source, ->(*) { flunk "compiled static markup" }) do + ViewComponent::CacheDigest.stub(:compiled_source, -> (*) { flunk("compiled static markup") }) do sources.each do |source| template = build_template(source) - rails_dependencies = ActionView::DependencyTracker.method(:find_dependencies).super_method.call("test/template", template, []) - - assert_equal rails_dependencies, ActionView::DependencyTracker.find_dependencies("test/template", template, []) - assert_empty ViewComponent::CacheDigest::Resolver.instance.send( - :template_dependencies, CacheableComponent, source, :erb, "test/template" + rails_dependencies = ActionView::DependencyTracker + .method(:find_dependencies) + .super_method + .call("test/template", template, []) + + assert_equal(rails_dependencies, ActionView::DependencyTracker.find_dependencies("test/template", template, [])) + assert_empty( + ViewComponent::CacheDigest::Resolver.instance.send( + :template_dependencies, + CacheableComponent, + source, + :erb, + "test/template" + ) ) end end @@ -1166,13 +1213,19 @@ def test_static_erb_markup_is_not_compiled_for_dependencies def test_literal_template_handlers_are_not_compiled_for_dependencies source = "<%= helpers.embed(ErbComponent.new) %>" - ViewComponent::CacheDigest.stub(:compiled_source, ->(*) { flunk "compiled a literal template" }) do + ViewComponent::CacheDigest.stub(:compiled_source, -> (*) { flunk("compiled a literal template") }) do %i[raw html].each do |extension| template = build_template(source, handler: ActionView::Template.handler_for_extension(extension)) - assert_empty ActionView::DependencyTracker.find_dependencies("test/template", template, []) - assert_empty ViewComponent::CacheDigest::Resolver.instance.send( - :template_dependencies, CacheableComponent, source, extension, "test/template" + assert_empty(ActionView::DependencyTracker.find_dependencies("test/template", template, [])) + assert_empty( + ViewComponent::CacheDigest::Resolver.instance.send( + :template_dependencies, + CacheableComponent, + source, + extension, + "test/template" + ) ) end end @@ -1183,16 +1236,16 @@ def test_erb_dependency_filter_handles_many_unterminated_tags handler = ActionView::Template.handler_for_extension(:erb) Timeout.timeout(2) do - refute ViewComponent::CacheDigest.template_dependencies?(source, handler) + refute(ViewComponent::CacheDigest.template_dependencies?(source, handler)) end end def test_static_templates_keep_explicit_component_dependencies source = "<%# Template Dependency: ErbComponent %>Hello" - ViewComponent::CacheDigest.stub(:compiled_source, ->(*) { flunk "compiled a dependency comment" }) do + ViewComponent::CacheDigest.stub(:compiled_source, -> (*) { flunk("compiled a dependency comment") }) do dependencies = ActionView::DependencyTracker.find_dependencies("test/template", build_template(source), []) - assert_includes dependencies, "view_component/cache_digest/erb_component" + assert_includes(dependencies, "view_component/cache_digest/erb_component") end end @@ -1206,10 +1259,17 @@ def test_helper_component_dependencies_are_found_in_each_template_language template = build_template(source, handler: ActionView::Template.handler_for_extension(extension)) dependencies = ActionView::DependencyTracker.find_dependencies("test/template", template, []) - assert_includes dependencies, "view_component/cache_digest/erb_component" - assert_includes ViewComponent::CacheDigest::Resolver.instance.send( - :template_dependencies, CacheableComponent, source, extension, "test/template" - ), "view_component/cache_digest/erb_component" + assert_includes(dependencies, "view_component/cache_digest/erb_component") + assert_includes( + ViewComponent::CacheDigest::Resolver.instance.send( + :template_dependencies, + CacheableComponent, + source, + extension, + "test/template" + ), + "view_component/cache_digest/erb_component" + ) end end @@ -1218,10 +1278,10 @@ def test_synthetic_templates_keep_dependencies_without_recompiling source = ViewComponent::CacheDigest::Resolver.instance.source_for(CacheableParentComponent) template = build_template(source, virtual_path: virtual_path) - ViewComponent::CacheDigest.stub(:compiled_source, ->(*) { flunk "recompiled the synthetic template" }) do + ViewComponent::CacheDigest.stub(:compiled_source, -> (*) { flunk("recompiled the synthetic template") }) do dependencies = ActionView::DependencyTracker.find_dependencies(virtual_path, template, []) - assert_includes dependencies, "view_component/cache_digest/cacheable_child_component" + assert_includes(dependencies, "view_component/cache_digest/cacheable_child_component") end end @@ -1238,19 +1298,23 @@ def test_unresolved_dynamic_partial_dependencies_are_discarded each_render_tracker do sources.each do |source| dependencies = ActionView::DependencyTracker.find_dependencies( - "test/template", build_template("<%= #{source} %>"), [] + "test/template", + build_template("<%= #{source} %>"), + [] ) - assert_empty dependencies, source - assert_equal [[], []], ViewComponent::CacheDigest.renders_in(source, "test/template", view_paths: []) + assert_empty(dependencies, source) + assert_equal([[], []], ViewComponent::CacheDigest.renders_in(source, "test/template", view_paths: [])) end end end def test_existing_dynamic_partial_dependencies_are_kept - view_paths = ActionView::PathSet.new([ - ActionView::FixtureResolver.new("buttons/_button.html.erb" => "Button") - ]) + view_paths = ActionView::PathSet.new( + [ + ActionView::FixtureResolver.new("buttons/_button.html.erb" => "Button") + ] + ) source = "render @button" each_render_tracker do @@ -1279,13 +1343,19 @@ def test_unresolvable_interpolated_partial_dependencies_are_discarded each_render_tracker do sources.each do |source| dependencies = ActionView::DependencyTracker.find_dependencies( - "test/template", build_template("<%= #{source} %>"), [] + "test/template", + build_template("<%= #{source} %>"), + [] ) # Older ERB trackers leave interpolation markers, which the digestor skips. - assert_empty dependencies.reject { |path| path.include?("#") }, source + assert_empty(dependencies.reject { |path| path.include?("#") }, source) [nil, []].each do |view_paths| - assert_equal [[], []], ViewComponent::CacheDigest.renders_in(source, "test/template", view_paths: view_paths), source + assert_equal( + [[], []], + ViewComponent::CacheDigest.renders_in(source, "test/template", view_paths: view_paths), + source + ) end end end @@ -1309,7 +1379,9 @@ def test_existing_dynamic_partials_still_change_the_digest ) ActionView::Digestor.digest( - name: "test/template", format: :html, finder: ActionView::LookupContext.new([resolver]) + name: "test/template", + format: :html, + finder: ActionView::LookupContext.new([resolver]) ) end @@ -1333,39 +1405,47 @@ def test_dynamic_partial_dependencies_are_kept_for_other_variants_formats_and_lo def test_literal_wildcard_dependencies_are_kept_alongside_dynamic_renders source = "<%= render UI.button %><%= render \"buttons/\#{@kind}\" %>" - view_paths = ActionView::PathSet.new([ - ActionView::FixtureResolver.new("buttons/_button.html.erb" => "Button") - ]) + view_paths = ActionView::PathSet.new( + [ + ActionView::FixtureResolver.new("buttons/_button.html.erb" => "Button") + ] + ) each_render_tracker do - dependencies = ActionView::DependencyTracker.find_dependencies("test/template", build_template(source), view_paths) + dependencies = ActionView::DependencyTracker.find_dependencies( + "test/template", + build_template(source), + view_paths + ) assert_equal( ["buttons/button"], dependencies.map { |path| path.gsub(%r{/_}, "/") }.uniq ) - assert_empty ActionView::DependencyTracker.find_dependencies("test/template", build_template(source), []) + assert_empty(ActionView::DependencyTracker.find_dependencies("test/template", build_template(source), [])) end end def test_missing_literal_dependencies_are_kept_alongside_dynamic_renders sources = [ - '<%= render UI.button %><%= render "buttons/button" %>', - '<%= render UI.button %><%= render("buttons/_button") %>', - '<%= render UI.button %><%= render(("buttons/button")) %>', - '<%= render partial: UI.button, layout: "buttons/button" %>', - '<%= render partial: UI.button, spacer_template: "buttons/button" %>' + "<%= render UI.button %><%= render \"buttons/button\" %>", + "<%= render UI.button %><%= render(\"buttons/_button\") %>", + "<%= render UI.button %><%= render((\"buttons/button\")) %>", + "<%= render partial: UI.button, layout: \"buttons/button\" %>", + "<%= render partial: UI.button, spacer_template: \"buttons/button\" %>" ] each_render_tracker do sources.each do |source| dependencies = ActionView::DependencyTracker.find_dependencies("test/template", build_template(source), []) - assert_includes dependencies.map { |path| path.gsub(%r{/_}, "/") }, "buttons/button", source + assert_includes(dependencies.map { |path| path.gsub(%r{/_}, "/") }, "buttons/button", source) components, partials = ViewComponent::CacheDigest.renders_in( - ViewComponent::CacheDigest.compiled_source(build_template(source)), "test/template", view_paths: [] + ViewComponent::CacheDigest.compiled_source(build_template(source)), + "test/template", + view_paths: [] ) - assert_empty components - assert_equal ["buttons/button"], partials.map { |path| path.gsub(%r{/_}, "/") } + assert_empty(components) + assert_equal(["buttons/button"], partials.map { |path| path.gsub(%r{/_}, "/") }) end end end @@ -1443,14 +1523,17 @@ def test_namespaced_component_renders_do_not_log_missing_templates each_render_tracker do clear_digest_cache - ActionView::Base.logger.stub(:error, ->(message) { flunk message }) do - refute_empty ActionView::Digestor.digest( - name: "test/_template", - format: :html, - finder: ActionView::LookupContext.new([resolver]) + ActionView::Base.logger.stub(:error, -> (message) { flunk(message) }) do + refute_empty( + ActionView::Digestor.digest( + name: "test/_template", + format: :html, + finder: ActionView::LookupContext.new([resolver]) + ) ) end end + ensure clear_digest_cache end @@ -1474,10 +1557,10 @@ def test_explicit_dependencies_named_like_inferred_component_partials_are_kept def test_unopted_component_digest_is_computable_without_registration with_registry({}) do - refute_predicate UntrackedChildComponent, :__vc_caches_output? + refute_predicate(UntrackedChildComponent, :__vc_caches_output?) - refute_empty UntrackedChildComponent.cache_digest - assert_equal "UntrackedChildComponent", ViewComponent::CacheDigest.registry["custom/untracked_child"] + refute_empty(UntrackedChildComponent.cache_digest) + assert_equal("UntrackedChildComponent", ViewComponent::CacheDigest.registry["custom/untracked_child"]) end end @@ -1489,18 +1572,21 @@ def test_precompute_serves_digests_without_reading_source_files ViewComponent::CacheDigest.precompute!(components) - assert_equal ViewComponent::CacheDigest::Resolver.instance.source_for(CacheableChildComponent), + assert_equal( + ViewComponent::CacheDigest::Resolver.instance.source_for(CacheableChildComponent), CacheableChildComponent.__vc_cache_digest_source - assert_predicate CacheableChildComponent.__vc_cache_digest_source, :frozen? + ) + assert_predicate(CacheableChildComponent.__vc_cache_digest_source, :frozen?) finder = ActionView::LookupContext.new(ActionController::Base.view_paths, formats: [:html]) - assert_equal expected, finder.digest_cache["view_component/cache_digest/cacheable_parent_component.html"] + assert_equal(expected, finder.digest_cache["view_component/cache_digest/cacheable_parent_component.html"]) # Rebuilding the tree uses the stored sources rather than the files on disk. clear_digest_cache - File.stub(:read, ->(*) { flunk "read a source file" }) do - assert_equal expected, CacheableParentComponent.cache_digest + File.stub(:read, -> (*) { flunk("read a source file") }) do + assert_equal(expected, CacheableParentComponent.cache_digest) end + ensure components.each { |component| component.__vc_cache_digest_source = nil } clear_digest_cache @@ -1509,9 +1595,9 @@ def test_precompute_serves_digests_without_reading_source_files def test_resolver_is_identified_by_class resolver = ViewComponent::CacheDigest::Resolver.instance - assert_equal "ViewComponent::CacheDigest::Resolver", resolver.to_s - assert_equal "ViewComponent::CacheDigest::Resolver", resolver.to_path - assert_equal resolver, ViewComponent::CacheDigest::Resolver.new + assert_equal("ViewComponent::CacheDigest::Resolver", resolver.to_s) + assert_equal("ViewComponent::CacheDigest::Resolver", resolver.to_path) + assert_equal(resolver, ViewComponent::CacheDigest::Resolver.new) end def test_install_is_idempotent @@ -1526,7 +1612,7 @@ def test_install_is_idempotent def test_install_leaves_view_paths_alone ViewComponent::CacheDigest.install! - assert ActionController::Base.view_paths.all? { |path| path.is_a?(ActionView::FileSystemResolver) } + assert(ActionController::Base.view_paths.all? { |path| path.is_a?(ActionView::FileSystemResolver) }) end private @@ -1582,6 +1668,7 @@ def each_render_tracker ActionView::DependencyTracker.register_tracker(:erb, tracker) yield end + ensure ActionView::DependencyTracker.instance_variable_set(:@trackers, trackers) end diff --git a/test/sandbox/test/collection_test.rb b/test/sandbox/test/collection_test.rb index bc2147024..44164599f 100644 --- a/test/sandbox/test/collection_test.rb +++ b/test/sandbox/test/collection_test.rb @@ -28,12 +28,12 @@ def setup end def test_collection_has_a_size - assert_equal 2, @collection.size - assert_equal 2, @collection.count + assert_equal(2, @collection.size) + assert_equal(2, @collection.count) end def test_is_a_collection_of_view_components - assert_equal [ProductComponent], @collection.map(&:class).uniq + assert_equal([ProductComponent], @collection.map(&:class).uniq) end def test_supports_components_with_keyword_args @@ -43,7 +43,7 @@ def test_supports_components_with_keyword_args end def test_collection_without_iteration_arguments_does_not_build_an_iterator - ActionView::PartialIteration.stub(:new, ->(*) { flunk "Unused collection iterator was allocated" }) do + ActionView::PartialIteration.stub(:new, -> (*) { flunk("Unused collection iterator was allocated") }) do render_inline(ProductComponent.with_collection(@products)) end @@ -61,9 +61,9 @@ def test_collection_escapes_html_unsafe_around_render_output render_inline(UnsafeAroundRenderComponent.with_collection([1, 2])) end - refute_includes @rendered_content, "