# Result builder

{% hint style="success" %}
This is the official documentation of the `agent_ruby` Ruby agent.
{% endhint %}

Actions can be configured to achieve different results in the GUI.

Most actions will simply perform work and display the default notification, however, other behaviors are possible:

* [Displaying a notification with a custom message](#custom-notifications)
* [Displaying HTML content in a side panel](#html-result)
* [Generating a file download](#file-generation)
* [Redirecting the user to another page](#redirections)
* [Calling a webhook from the user's browser](#webhooks) (for instance to trigger a login in a third-party application)
* [Invalidating related data](/developer-guide-agents-ruby/agent-customization/actions/related-data-invalidation.md)

### Default behavior

The default behavior, when no exception is thrown in the handler is to display a generic notification.

![](/files/y5iCeQn9elrwxusEppak)

#### Traditional Syntax

Using full context methods with `customize_collection`:

```ruby
include ForestAdmin::Types

@create_agent.customize_collection('company') do |collection|
  collection.add_action(
    'Mark as live',
    BaseAction.new(scope: ActionScope::SINGLE) do |context|
      # Not using the resultBuilder here will display the generic success notification.
      # (as long as no exception is thrown)
    end
  )
end
```

#### DSL Syntax

Using simplified helper methods with `collection.action`:

```ruby
@create_agent.collection :company do |collection|
  collection.action 'Mark as live', scope: :single do
    execute do
      # Not using the result builder here will display the generic success notification.
      # (as long as no exception is thrown)
    end
  end
end
```

### Custom notifications

When customizing the notification message, you can use the `ForestAdminDatasourceCustomizer::Decorators::Action::ResultBuilder` to generate different types of responses.

![](/files/4mUbz1kSzo19MUHzvhyO) ![](/files/uTsszKy7nguu3DmUxV99)

#### Traditional Syntax

Using full context methods with `customize_collection`:

```ruby
include ForestAdmin::Types

@create_agent.customize_collection('company') do |collection|
  collection.add_action(
    'Mark as live',
    BaseAction.new(scope: ActionScope::SINGLE) do |_context, result_builder|
      if # Company is not live
        result_builder.success(message: 'Company is now live!')
      else
        result_builder.error(message: 'The company was already live!')
      end
    end
  )
end
```

#### DSL Syntax

Using simplified helper methods with `collection.action`:

```ruby
@create_agent.collection :company do |collection|
  collection.action 'Mark as live', scope: :single do
    execute do
      if # Company is not live
        success 'Company is now live!'
      else
        error 'The company was already live!'
      end
    end
  end
end
```

### HTML result

You can also return an HTML page to give more feedback to the user who triggered the Action.

![](/files/fWnP91qfTWpo2b8bBxyh)

```ruby
include ForestAdmin::Types

@create_agent.customize_collection('company') do |collection|
  collection.add_action(
    'Charge credit card',
    BaseAction.new(scope: ActionScope::SINGLE) do |context, result_builder|
      # ... charge the credit card ...
      record = context.get_record(['amount', 'source:last4'])
      if credit_card_successfully_charged
        result_builder.success(
          message: 'Success',
          options: {
            html: "<p class='c-clr-1-4 l-mt l-mb'>#{record['amount'] / 100} USD has been successfully charged.</p>
              <strong class='c-form__label--read c-clr-1-2'>Credit card</strong>
              <p class='c-clr-1-4 l-mb'>**** **** **** #{record['source']['last4']}</p>"
          }
        )
      else
        result_builder.error(
          message: 'An error occured',
          options: {
            html: "<p class='c-clr-1-4 l-mt l-mb'>#{record['amount'] / 100} USD has not been charged.</p>
              <strong class='c-form__label--read c-clr-1-2'>Credit card</strong>
              <p class='c-clr-1-4 l-mb'>**** **** **** #{record['source']['last4']}</p>
              <strong class='c-form__label--read c-clr-1-2'>Reason</strong>
              <p class='c-clr-1-4 l-mb'>You can not charge this credit card. The card is marked as blocked</p>"
          }
        )
      end
    end
  )
end
```

### File generation

{% hint style="warning" %}
Because of technical limitations, Smart Actions that generate files should be flagged as such with the `generateFile` option.

This will cause the GUI to download the output of the action, but will also prevent from being able to use the `resultBuilder` to display notifications, errors, or HTML content.
{% endhint %}

Smart actions can be used to generate or download files.

The example code below will trigger a file download (with the file named `filename.txt`, containing `StringThatWillBeInTheFile` using `text/plain` mime-type).

```ruby
include ForestAdmin::Types

@create_agent.customize_collection('company') do |collection|
  collection.add_action(
    'Download a file',
    BaseAction.new(scope: ActionScope::GLOBAL, is_generate_file: true) do |_context, result_builder|
      my_file = File.open('filename.txt', 'w')
      my_file.write('StringThatWillBeInTheFile')
      my_file.close

      result_builder.file(content: 'filename.txt', name: 'filename.txt', mime_type: 'text/plain')
    end
  )
end
```

### Redirections

To streamline your operation workflow, it could make sense to redirect to another page after an Action has successfully been executed.

It is possible using the `redirectTo` function.

The redirection works both for internal (`\*.forestadmin.com` pages) and external links.

{% tabs %}
{% tab title="Internal link" %}

```ruby
include ForestAdmin::Types
```

{% endtab %}

{% tab title="External link" %}

{% endtab %}
{% endtabs %}

### Webhooks

After an action you can set up an HTTP (or HTTPS) callback - a webhook - to forward information to other applications.

Note that the webhook will be triggered from the user's browser, so it will be subject to CORS restrictions.

Its intended use is often to perform a login on a third-party application or to trigger a background job on the current user's behalf.

```ruby
include ForestAdmin::Types

@create_agent.customize_collection('company') do |collection|
  collection.add_action(
    'Mark as live',
    BaseAction.new(scope: ActionScope::SINGLE) do |_context, result_builder|
      result_builder.webhook(
        url: 'http://my-company-name', # The url of the company providing the service.
        method: 'POST', # The method you would like to use (typically a POST).
        headers: {}, # You can add some headers if needed.
        body: { adminToken: 'your-admin-token' } # A body to send to the url.
      )
    end
  )
end
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.forestadmin.com/developer-guide-agents-ruby/agent-customization/actions/result-builder.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
