> ## Documentation Index
> Fetch the complete documentation index at: https://docs.appsignal.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Ruby on Rails

export const Compatibility = ({versions = [], label = "Available in"}) => {
  if (!Array.isArray(versions) || versions.length === 0) {
    return null;
  }
  const defaultPillStyle = {
    borderColor: "#d4d4d8",
    background: "#f4f4f5",
    color: "#3f3f46"
  };
  const pillStyles = {
    "AppSignal for Elixir": {
      background: "#f3e8ff",
      borderColor: "#d8b4fe",
      color: "#6b21a8"
    },
    "AppSignal for Front-end": {
      background: "#fef9c3",
      borderColor: "#fde047",
      color: "#854d0e"
    },
    "AppSignal for Go": {
      background: "#ccfbf1",
      borderColor: "#5eead4",
      color: "#115e59"
    },
    "AppSignal for JavaScript": {
      background: "#fef9c3",
      borderColor: "#fde047",
      color: "#854d0e"
    },
    "AppSignal for Node.js": {
      background: "#dcfce7",
      borderColor: "#86efac",
      color: "#166534"
    },
    "AppSignal for Python": {
      background: "#dbeafe",
      borderColor: "#93c5fd",
      color: "#1e40af"
    },
    "AppSignal for Ruby": {
      background: "#fee2e2",
      borderColor: "#fca5a5",
      color: "#991b1b"
    },
    "AppSignal for Rust": {
      background: "#ffedd5",
      borderColor: "#fdba74",
      color: "#9a3412"
    }
  };
  const getPillStyle = name => ({
    ...defaultPillStyle,
    ...pillStyles[name] || ({})
  });
  return <div className="not-prose my-4 rounded-lg border border-zinc-200 bg-zinc-50 px-4 py-3 text-sm dark:border-white/10 dark:bg-white/5">
      <div className="flex flex-wrap items-center gap-x-2 gap-y-1">
        <span className="font-semibold text-zinc-700 dark:text-zinc-200">
          {label}:
        </span>
        {versions.map((v, i) => <span key={`${v.name}-${v.version}-${i}`} className="inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-xs font-medium" style={getPillStyle(v.name)}>
            <span>{v.name}</span>
            <span className="opacity-70">
              {v.version}
              {v.exact ? "" : "+"}
            </span>
          </span>)}
      </div>
    </div>;
};

[Ruby on Rails](http://rubyonrails.org/) is supported out-of-the-box by AppSignal. To install follow the installation steps in AppSignal, start by clicking 'Add app' on the [accounts screen](https://appsignal.com/accounts).

The AppSignal integration for Rails works by tracking exceptions and performance in requests. When an error occurs in a controller during a request AppSignal will report it. Performance issues will be based on the duration of a request and create a timeline of events detailing which parts of the application took the longest.

## Active Job

<Compatibility versions={[{ name: "AppSignal for Ruby", version: "2.11.0" }]} />

See our [Active Job page](/ruby/integrations/active-job) for more information on how our Active Job instrumentation works.

## Action Cable

<Compatibility versions={[{ name: "AppSignal for Ruby", version: "2.3.0" }]} />

See our [Action Cable page](/ruby/integrations/action-cable) for more information on how our Action Cable instrumentation works.

## Configure AppSignal in an initializer

<Compatibility versions={[{ name: "AppSignal for Ruby", version: "3.12.0" }]} />

We recommend using our [`config/appsignal.rb` config file](/ruby/configuration/load-order#appsignal-rb-config-file) or [environment variables](/ruby/configuration/load-order#5-environment-variables) to [configure AppSignal](/ruby/configuration).
By default, it's not possible to configure AppSignal from a Rails initializer, because AppSignal loads before your application's initializers, in order to be able to report errors that take place during initialization.

To configure AppSignal in a Rails initializer, first configure Rails to start AppSignal after the app's initializers have run.

<CodeGroup>
  ```ruby Ruby theme={null}
  # config/application.rb

  # ...

  module MyApp
    class Application < Rails::Application
      # Add this line
      config.appsignal.start_at = :after_initialize

      # Other config
    end
  end
  ```
</CodeGroup>

Then, in the initializer:

<CodeGroup>
  ```ruby Ruby theme={null}
  # config/initializers/appsignal.rb

  Appsignal.configure do |config|
    config.ignore_actions = ["My action"]
  end
  ```
</CodeGroup>

Do not call `Appsignal.start` in the initializers. The Ruby gem will start AppSignal automatically when Rails has run all initializers.

When a Rails app is configured to start AppSignal after the initializers have loaded, it is no longer possible to [report errors from initializers when booting Rails app](#error-reporting-from-initializers).

## Error reporting from initializers

By default, AppSignal reports errors that occur in controller, Rake tasks and Active Job jobs. It does not report errors that occur when the application is booting, before the Rails initializers. To do get notified when these errors occur, adding the following to your `config.ru` file, around the line that requires the `environment.rb` file.

<CodeGroup>
  ```ruby Ruby theme={null}
  # config.ru
  begin
    require ::File.expand_path("../config/environment",  __FILE__)
  rescue Exception => error
    Appsignal.send_error(error)
    raise
  end
  ```
</CodeGroup>

The errors that occur here will not be grouped under an incident with an action name.

## Backtrace cleaner

With the Rails integration, AppSignal will run the backtrace of each exception through the [Rails backtrace cleaner][backtrace cleaner docs]. This cleaner gives you the option to modify or filter out unwanted backtrace lines, removing clutter and noise from the backtrace.

You can add or remove filters and silencers to the default configuration.

**Filters** will mutate the given line. An example would be to remove the `Rails.root` prefix.

**Silencers** will remove the line from the backtrace, if the given expression returns `true`. You can add these additional backtrace cleaner rules in an initialize.

For example:

<CodeGroup>
  ```ruby Ruby theme={null}
  # config/initializers/backtrace_cleaner.rb
  bc = Rails.backtrace_cleaner
  bc.add_filter { |line| line.gsub(Rails.root.to_s, '<root>') }
  bc.add_silencer { |line| line.index('<root>').nil? and line.index('/') == 0 }
  bc.add_silencer { |line| line.index('<root>/vendor/') == 0 }
  ```
</CodeGroup>

For more information about the backtrace cleaner, see the [Rails BacktraceCleaner documentation][backtrace cleaner docs].

## Error reporter

<Compatibility versions={[{ name: "AppSignal for Ruby", version: "3.4.1" }]} />

AppSignal reports errors raised via `ActiveSupport::ErrorReporter` by default. `ActiveSupport::ErrorReporter` was introduced in Rails 7.0 to standardize custom error reporting.

You can disable this functionality with the [`enable_rails_error_reporter`](/ruby/configuration/options#option-enable_rails_error_reporter) configuration option.

If a transaction is active in the context an error is reported through the Rails error reporter, it will include the same metadata and sample data as the active transaction: namespace, action name, tags, custom data, parameters, etc.

<CodeGroup>
  ```ruby Ruby theme={null}
  # In both scenarios, the error is reported by AppSignal
  Rails.error.handle do
    raise "some error"
  end

  Rails.error.record do
    raise "some error"
  end
  ```
</CodeGroup>

<Warning>
  In AppSignal for Ruby gem version 3, some behavior was different. Please
  consult the [Ruby gem 3 legacy behavior](#ruby-gem-3-legacy-behavior) section
  for more information about the differences.
</Warning>

### Namespace and action from the current transaction

When reporting errors, we determine the namespace and action name in which it takes place, such as a controller or background job, on a best-effort basis. The incident namespace and action name will not always be set or be accurate.

If an AppSignal transaction is active (like in a web request or background job) the error reported with `Rails.error.handle/record` will have the same namespace, action name, tags, parameters, custom data, etc. as the active transaction. If no AppSignal transaction is active, no namespace, action name, tags, etc. will be set by default.

### Namespace and action from the context

If you want to change the reported error's namespace and action name without changing them on the already active AppSignal transaction, you can customize this on the error reporter call.

<CodeGroup>
  ```ruby Ruby theme={null}
  # The error reported here will have the "custom_namespace" namespace
  # and "CustomizedActionName#index" action name
  Rails.error.handle(:context => { :appsignal => { :namespace => "custom_namespace", :action => "CustomizedActionName#index" } }) do
    raise "some error"
  end
  ```
</CodeGroup>

### Tags from the active transaction

By default, the request/job's transaction tags are copied to the error reporter's error AppSignal transaction from the request/job's transaction.

<CodeGroup>
  ```ruby Ruby theme={null}
  # Rails controller example using a before_action callback
  class ExamplesController < ApplicationController
    before_action do
      Appsignal.add_tags(:tag1 => "value1", :tag2 => "value2")
    end

    def index
      # The error reported here will have the same tags set
      # as in the `before_action` callback
      Rails.error.handle do
        raise "some error"
      end
    end
  end
  ```
</CodeGroup>

### Tags from context

You can add tags to a reported error by using `context` in the `Rails.error.handle/record` call. These tags will only be set on the error reported with the `Rails.error.handle/record` methods.

<CodeGroup>
  ```ruby Ruby theme={null}
  Rails.error.handle(:context => { :tag1 => "value1", :tag2 => "value2" }) do
    raise "some error"
  end
  ```
</CodeGroup>

The same tagging limitations apply as for using [`Appsignal.add_tags`](/guides/tagging#ruby).

### Ruby gem 3 legacy behavior

In AppSignal for Ruby gem version 3 the error reporting behavior is different.

* Errors reported with the `Rails.error.handle` method are reported to AppSignal.
* Errors reported with `Rails.error.record` are not reported to AppSignal to avoid reporting the error twice when it's being reported by our Rails error reporting middleware.

All errors reported with the Rails error reporter are reported as separate errors. They do not always include the same metadata and sample data from any active AppSignal transaction. See the section for [context inheritance limitations](#context-inheritance-limitations) for more information.

<CodeGroup>
  ```ruby Ruby theme={null}
  # Reported by AppSignal
  Rails.error.handle do
    raise "some error"
  end

  # NOT reported by AppSignal
  Rails.error.record do
    raise "some error"
  end
  ```
</CodeGroup>

#### Context inheritance limitations

In Ruby gem 3 the context inheritance from the active transaction is limited. The metadata and some of the sample data is only copied if it set at the time `Rails.error.handle/record` is called.

In practice this mean Rails controllers and Active Job jobs will be accurately reported. Other libraries like Sidekiq jobs, no action name is set when reporting errors with `Rails.error.handle`.

Tags set after `Rails.error.handle/record` is called are not reported for the error reported using this helper.

## Runners

<Compatibility versions={[{ name: "AppSignal for Ruby", version: "4.0.0" }]} />

AppSignal will automatically report errors inside [Rails runners](https://guides.rubyonrails.org/command_line.html#bin-rails-runner). Some manual setup is also required to instrument a runner's performance.

We recommend putting the runner's code in a separate file and wrap it in the [`Appsignal.monitor` helper](/ruby/instrumentation/background-jobs), as shown in the example below.

```bash Bash theme={null}
bin/rails runner path_to_file.rb
```

<CodeGroup>
  ```ruby Ruby theme={null}
  Appsignal.monitor(:namespace => :runner, :action => "Runner name") do
    # Some code
  end
  ```
</CodeGroup>

If your Rails runner runs on a container that is only started to run this task, make sure that [`enable_at_exit_hook` option](/ruby/configuration/options#option-enable_at_exit_hook) is set to `true` (which should be the default on containers). This will ensure the data gets flushed to the AppSignal agent before the runner shuts down.

[backtrace cleaner docs]: https://api.rubyonrails.org/classes/ActiveSupport/BacktraceCleaner.html

[error reporter]: https://guides.rubyonrails.org/error_reporting.html
