# Getting Started with StandardRB

Code consistency becomes crucial as Ruby projects evolve from individual scripts into collaborative applications. StandardRB eliminates style debates by providing an opinionated formatter that automatically fixes Ruby code according to established conventions.


This guide covers StandardRB installation, configuration, and integration into Ruby development workflows.

## Prerequisites

Ruby 2.7 or later includes the syntax features that StandardRB expects for modern Ruby code formatting.

Basic familiarity with Ruby syntax and common development tools like bundler and rake will help you integrate StandardRB into existing projects effectively.

## StandardRB's approach to code style

![233717126-9fd13e6d-9a66-4f1c-b40c-fe875cb1d1b4.png](https://imagedelivery.net/xZXo0QFi-1_4Zimer-T0XQ/af05146b-8c5b-4b3d-4857-4448aa7a1a00/lg2x =2232x509)

StandardRB follows the principle of "zero configuration" by making opinionated decisions about Ruby code formatting. Rather than providing hundreds of configurable rules, it implements a fixed set of conventions derived from community best practices and Ruby's own style guide.

The formatter handles these key areas:

- **Indentation**: Two spaces, no tabs
- **Line length**: 120 characters maximum
- **String quotes**: Double quotes by default
- **Method definitions**: Consistent spacing and alignment
- **Hash syntax**: Modern Ruby hash syntax where appropriate

This opinionated approach eliminates bikeshedding about style preferences while maintaining readability and consistency across Ruby codebases.

Create a test project:

```command
mkdir standard-ruby-demo && cd standard-ruby-demo
```

## Installing and basic usage

StandardRB installs as a Ruby gem and integrates with most Ruby project structures. The gem provides both command-line tools and programmatic APIs for code formatting and style checking.

Add StandardRB to your project:

```ruby
[label Gemfile]
# Gemfile
source 'https://rubygems.org'

gem 'standard', group: [:development, :test]
```

Install the gem:

```command
bundle install
```

Create a sample Ruby file with inconsistent formatting:

```ruby
[label messy_code.rb]
class User
def initialize( name,email )
@name=name
@email = email
end

def to_hash()
{
:name => @name,
"email" => @email
}
end

def self.from_hash(hash)
new(hash[:name],hash["email"])
end
end

user=User.new("John Doe","john@example.com")
puts user.to_hash
```

This intentionally messy code demonstrates common formatting inconsistencies: irregular spacing, mixed hash syntax, inconsistent method call formatting, and variable assignment spacing.

Run StandardRB to see the issues:

```command
bundle exec standardrb messy_code.rb
```

```text
[output]
standard: Use Ruby Standard Style (https://github.com/standardrb/standard)
  messy_code.rb:2:1: Layout/IndentationWidth: Use 2 (not 0) spaces for indentation.
  messy_code.rb:2:16: Layout/SpaceInsideParens: Space inside parentheses detected.
  messy_code.rb:2:21: Layout/SpaceAfterComma: Space missing after comma.
  messy_code.rb:2:27: Layout/SpaceInsideParens: Space inside 
...
  messy_code.rb:15:16: Layout/SpaceAfterComma: Space missing after comma.
  messy_code.rb:19:5: Layout/SpaceAroundOperators: Surrounding space missing for operator `=`.
  messy_code.rb:19:25: Layout/SpaceAfterComma: Space missing after comma.
standard: Run `standardrb --fix` to fix up to 15 problems.
```

StandardRB identifies specific violations with line numbers and descriptions. The `--fix` option automatically corrects most issues.

Fix the formatting automatically:

```command
bundle exec standardrb --fix messy_code.rb
```

Check the corrected code:

```ruby
[label messy_code.rb]
class User
  def initialize(name, email)
    @name = name
    @email = email
  end

  def to_hash
    {
      :name => @name,
      "email" => @email
    }
  end

  def self.from_hash(hash)
    new(hash[:name], hash["email"])
  end
end

user = User.new("John Doe", "john@example.com")
puts user.to_hash
```

StandardRB automatically corrected spacing, indentation, hash syntax, and method definitions while preserving the code's functionality. 

The formatter converts old-style hash syntax (`:name => value`) to modern syntax (`name: value`) and ensures consistent spacing throughout.

## Integrating with development workflows

StandardRB integrates with popular Ruby development tools to provide automatic formatting during normal development activities. This integration ensures code stays formatted without manual intervention.

![Screenshot of the integration](https://imagedelivery.net/xZXo0QFi-1_4Zimer-T0XQ/535353a3-1b9a-4724-7cb8-0f3110275a00/md1x =1202x1504)

### Rake integration

StandardRB includes pre-built Rake tasks that you can add to your project. These tasks let you check or fix code formatting using familiar `rake` commands.


Update your Gemfile to include rake:

```ruby
[label Gemfile]
# Gemfile
source 'https://rubygems.org'
[highlight]
gem 'rake'
[/highlight]
gem 'standard', group: [:development, :test]
```

Then run:

```command
bundle install
```

After that, create a Rakefile in your project root (or add to an existing one):

```ruby
[label Rakefile]
require 'standard/rake'
```

This single line adds two new rake tasks to your project:

- `rake standard` - scans your code and reports style violations
- `rake standard:fix` - automatically fixes style violations

Test the basic checking task:

```command
bundle exec rake standard
```

```text
[output]
standard: Use Ruby Standard Style (https://github.com/standardrb/standard)
  Gemfile:2:8: Style/StringLiterals: Prefer double-quoted strings unless you need single quotes to avoid extra backslashes for escaping.
...
  Rakefile:1:9: Style/StringLiterals: Prefer double-quoted strings unless you need single quotes to avoid extra backslashes for escaping.
standard: Run `rake standard:fix` to fix up to 4 problems.
rake aborted!
```

StandardRB detected style violations in your project files. Fix them automatically:

```command
bundle exec rake standard:fix
```

Now add a custom task that enforces style checking before running tests:

```ruby
[label Rakefile]
require "standard/rake"

[highlight]
desc "Run tests with style checking"
task test_with_style: [:standard] do
  puts "Code style verified, running tests..."
  system("bundle exec rake test")
end
[/highlight]
```

Run the combined task:

```command
bundle exec rake test_with_style
```

```text
[output]
standard: Use Ruby Standard Style (https://github.com/standardrb/standard)
  Rakefile:8:1: Layout/TrailingEmptyLines: 1 trailing blank lines detected.
standard: Run `rake standard:fix` to potentially fix one problem.
rake aborted!
...
```


This shows the workflow working correctly: StandardRB passed the style check, printed "Code style verified, running tests...", then failed because no test task exists yet. The dependency chain works as intended - style violations prevent execution, but clean code proceeds to the next step.

This real-world example demonstrates StandardRB's integration value: it catches formatting issues (like trailing whitespace) that might otherwise slip through code review, ensuring consistent code quality before tests or deployment.RetryClaude can make mistakes. Please double-check responses.



### Git hooks integration

Git hooks provide automatic StandardRB checking at key points in your development workflow. Pre-commit hooks catch formatting issues before they enter your repository, while pre-push hooks ensure clean code reaches shared branches.

Initialize a Git repository in your project:

```command
git init
```
```command
git add .
```
```command
git commit -m "Initial commit"
```

Create a pre-commit hook that automatically formats code before each commit:

```bash
[label .git/hooks/pre-commit]
#!/bin/bash

echo "Running StandardRB..."

# Check for violations first
if ! bundle exec standardrb --no-fix; then
  echo "StandardRB found violations. Attempting to fix..."
  
  # Fix formatting issues automatically
  bundle exec standardrb --fix
  
  # Add any fixed files back to the commit
  git add -u
  
  # Check again for any remaining issues
  if ! bundle exec standardrb --no-fix; then
    echo "Unable to automatically fix all violations."
    echo "Please review and fix manually, then commit again."
    exit 1
  fi
  
  echo "Code formatting fixed and staged for commit."
fi

echo "StandardRB check passed."
```

This hook script implements a safety workflow that first checks for violations using `standardrb --no-fix`, which scans without making changes. 

The `!` operator inverts the exit code, triggering the conditional block when violations exist. If issues are found, the script runs `standardrb --fix` to automatically correct formatting problems, then uses `git add -u` to stage the corrected files back into the commit.

 A final verification step runs another `--no-fix` check to ensure all violations were resolved, and if any remain unfixable, the hook exits with code 1 to abort the commit. The `--no-fix` flag prevents StandardRB from making changes during checking phases, while `--fix` explicitly enables corrections, and `git add -u` stages only modified files rather than new files.

Make the hook executable:

```command
chmod +x .git/hooks/pre-commit
```

This permission change is essential because Git requires hook scripts to have execute permissions, or they won't run during Git operations.

Test the hook by making a commit with poorly formatted code:

```ruby
[label bad_format.rb]
def messy_method(x,y)
return x+y
end
```

Add and attempt to commit:

```command
git add bad_format.rb
```
```command
git commit -m "Add poorly formatted code"
```

```text
[output]

Running StandardRB...
standard: Use Ruby Standard Style (https://github.com/standardrb/standard)
  Rakefile:8:1: Layout/TrailingEmptyLines: 1 trailing blank lines detected.
  bad_format.rb:1:19: Layout/SpaceAfterComma: Space missing after comma.
  bad_format.rb:2:1: Layout/IndentationWidth: Use 2 (not 0) spaces for indentation.
  bad_format.rb:2:1: Style/RedundantReturn: Redundant `return` detected.
  bad_format.rb:2:9: Layout/SpaceAroundOperators: Surrounding space missing for operator `+`.
standard: Run `standardrb --fix` to fix up to 5 problems.
StandardRB found violations. Attempting to fix...
Code formatting fixed and staged for commit.
StandardRB check passed.
[master a0b0f3b] Add poorly formatted code
 2 files changed, 3 insertions(+), 1 deletion(-)
 create mode 100644 bad_format.rb
stanley@MacBookPro standard-ruby-demo
```

The hook automatically detected formatting violations, fixed them, and included the corrections in your commit. This ensures your repository maintains consistent formatting without manual intervention.



## Configuration and customization

While StandardRB emphasizes zero configuration, it provides limited customization options for projects with specific requirements. These configurations should be used sparingly to maintain the tool's core philosophy of consistency.

Create a StandardRB configuration file:

```yaml
[label .standard.yml]
# Ignore specific files or directories
ignore:
  - 'db/migrate/**/*'
  - 'vendor/**/*'
  - 'tmp/**/*'
  - 'node_modules/**/*'

# Fix specific file patterns only
fix: true

# Parallel processing for large codebases
parallel: true
```

The configuration file supports basic options without compromising StandardRB's opinionated approach. The `ignore` option helps exclude generated code, database migrations, or third-party libraries from formatting requirements. Database migrations often contain auto-generated timestamps and formatting that shouldn't be modified, while vendor directories contain external code that follows different style conventions.

Test the ignore configuration by creating a file that would normally trigger violations:

```ruby
[label db/migrate/001_create_users.rb]
class CreateUsers<ActiveRecord::Migration
def change
create_table :users do|t|
t.string:name
t.string:email
end
end
end
```

Run StandardRB to verify the ignore rules work:

```command
bundle exec standardrb
```

The empty output with no error messages or violation reports confirms that StandardRB found no offenses. This silent success indicates the ignore configuration worked correctly - StandardRB scanned your project but skipped the `db/migrate/001_create_users.rb` file due to the `db/migrate/**/*` ignore pattern in your `.standard.yml` configuration.

Without the ignore configuration, StandardRB would have reported multiple formatting violations from the migration file, including missing spaces around operators (`<`), inconsistent indentation, and missing spaces in method calls. The absence of any output proves that StandardRB successfully excluded the problematic file from its analysis.

This demonstrates StandardRB's ignore functionality allows you to maintain strict formatting standards for application code while excluding generated files, vendor libraries, and other code that shouldn't be reformatted.



## Final thoughts

StandardRB eliminates style debates through automated formatting and zero-configuration conventions. Start with basic installation and automatic fixing, then integrate into your workflow through Git hooks and CI pipelines.

For adoption, focus on incremental rollout and communicate the benefits of consistent formatting to your team. The time saved on style discussions typically justifies setup effort within weeks. The [StandardRB documentation](https://github.com/testdouble/standard) provides advanced configuration guides, while the [Ruby Style Guide](https://rubystyle.guide/) explains formatting conventions and the [RuboCop rules reference](https://docs.rubocop.org/rubocop/) helps if you're migrating from other linters.