RubyCritic Documentation

repository·main·Indexed 25 days ago

https://github.com/whitesmith/rubycritic

A quality reporting tool for Ruby that wraps static analysis gems including Reek, Flay, and Flog. It provides a comprehensive overview of code health through metrics such as Score, Churn, Complexity, and Rating. RubyCritic supports CLI usage, Rake task integration, custom formatters, and CI/CD integration with Jenkins and GitHub.

Tokens
5.6K
Snippets
10
Records
36
Agent score
86%

What's inside RubyCritic

  1. Understand RubyCritic core metrics

    main

    RubyCritic provides a quality report by wrapping static analysis gems like Reek, Flay, and Flog. It calculates four key metrics to help you judge the 'odorousness' of your Ruby code:

    • Score: A value from 0 to 100 representing overall code quality (higher is better).
    • Churn: The number of times a file has been committed.
    • Complexity: The amount of 'pain' in the code, calculated using Flog's ABC (Assignments, Branches, Calls) metric.
    • Rating: A letter grade from A (best) to F (worst) assigned to each file.
    • Cost: A non-negative number where higher values indicate worse code smells. This value is used to determine the Rating and the overall Score.
  2. Integrate RubyCritic with Jenkins for Pull Request reviews

    main

    You can use RubyCritic to automatically comment on GitHub Pull Requests via Jenkins by using the Violation Comments to GitHub Jenkins Plugin.

    To make this work, you must configure RubyCritic to output in the lint format, which is compatible with the plugin's GOLINT parser. This allows the plugin to read the lint.txt file generated by RubyCritic and post comments directly to the PR.

    Prerequisites

    1. Jenkins Plugin: Install the Violation Comments to GitHub Jenkins Plugin via Manage Jenkins > Manage Plugins > Available.
    2. RubyCritic Output: Ensure RubyCritic is executed with the -f lint flag to produce a compatible format.
    pipeline {
      agent any
    
      stages {
        stage('Build') {
          steps {
            // Install gems etc.
          }
        }
        stage('Test') {
          steps {
            parallel tests: {
              sh 'bundle exec rspec'
            },
            code_checks: {
              sh 'bundle exec rubycritic -f lint'
            }
          }
        }
        stage('Package / Deploy') {
          steps {
            parallel deploy: {
              // ...
            },
            publish_code_review: {
              step([
                $class: 'ViolationsToGitHubRecorder',
                config: [
                  repositoryName: 'your_project_name',
                  pullRequestId: env.CHANGE_ID,
                  createSingleFileComments: true,
                  commentOnlyChangedContent: true,
                  keepOldComments: false,
                  violationConfigs: [
                    [ pattern: '.*/lint\\.txt$', parser: 'GOLINT', reporter: 'RubyCritic' ],
                  ]
                ]])
            }
          }
        }
      }
    }
  3. Configure Jenkins for RubyCritic reports

    main

    To persist and view RubyCritic reports within Jenkins, you must install the HTML Publisher plugin.

    When configuring your Jenkins job, add a Post-build Action with the following settings:

    • Publish HTML reports
    • HTML directory to archive: tmp/rubycritic/
    • Index page: overview.html
    • Keep past HTML reports: Enable this to track project quality trends over time.
  4. Interpret Churn and Complexity charts

    main

    RubyCritic visualizes files on a chart based on Churn and Complexity.

    • Goal: Files should be as close to the bottom-left corner as possible.
    • Complexity: Represents the ABC metric (Assignments, Branches, and Calls). Lower complexity is better.
    • Churn: Represents the number of commits. Since you cannot easily reduce historical churn, focus on keeping the dots as low as possible on the chart by managing complexity.
  5. Install RubyCritic

    main

    You can install RubyCritic directly via gem or by adding it to your Gemfile for use with Bundler.

    Using gem:

    $ gem install rubycritic

    Using Bundler: Add this to your Gemfile:

    gem "rubycritic", require: false

    Then run:

    $ bundle
  6. Set up a Jenkins Build Job for RubyCritic

    main

    To automate code analysis on every push, create a 'Build a free-style software project' in Jenkins and configure the following:

    1. Source Code Management: Select Git and provide your repository URL. If private, use SSH Username with private key credentials pointing to the Jenkins master's ~/.ssh folder.
    2. Build Triggers: Select Build when a change is pushed to GitHub.
    3. Build Steps: Add an Execute shell step and enter your analysis command:
      rubycritic app lib
    4. Post-build Actions: Use the HTML Publisher plugin to archive the results (see Configure Jenkins for RubyCritic reports).
  7. Load a custom formatter in a Rakefile

    main

    When using RubyCritic::RakeTask, you must require your formatter class before defining the task. You can then specify the formatter by passing its fully qualified classname to the task.options using the --custom-format flag.

    require 'my_formatter'
    
    RubyCritic::RakeTask.new do |task|
      task.options = %(--custom-format MyFormatter)
    end
  8. Integrate GitHub with Jenkins via Webhooks

    main

    To trigger Jenkins jobs automatically upon a GitHub push:

    1. In your GitHub repository, navigate to Settings > Webhooks & Services.
    2. Click Add service and select Jenkins (GitHub plugin).
    3. Set the Jenkins hook url to your Jenkins UI URL followed by /github-webhook/ (e.g., http://your-jenkins-server:8080/github-webhook/).
  9. Configure Violation Comments to GitHub Jenkins Plugin for RubyCritic

    main

    When using the ViolationsToGitHubRecorder step in a Jenkins pipeline, configure the violationConfigs to recognize RubyCritic's output.

    Use the following configuration parameters:

    • pattern: A regex matching the RubyCritic output file (e.g., '.*/lint\.txt$').
    • parser: Set to 'GOLINT' (the plugin uses the GoLint parser to read RubyCritic's lint format).
    • reporter: Set to 'RubyCritic'.

    Other useful config keys for ViolationsToGitHubRecorder:

    • repositoryName: The name of your GitHub repository.
    • pullRequestId: Use env.CHANGE_ID to automatically capture the PR ID.
    • createSingleFileComments: Set to true to create one comment per violation.
    • commentOnlyChangedContent: Set to true to only comment on lines that have changed in the PR.
  10. Configure RubyCritic with .rubycritic.yml

    main

    Create a .rubycritic.yml file in your project root to persist configuration.

    Example configuration:

    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
    duplicate_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)
    mode_ci:
      enabled: true
      branch: 'production'
    branch: 'production'
    path: '/tmp/mycustompath'
    coverage_path: '/tmp/coverage'
    threshold_score: 10
    duplicate_symlinks: true
    suppress_ratings: true
    no_browser: true
    formats:
      - console
    minimum_score: 95
    paths:
      - 'app/controllers/'
      - 'app/models/'
      - 'lib/**'