### Verify Ruby Installation Source: https://github.com/whitesmith/rubycritic/wiki/Building-your-own-Code-Climate After installing Ruby using a preferred method (like RVM or rbenv), this command verifies that the installation was successful and that Ruby is accessible in the system's PATH. It's a simple check to ensure Ruby is ready for gem installation. ```bash ruby --version ``` -------------------------------- ### Verify Git Installation Source: https://github.com/whitesmith/rubycritic/wiki/Building-your-own-Code-Climate This command confirms that Git has been successfully installed on the Build Server. Jenkins requires Git to clone repositories for analysis, so verifying its installation is a critical step. ```bash git --version ``` -------------------------------- ### Install RubyCritic Gem Source: https://github.com/whitesmith/rubycritic/blob/main/README.md Installs the RubyCritic gem using the standard RubyGems package manager. This is the most straightforward way to get started with RubyCritic. ```bash #!/bin/bash gem install rubycritic ``` -------------------------------- ### RubyCritic CLI Usage Examples Source: https://context7.com/whitesmith/rubycritic/llms.txt Demonstrates various command-line interface commands for installing RubyCritic, analyzing code paths, specifying output formats, and configuring CI modes. ```bash gem install rubycritic rubycritic rubycritic app lib/foo.rb rubycritic --format json rubycritic --mode-ci --branch main rubycritic --minimum-score 95.0 rubycritic --format console --format json --format html rubycritic --path tmp/custom_report rubycritic --no-browser rubycritic --mode-ci --branch production --maximum-decrease 5.0 ``` -------------------------------- ### Install Bundler and RubyCritic Gems Source: https://github.com/whitesmith/rubycritic/wiki/Building-your-own-Code-Climate This command installs the necessary Ruby gems: Bundler for managing gem dependencies and RubyCritic for code analysis. These gems are essential for the project's analysis pipeline. ```bash gem install bundler rubycritic ``` -------------------------------- ### Switch to Jenkins User Account Source: https://github.com/whitesmith/rubycritic/wiki/Building-your-own-Code-Climate This command allows you to switch to the Jenkins user account on the Build Server, which is necessary for performing subsequent installations and configurations under the correct user privileges. It is a prerequisite for many setup steps. ```bash sudo su - jenkins ``` -------------------------------- ### Execute Shell Script for Ruby Project Build Source: https://github.com/whitesmith/rubycritic/wiki/Building-your-own-Code-Climate This script installs project dependencies using Bundler and runs project tests using Rake. It's a common setup for continuous integration in Ruby projects. ```bash bundle rake ``` -------------------------------- ### Get RubyCritic Help Source: https://github.com/whitesmith/rubycritic/blob/main/README.md Displays the full list of available command-line options and their descriptions for RubyCritic. ```bash rubycritic --help ``` -------------------------------- ### Execute Shell Script for Ruby Project Build with RVM Source: https://github.com/whitesmith/rubycritic/wiki/Building-your-own-Code-Climate This script demonstrates testing a Ruby project across different Ruby versions using RVM. It explicitly sets the Ruby version, installs dependencies, runs tests, and then switches to another version for further testing. The `#!/bin/bash` shebang is crucial for correct execution. ```bash #!/bin/bash rvm use 1.9.3 bundle rake rvm use 2.1 bundle rake ``` -------------------------------- ### Execute Shell Script for RubyGem Build Source: https://github.com/whitesmith/rubycritic/blob/main/docs/building-own-code-climate.md This script installs project dependencies using Bundler and runs tests using Rake. It's a basic setup for building and testing a Ruby project within a Jenkins environment. ```bash #!/bin/bash bundle rake ``` -------------------------------- ### RubyCritic YAML Configuration Example Source: https://context7.com/whitesmith/rubycritic/llms.txt Shows a sample .rubycritic.yml file for defining project-specific analysis settings, including CI mode, output paths, and formats. ```yaml # .rubycritic.yml - place in project root mode_ci: enabled: true branch: 'production' branch: 'production' path: '/tmp/rubycritic_reports' coverage_path: '/tmp/coverage' threshold_score: 10 deduplicate_symlinks: true suppress_ratings: false no_browser: true formats: - console - json - html minimum_score: 95.0 paths: - 'app/controllers/' - 'app/models/' - 'lib/**' ``` -------------------------------- ### Execute RubyCritic Analysis Source: https://github.com/whitesmith/rubycritic/wiki/Building-your-own-Code-Climate This command executes the RubyCritic gem to analyze the `app` and `lib` directories of a Ruby project. The output is typically HTML reports that need to be archived. ```bash rubycritic app lib ``` -------------------------------- ### RubyCritic Configuration File Example Source: https://github.com/whitesmith/rubycritic/blob/main/README.md An example of a `.rubycritic.yml` configuration file. This file allows you to set various analysis options such as CI mode, branch, paths, score thresholds, and output formats. ```yaml mode_ci: enabled: true # default is false branch: 'production' # default is main branch: 'production' # default is main path: '/tmp/mycustompath' # Set path where report will be saved (tmp/rubycritic by default) coverage_path: '/tmp/coverage' # Set path where SimpleCov coverage will be saved (./coverage by default) threshold_score: 10 # default is 0 deduplicate_symlinks: true # default is false suppress_ratings: true # default is false no_browser: true # default is false formats: # Available values are: html, json, console, lint. Default value is html. - console minimum_score: 95 # default is 0 paths: # Files to analyse. Churn calculation is scoped to these files when using Git SCM. - 'app/controllers/' - 'app/models/' - 'lib/**' # Wildcard patterns are supported (excludes tmp directories automatically) ``` -------------------------------- ### Test SSH Connection to GitHub Source: https://github.com/whitesmith/rubycritic/wiki/Building-your-own-Code-Climate This command tests the SSH connection to GitHub using the Jenkins user's SSH keys. It ensures that Jenkins can securely connect to GitHub to clone private repositories without requiring passwords. ```bash ssh -T git@github.com ``` -------------------------------- ### Basic RubyCritic Rake Task Setup Source: https://github.com/whitesmith/rubycritic/blob/main/README.md This is the simplest way to integrate RubyCritic into your Rake tasks. It requires the RubyCritic Rake task library and initializes a default task. ```ruby require "rubycritic/rake_task" RubyCritic::RakeTask.new ``` -------------------------------- ### Multiple RubyCritic Rake Tasks for Different Configurations Source: https://github.com/whitesmith/rubycritic/blob/main/README.md This example illustrates how to define multiple RubyCritic Rake tasks, useful for managing different configurations (e.g., local vs. CI). Each task can be given a unique name and description, and specific options can be applied to each. ```ruby # for local RubyCritic::RakeTask.new("local", "Run RubyCritic (local configuration)" do |task| # ... end # for CI RubyCritic::RakeTask.new("ci", "Run RubyCritic (CI configuration)" do |task| task.options = "--mode-ci" # ... end ``` -------------------------------- ### Advanced RubyCritic Rake Task Configuration Source: https://github.com/whitesmith/rubycritic/blob/main/README.md This example demonstrates a more sophisticated Rake task configuration for RubyCritic. It allows customization of the task name, source file paths, output options (like CI mode and JSON format), verbosity, and error handling. ```ruby RubyCritic::RakeTask.new do |task| # Name of RubyCritic task. Defaults to :rubycritic. task.name = 'something_special' # Glob pattern to match source files. Defaults to FileList['.']. task.paths = FileList['vendor/**/*.rb'] # You can pass all the options here in that are shown by "rubycritic -h" except for # "-p / --path" since that is set separately. Defaults to ''. task.options = '--mode-ci --format json' # Defaults to false task.verbose = true # Fail the Rake task if RubyCritic doesn't pass. Defaults to true task.fail_on_error = true end ``` -------------------------------- ### RubyCritic Programmatic API Usage Source: https://context7.com/whitesmith/rubycritic/llms.txt Provides examples of using RubyCritic programmatically within Ruby applications, including basic execution, direct configuration, and accessing analysis results. ```ruby require 'rubycritic/cli/application' require 'rubycritic/configuration' require 'rubycritic/command_factory' require 'rubycritic/analysers_runner' # Basic programmatic execution app = RubyCritic::Cli::Application.new(['app', 'lib']) exit_status = app.execute # Direct configuration and analysis options = { mode: :default, paths: ['app', 'lib'], formats: [:json, :html], root: 'tmp/rubycritic', minimum_score: 90.0, suppress_ratings: false, no_browser: true } RubyCritic::Config.set(options) command = RubyCritic::CommandFactory.create(options) reporter = command.execute # Access analysis results puts "Status: #{reporter.status_message}" puts "Score: #{reporter.score}" puts "Exit status: #{reporter.status}" # Direct analyser access paths = ['app/models', 'lib'] runner = RubyCritic::AnalysersRunner.new(paths) analysed_modules = runner.run # Examine individual modules analysed_modules.each do |mod| puts "File: #{mod.path}" puts "Rating: #{mod.rating}" puts "Complexity: #{mod.complexity}" puts "Churn: #{mod.churn}" puts "Smells count: #{mod.smells_count}" puts "Cost: #{mod.cost}" mod.smells.each do |smell| puts " - #{smell.type} at line #{smell.locations.first.line}" end end # Calculate overall score overall_score = analysed_modules.score puts "Overall quality score: #{overall_score}" ``` -------------------------------- ### Generating RubyCritic Reports (HTML, JSON, Console, Lint) Source: https://context7.com/whitesmith/rubycritic/llms.txt Provides a comprehensive example of generating various report formats using RubyCritic's Reporter and specific generator classes. It covers configuring output formats and generating reports both automatically and individually. ```ruby require 'rubycritic/reporter' require 'rubycritic/generators/html_report' require 'rubycritic/generators/json_report' require 'rubycritic/generators/console_report' require 'rubycritic/generators/lint_report' # Analyze code first paths = ['app', 'lib'] runner = RubyCritic::AnalysersRunner.new(paths) analysed_modules = runner.run # Configure output formats RubyCritic::Config.set({ formats: [:html, :json, :console, :lint], root: 'tmp/quality_reports', no_browser: false }) # Generate all configured reports RubyCritic::Reporter.generate_report(analysed_modules) # Or generate specific reports manually html_generator = RubyCritic::Generator::HtmlReport.new(analysed_modules) html_generator.generate_report # Output: "New critique at tmp/quality_reports/overview.html" json_generator = RubyCritic::Generator::JsonReport.new(analysed_modules) json_generator.generate_report # Creates: tmp/quality_reports/report.json console_generator = RubyCritic::Generator::ConsoleReport.new(analysed_modules) console_generator.generate_report # Prints colored output to stdout lint_generator = RubyCritic::Generator::LintReport.new(analysed_modules) lint_generator.generate_report # Prints lint-style warnings to stdout # The JSON report structure # { # "analysed_modules": [ # { # "name": "User", # "path": "app/models/user.rb", # "smells": [...], # "churn": 23, # "complexity": 45.3, # "duplication": 5, # "methods_count": 12, # "cost": 8.8, # "rating": "C" # } # ], # "score": 87.5 # } ``` -------------------------------- ### Configure Jenkins Pipeline for RubyCritic Code Review Source: https://github.com/whitesmith/rubycritic/blob/main/docs/jenkins-pr-reviews.md This Jenkinsfile configures a CI/CD pipeline to execute RubyCritic, generate lint-style reports, and post violation comments back to GitHub Pull Requests. It assumes RubyCritic is installed and configured to output in a GoLint-compatible format. The `ViolationsToGitHubRecorder` step uses the generated report to comment on changed code lines within the PR. ```groovy pipeline { agent any stages { stage('Build') { steps { // Install gems etc. } } stage('Test') { steps { parallel tests: { // We are running tests and code_checks in parallel to shorten build times sh 'bundle exec rspec' }, code_checks: { sh 'bundle exec rubycritic -f lint' } } } stage('Package / Deploy') { steps { parallel deploy: { // Create Docker image / deploy via Capistrano / ... }, publish_code_review: { step([ $class: 'ViolationsToGitHubRecorder', config: [ repositoryName: 'your_project_name', pullRequestId: env.CHANGE_ID, // The CHANGE_ID env variable will be set to the PR ID by Jenkins createSingleFileComments: true, // Create one comment per violation commentOnlyChangedContent: true, // Only comment on lines that have changed keepOldComments: false, violationConfigs: [ [ pattern: '.*/lint\.txt$', parser: 'GOLINT', reporter: 'RubyCritic' ], // RubyCritic will output a lint.txt file in GoLint compatible format ] ]]) } } } } } ``` -------------------------------- ### Highlighting Duplicated Code Blocks Source: https://github.com/whitesmith/rubycritic/wiki/Roadmap A proposed enhancement to highlight entire blocks of duplicated code, rather than just the start. This may necessitate rewriting the Flay integration using the 'parser' gem instead of 'ruby_parser'. ```ruby # Potential future implementation using the 'parser' gem require 'parser' def analyze_duplication_with_parser(code) ast = Parser::CurrentRuby.parse(code) # ... AST traversal and duplication detection logic ... end ``` -------------------------------- ### Change Jenkins User Password Source: https://github.com/whitesmith/rubycritic/wiki/Building-your-own-Code-Climate Use this command if you do not know the Jenkins user's password. It prompts you to set a new password for the Jenkins user, ensuring you can log in and perform necessary operations. This is crucial for security and access. ```bash sudo passwd jenkins ``` -------------------------------- ### Accessing Analysis Collection Source: https://context7.com/whitesmith/rubycritic/llms.txt Demonstrates how to access the analysed modules collection and retrieve overall quality score and file count from RubyCritic. ```ruby collection = runner.analysed_modules collection.score # Overall quality score (0-100) collection.count # Number of analyzed files ``` -------------------------------- ### Integrate Custom Analyzers with RubyCritic Source: https://context7.com/whitesmith/rubycritic/llms.txt Extend RubyCritic's analysis capabilities by integrating custom analyzers. This section explains the default analyzer pipeline and demonstrates how to use `AnalysersRunner` to run the analysis process on specified paths, generating a collection of analyzed modules. ```ruby require 'rubycritic/analysers_runner' require 'rubycritic/core/analysed_modules_collection' # Understanding the analyzer pipeline # RubyCritic runs analyzers in sequence: # 1. FlaySmells - duplicate code detection # 2. FlogSmells - complexity analysis # 3. ReekSmells - code smell detection # 4. Complexity - calculate complexity metrics # 5. Attributes - extract module attributes # 6. Churn - calculate file change frequency # 7. Coverage - extract test coverage data # Running analyzers paths = ['app/models', 'lib'] runner = RubyCritic::AnalysersRunner.new(paths) # This builds collection and runs all analyzers analysed_modules = runner.run ``` -------------------------------- ### Source Control Integration with RubyCritic Source: https://context7.com/whitesmith/rubycritic/llms.txt Shows how to use RubyCritic's base source control system interface to check for revisions and count commits for a specific file. ```ruby require 'rubycritic/source_control_systems/base' scs = RubyCritic::SourceControlSystem::Base.create if scs.has_revision? commits = scs.revisions_count('app/models/user.rb') puts "File has #{commits} commits" end ``` -------------------------------- ### Run Rubycritic with Custom Formatter via Command Line Source: https://github.com/whitesmith/rubycritic/blob/main/docs/formatters.md This shell command demonstrates how to run Rubycritic with a custom formatter from the command line when the formatter is packaged as a gem. It specifies the require path and the fully qualified classname of the formatter, separated by a colon. ```shell gem install my_formatter_gem rubycritic --custom-format my_formatter:MyFormatter ``` -------------------------------- ### Configuration API Source: https://context7.com/whitesmith/rubycritic/llms.txt Configure RubyCritic programmatically by setting various options such as mode, output paths, formats, and more. ```APIDOC ## Configuration API ### Description Configuring RubyCritic programmatically. Access and set global configuration options to customize the analysis behavior and output. ### Method `RubyCritic::Config.set(options)` ### Endpoint N/A (Global Configuration) ### Parameters - **options** (Hash) - Required - A hash containing configuration options. - **mode** (:symbol) - Optional - Analysis mode (:default, :ci, :compare). - **root** (String) - Optional - Report output directory. - **paths** (Array) - Optional - Files/directories to analyze. - **formats** (Array) - Optional - Output formats (:html, :json, :console). - **formatters** (Array) - Optional - Custom formatters. - **minimum_score** (Float) - Optional - Minimum acceptable score. - **threshold_score** (Integer) - Optional - Max score decrease for branch comparison. - **deduplicate_symlinks** (Boolean) - Optional - De-duplicate symlinked files. - **suppress_ratings** (Boolean) - Optional - Hide letter grades. - **no_browser** (Boolean) - Optional - Don't auto-open browser. - **coverage_path** (String) - Optional - SimpleCov coverage path. - **base_branch** (String) - Optional - Base branch for comparison. - **feature_branch** (String) - Optional - Feature branch for comparison. - **churn_after** (String) - Optional - Calculate churn after this date (YYYY-MM-DD). - **ruby_extensions** (Array) - Optional - File extensions to analyze. ### Request Example ```ruby require 'rubycritic/configuration' options = { mode: :ci, root: 'tmp/rubycritic', paths: ['app', 'lib'], formats: [:html, :json, :console], no_browser: true, base_branch: 'main', feature_branch: 'feature-x', churn_after: '2024-01-01', ruby_extensions: ['.rb', '.rake'] } RubyCritic::Config.set(options) ``` ### Response #### Success Response (200) Configuration is updated. Access values using `RubyCritic::Config.`. #### Response Example ```ruby # Accessing configuration values: RubyCritic::Config.mode # => :ci RubyCritic::Config.root # => "/full/path/tmp/rubycritic" RubyCritic::Config.formats # => [:html, :json, :console] RubyCritic::Config.no_browser # => true # Checking configuration state: RubyCritic::Config.source_control_present? # => true/false RubyCritic::Config.compare_branches_mode? # => true if mode is :ci or :compare_branches RubyCritic::Config.build_mode? # => true if browser disabled and in comparison mode ``` ``` -------------------------------- ### Custom Analysis Workflow with Revision Comparison Source: https://context7.com/whitesmith/rubycritic/llms.txt Illustrates a custom analysis workflow using RubyCritic's RevisionComparator to determine the status (new, modified, unchanged) of analyzed modules. ```ruby require 'rubycritic/revision_comparator' analysed_modules = RubyCritic::AnalysersRunner.new(paths).run comparator = RubyCritic::RevisionComparator.new(paths) comparator.statuses = analysed_modules # This marks each module as :new, :modified, or :unchanged analysed_modules.each do |mod| puts "#{mod.path}: #{mod.status}" end ``` -------------------------------- ### Configure RubyCritic Programmatically Source: https://context7.com/whitesmith/rubycritic/llms.txt Learn how to configure RubyCritic's behavior and analysis settings programmatically. This involves accessing the global configuration object and setting various options such as analysis paths, output formats, reporting directories, and comparison modes for branch analysis. ```ruby require 'rubycritic/configuration' # Access global configuration config = RubyCritic::Config.configuration # Set configuration options options = { mode: :ci, # :default, :ci, :compare root: 'tmp/rubycritic', # Report output directory paths: ['app', 'lib'], # Files/directories to analyze formats: [:html, :json, :console], # Output formats formatters: [], # Custom formatters minimum_score: 90.0, # Minimum acceptable score threshold_score: 5, # Max score decrease for branch comparison deduplicate_symlinks: true, # De-duplicate symlinked files suppress_ratings: false, # Hide letter grades no_browser: true, # Don't auto-open browser coverage_path: './coverage', # SimpleCov coverage path base_branch: 'main', # Base branch for comparison feature_branch: 'feature-x', # Feature branch for comparison churn_after: '2024-01-01', # Calculate churn after this date ruby_extensions: ['.rb', '.rake'] # File extensions to analyze } RubyCritic::Config.set(options) # Access configuration values RubyCritic::Config.mode # => :ci RubyCritic::Config.root # => "/full/path/tmp/rubycritic" RubyCritic::Config.formats # => [:html, :json, :console] RubyCritic::Config.no_browser # => true # Check configuration state RubyCritic::Config.source_control_present? # => true/false RubyCritic::Config.compare_branches_mode? # => true if mode is :ci or :compare_branches RubyCritic::Config.build_mode? # => true if browser disabled and in comparison mode ``` -------------------------------- ### RubyCritic CLI with Minimum Score Option Source: https://github.com/whitesmith/rubycritic/blob/main/docs/building-own-code-climate.md This command demonstrates using the `--minimum-score` option with RubyCritic. It causes the tool to exit with an error status if the calculated code quality score falls below the specified threshold, enabling CI jobs to fail early. ```bash rubycritic --minimum-score 80 app lib ``` -------------------------------- ### Module Analysis Properties and Metrics Source: https://context7.com/whitesmith/rubycritic/llms.txt Access detailed properties and calculated metrics for a given module analysis. This includes information about the module's name, path, file details, line count, complexity, method counts, churn, duplication, coverage, and code smells. ```APIDOC ## Module Analysis Properties and Metrics ### Description Access detailed properties and calculated metrics for a given module analysis. This includes information about the module's name, path, file details, line count, complexity, method counts, churn, duplication, coverage, and code smells. ### Method N/A (Object Property Access) ### Endpoint N/A (Object Property Access) ### Parameters None ### Request Example ```ruby # Assuming module_analysis is an instance of a RubyCritic analysis object module_analysis.name # => "User" module_analysis.path # => "app/models/user.rb" module_analysis.file_name # => "user.rb" module_analysis.file_location # => "app/models" module_analysis.line_count # => 150 # Metrics module_analysis.complexity # => 45.3 module_analysis.complexity_per_method # => 7.5 or "N/A" module_analysis.methods_count # => 12 module_analysis.churn # => 23 module_analysis.duplication # => 5 module_analysis.coverage # => 87.5 # Calculated values module_analysis.cost # => 12.8 (smells cost + complexity/25) module_analysis.rating # => Rating<"C"> module_analysis.coverage_rating # => Rating<"A"> # Smells inspection module_analysis.smells_count # => 8 module_analysis.smells? # => true module_analysis.smells.each do |smell| puts "#{smell.type}: #{smell.message}" smell.locations.each do |loc| puts " at #{loc.line}:#{loc.column}" end end ``` ### Response #### Success Response (200) Properties and metrics are returned as Ruby objects or primitive types. #### Response Example ```ruby # Example output for specific properties: # "User" # "app/models/user.rb" # 150 # 45.3 # 12 # 5 # 87.5 # 12.8 # Rating<"C"> # Rating<"A"> # 8 # true ``` ``` -------------------------------- ### Configuration with .rubycritic.yml Source: https://github.com/whitesmith/rubycritic/wiki/Roadmap Implementation of a configuration file, likely named '.rubycritic.yml', to allow users to customize RubyCritic's behavior. This includes options for quiet/verbose modes, file exclusion, and date range for churn calculations. ```yaml quiet: true verbose: false exclude: - 'vendor/**' - 'db/**' churn_days: 365 ``` -------------------------------- ### Access RubyCritic Module Properties Source: https://context7.com/whitesmith/rubycritic/llms.txt Retrieve various properties and metrics of a Ruby module analyzed by RubyCritic. This includes basic information like name and path, code metrics such as complexity and method count, and calculated values like cost and rating. It also demonstrates how to inspect smells and export analysis results. ```ruby # Access module properties module_analysis.name # => "User" module_analysis.path # => "app/models/user.rb" module_analysis.file_name # => "user.rb" module_analysis.file_location # => "app/models" module_analysis.line_count # => 150 # Metrics module_analysis.complexity # => 45.3 module_analysis.complexity_per_method # => 7.5 or "N/A" module_analysis.methods_count # => 12 module_analysis.churn # => 23 module_analysis.duplication # => 5 module_analysis.coverage # => 87.5 # Calculated values module_analysis.cost # => 12.8 (smells cost + complexity/25) module_analysis.rating # => Rating<"C"> module_analysis.coverage_rating # => Rating<"A"> # Smells inspection module_analysis.smells_count # => 8 module_analysis.smells? # => true module_analysis.smells.each do |smell| puts "#{smell.type}: #{smell.message}" smell.locations.each do |loc| puts " at #{loc.line}:#{loc.column}" end end # Get smells at specific location location = RubyCritic::Location.new("app/models/user.rb", 42) smells_at_line = module_analysis.smells_at_location(location) # Export to hash/JSON hash_data = module_analysis.to_h # => {name: "User", path: "app/models/user.rb", smells: [...], # churn: 23, complexity: 45.3, cost: 12.8, rating: "C"} json_data = module_analysis.to_json ``` -------------------------------- ### Run RubyCritic Analysis Source: https://github.com/whitesmith/rubycritic/blob/main/README.md Executes RubyCritic to analyze Ruby files. By default, it analyzes all Ruby files in the current directory. You can also specify specific files or directories to include in the analysis. ```bash rubycritic rubycritic app lib/foo.rb ``` -------------------------------- ### RubyCritic Rake Task Integration Source: https://context7.com/whitesmith/rubycritic/llms.txt Illustrates how to integrate RubyCritic into Rake workflows for automated code quality checks, including basic and advanced configurations. ```ruby # Rakefile require 'rubycritic/rake_task' # Simple task with defaults RubyCritic::RakeTask.new # Advanced configuration RubyCritic::RakeTask.new do |task| task.name = 'quality_check' task.paths = FileList['app/**/*.rb', 'lib/**/*.rb'] task.options = '--mode-ci --format json --minimum-score 90' task.verbose = true task.fail_on_error = true end # Multiple tasks for different environments RubyCritic::RakeTask.new('local', 'Run RubyCritic locally') do |task| task.paths = FileList['app/**/*.rb'] task.options = '--no-browser' task.fail_on_error = false end RubyCritic::RakeTask.new('ci', 'Run RubyCritic for CI') do |task| task.paths = FileList['app/**/*.rb', 'lib/**/*.rb'] task.options = '--mode-ci --format json --minimum-score 95' task.verbose = true end # Run tasks # $ rake quality_check # $ rake local # $ rake ci ``` -------------------------------- ### RubyCritic AnalysedModule Core API (Conceptual) Source: https://context7.com/whitesmith/rubycritic/llms.txt Shows the required imports for working with the core AnalysedModule and Rating classes in RubyCritic, used for examining individual code analysis results. ```ruby require 'rubycritic/core/analysed_module' require 'rubycritic/core/rating' # AnalysedModule represents a single Ruby file's analysis # Typically obtained from AnalysersRunner, not created directly ``` -------------------------------- ### Export to Hash/JSON Source: https://context7.com/whitesmith/rubycritic/llms.txt Convert the analysis results into a Hash or JSON format for easier data manipulation and external use. ```APIDOC ## Export to Hash/JSON ### Description Convert the analysis results of a module into a Hash or JSON string representation. ### Method `module_analysis.to_h`, `module_analysis.to_json` ### Endpoint N/A (Object Method) ### Parameters None ### Request Example ```ruby # Assuming module_analysis is an instance of a RubyCritic analysis object hash_data = module_analysis.to_h # => {name: "User", path: "app/models/user.rb", smells: [...], churn: 23, complexity: 45.3, cost: 12.8, rating: "C"} json_data = module_analysis.to_json ``` ### Response #### Success Response (200) Returns a Hash or a JSON string representing the module analysis data. #### Response Example ```json { "name": "User", "path": "app/models/user.rb", "smells": [ { "type": "ExampleSmell", "message": "This is an example smell.", "locations": [ { "line": 42, "column": 5 } ] } ], "churn": 23, "complexity": 45.3, "cost": 12.8, "rating": "C" } ``` ``` -------------------------------- ### Custom Analyzer Integration Source: https://context7.com/whitesmith/rubycritic/llms.txt Integrate custom analyzers into RubyCritic's pipeline to extend its analysis capabilities. ```APIDOC ## Custom Analyzer Integration ### Description Extending RubyCritic with custom analyzers. Understanding the analyzer pipeline and how to run them. RubyCritic runs analyzers in sequence: 1. FlaySmells - duplicate code detection 2. FlogSmells - complexity analysis 3. ReekSmells - code smell detection 4. Complexity - calculate complexity metrics 5. Attributes - extract module attributes 6. Churn - calculate file change frequency 7. Coverage - extract test coverage data ### Method `RubyCritic::AnalysersRunner.new(paths).run` ### Endpoint N/A (Analysis Execution) ### Parameters - **paths** (Array) - Required - An array of file paths or directories to analyze. ### Request Example ```ruby require 'rubycritic/analysers_runner' require 'rubycritic/core/analysed_modules_collection' paths = ['app/models', 'lib'] runner = RubyCritic::AnalysersRunner.new(paths) # This builds collection and runs all analyzers analysed_modules = runner.run ``` ### Response #### Success Response (200) Returns an `AnalysedModulesCollection` object containing the results of all analyzers. #### Response Example ```ruby # analysed_modules is an instance of RubyCritic::AnalysedModulesCollection # It contains a collection of analysed module objects. ``` -------------------------------- ### RubyCritic Rating System Source: https://context7.com/whitesmith/rubycritic/llms.txt Understand how ratings are calculated based on cost values and the thresholds used for A, B, C, D, and F ratings. ```APIDOC ## Rating System ### Description Understand and using the rating conversion system. Ratings are calculated from cost values, where Cost = sum of smell costs + (complexity / 25). ### Method N/A (Class Method) ### Endpoint N/A (Class Method) ### Parameters None ### Request Example ```ruby require 'rubycritic/core/rating' # Rating thresholds: # A: cost <= 2 # B: cost <= 4 # C: cost <= 8 # D: cost <= 16 # F: cost > 16 rating_a = RubyCritic::Rating.from_cost(1.5) # => "A" rating_b = RubyCritic::Rating.from_cost(3.2) # => "B" rating_c = RubyCritic::Rating.from_cost(6.8) # => "C" rating_d = RubyCritic::Rating.from_cost(12.0) # => "D" rating_f = RubyCritic::Rating.from_cost(20.5) # => "F" # Using ratings puts rating_a.to_s # => "A" puts rating_a.to_h # => "A" puts rating_a.to_json # => "\"A\"" # Practical example with module module_complexity = 75.0 smell_costs = [2.0, 1.5, 0.8, 1.2] # Individual smell costs total_cost = smell_costs.sum + (module_complexity / 25.0) # total_cost = 5.5 + 3.0 = 8.5 rating = RubyCritic::Rating.from_cost(total_cost) puts rating # => "D" ``` ### Response #### Success Response (200) Returns a RubyCritic::Rating object or its string representation. #### Response Example ```ruby # "A" # "B" # "C" # "D" # "F" ``` ```