Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

14.4 KB
Raw Blame
---
title: Creating a Spree extension
description: Build a Spree extension gem — models, API endpoints, permissions, workflow hooks and event subscribers — and pair it with a dashboard plugin for the admin UI.
---

## Overview

A Spree extension is a Ruby gem containing a Rails engine. It adds features to any Spree application without forking Spree: new models, new API endpoints, new permissions, and custom logic that runs inside Spree's workflows. You can share an extension with the Spree community on GitHub so anyone can use it and contribute improvements. For officially supported integrations, see the [Integrations directory](/integrations).

An extension is backend code only. Spree 6 has no Rails storefront or Rails admin to add views to:

| Part of the feature | Where it lives |
|---|---|
| Models, migrations, business logic | The extension gem |
| API endpoints (Store API and Admin API) | The extension gem |
| Permissions for staff roles and API keys | The extension gem |
| Admin screens | A [dashboard plugin](/developer/dashboard/plugins/overview) — an npm package that talks to your Admin API endpoints |
| Storefront pages | Your storefront application, through [`@spree/sdk`](/developer/sdk/quickstart) |

<Info>
  Prefer Spree's extension points over [decorators](/developer/customization/decorators): [workflow hooks](/developer/customization/workflows) to change what happens inside a flow, [events](/developer/core-concepts/events) to react after something happened, and `additional_permitted_attributes` to make your own columns writable. They keep working when Spree changes internally. See the [Customization Quickstart](/developer/customization/quickstart) for guidance on choosing the right approach.
</Info>

In this guide we build `spree_reviews`: customers read product reviews through the Store API, and staff manage them through the Admin API.

## Generate the extension

Install the Spree extension generator. Spree 6 needs version 2.0 or newer — earlier versions generate a Spree 5 scaffold built around the Rails admin:

```bash
gem install spree_extension -v '>= 2.0'
```

Run the following command from a directory outside your Spree application:

```bash
spree-extension create reviews
```

This creates a `spree_reviews` directory containing the engine, a gemspec, a test setup and continuous integration configuration. Its `config/routes.rb` and `config/initializers/spree.rb` come with commented-out Spree 6 examples — API routes, permission scopes, workflow hooks and event subscribers — that the steps below fill in. Change to its directory:

```bash
cd spree_reviews
```

## Add a model

Create the migration in `db/migrate/`:

```ruby db/migrate/20260901000000_create_spree_reviews.rb
class CreateSpreeReviews < ActiveRecord::Migration[8.1]
  def change
    create_table :spree_reviews do |t|
      t.references :store, null: false, index: true, foreign_key: false
      t.references :product, null: false, index: true, foreign_key: false
      t.integer :rating, null: false
      t.text :body
      t.boolean :approved, null: false, default: false

      t.timestamps
    end
  end
end
```

Then the model:

```ruby app/models/spree/review.rb
module Spree
  class Review < Spree.base_class
    include Spree::SingleStoreResource

    has_prefix_id :review
    publishes_lifecycle_events

    belongs_to :product, class_name: 'Spree::Product'

    validates :rating, presence: true, inclusion: { in: 1..5 }

    scope :approved, -> { where(approved: true) }

    self.whitelisted_ransackable_attributes = %w[rating approved]
  end
end
```

A few Spree conventions are at work here:

- **Reviews belong to a store.** `Spree::SingleStoreResource` fills in the store for new records, and the API only returns the current store's reviews. Commerce data is always per store.
- **Prefixed IDs.** `has_prefix_id` gives every review an ID like `review_k5nR8xLq` in API responses. Integer database IDs are never exposed.
- **No foreign key constraints** on business tables, and `class_name` on every association.
- **Lifecycle events.** `publishes_lifecycle_events` makes the model emit `review.created`, `review.updated` and `review.deleted`, which subscribers and [webhooks](/developer/core-concepts/webhooks) can react to.

## Expose it through the API

Add serializers for both APIs. The Admin API serializer extends the Store API one with the fields only staff should see:

```ruby app/serializers/spree/api/v3/review_serializer.rb
module Spree
  module Api
    module V3
      class ReviewSerializer < BaseSerializer
        typelize rating: :number, body: [:string, nullable: true]

        attributes :rating, :body
      end
    end
  end
end
```

```ruby app/serializers/spree/api/v3/admin/review_serializer.rb
module Spree
  module Api
    module V3
      module Admin
        class ReviewSerializer < V3::ReviewSerializer
          typelize approved: :boolean

          attributes :approved, :created_at, :updated_at
        end
      end
    end
  end
end
```

The Store API controller is read-only and returns approved reviews only:

```ruby app/controllers/spree/api/v3/store/reviews_controller.rb
module Spree
  module Api
    module V3
      module Store
        class ReviewsController < ResourceController
          protected

          def model_class
            Spree::Review
          end

          def serializer_class
            Spree::Api::V3::ReviewSerializer
          end

          def scope
            super.approved
          end
        end
      end
    end
  end
end
```

The Admin API controller gives staff full create, read, update and delete access:

```ruby app/controllers/spree/api/v3/admin/reviews_controller.rb
module Spree
  module Api
    module V3
      module Admin
        class ReviewsController < ResourceController
          scoped_resource :reviews

          request_params :review do |body|
            body.attribute :product_id, :id, required: true, on: :create
            body.attribute :rating, :integer, required: true, on: :create
            body.attribute :body, :string
            body.attribute :approved, :boolean
          end

          protected

          def model_class
            Spree::Review
          end

          def serializer_class
            Spree::Api::V3::Admin::ReviewSerializer
          end
        end
      end
    end
  end
end
```

`scoped_resource :reviews` means only staff roles and secret API keys holding the `read_reviews` or `write_reviews` permission can call these endpoints. The next section registers that permission.

Finally, add the routes. The scaffold's `config/routes.rb` already contains the route hook:

```ruby config/routes.rb
Spree::Core::Engine.add_routes do
  namespace :api, defaults: { format: 'json' } do
    namespace :v3 do
      namespace :store do
        resources :reviews, only: [:index, :show]
      end

      namespace :admin do
        resources :reviews
      end
    end
  end
end
```

Pagination, [Ransack](https://github.com/activerecord-hackery/ransack) filtering (`?q[rating_gteq]=4`), sorting and prefixed ID lookup all come from the base `ResourceController`. See [Customizing the API](/developer/customization/api) for everything you can override.

## Register permissions

Register your model as a permission scope, so the `read_reviews` and `write_reviews` permissions appear in the staff role editor and can be granted to secret API keys:

```ruby config/initializers/spree.rb
Spree.permissions.register_scope(:reviews, group: :catalog, resources: -> {
  [Spree::Review]
})
```

Label the permission for the dashboard in your locale file:

```yaml config/locales/en.yml
en:
  spree:
    permissions_catalog:
      resources:
        reviews:
          label: Reviews
          description: Product reviews left by customers
```

See [Permissions](/developer/customization/permissions) for audiences and read-only scopes.

## Extend core models and behavior

Extensions often need to change Spree's own resources as well as add new ones. Reach for these options in order.

### Make a new column writable

Suppose each product gets a `reviews_enabled` switch. Add the column with a migration, then let the existing product endpoints accept it — no controller changes needed:

```ruby lib/spree_reviews/engine.rb
config.to_prepare do
  Spree::Product.additional_permitted_attributes += [:reviews_enabled]
end
```

Always append with `+=`, so you don't remove attributes that other extensions added.

### Run code inside a Spree workflow

[Workflow hooks](/developer/customization/workflows) run your code at a named point inside a core flow — checkout completion, cancellations, refunds, product changes — and can stop the operation. For example, to require a description before a product with reviews enabled goes on sale:

```ruby config/initializers/spree.rb
Spree.hooks.register('products.activate.validate', 'SpreeReviews::RequireDescription')
```

```ruby app/services/spree_reviews/require_description.rb
module SpreeReviews
  class RequireDescription
    def call(workflow)
      product = workflow.product
      return unless product.reviews_enabled
      return if product.description.present?

      workflow.reject!('Add a description before activating a product with reviews.')
    end
  end
end
```

Hook names are checked when the application boots, so a typo fails at startup rather than silently never running.

### React to events

To do something *after* an event, without influencing it, write an [event subscriber](/developer/core-concepts/events). For example, to ask customers for a review once their order arrives:

```ruby app/subscribers/spree_reviews/review_request_subscriber.rb
module SpreeReviews
  class ReviewRequestSubscriber < Spree::Subscriber
    subscribes_to 'order.delivered'

    def handle(event)
      order = Spree::Order.find_by_prefix_id(event.payload['id'])
      return unless order

      SpreeReviews::ReviewRequestMailer.request_review(order).deliver_later
    end
  end
end
```

Subscribers are not discovered automatically. Register them in the extension's initializer — `bin/rails g spree:subscriber` adds the line for you:

```ruby config/initializers/spree.rb
Rails.application.config.after_initialize do
  Spree.subscribers << SpreeReviews::ReviewRequestSubscriber
end
```

### Decorators, as a last resort

When none of the above fits — adding an association to a core model, for example — use a [decorator](/developer/customization/decorators):

```ruby app/models/spree_reviews/product_decorator.rb
module SpreeReviews
  module ProductDecorator
    def self.prepended(base)
      base.has_many :reviews, class_name: 'Spree::Review', dependent: :destroy
    end
  end
end

Spree::Product.prepend SpreeReviews::ProductDecorator
```

Rails does not load decorators on its own, so the scaffold's engine does it for you: `lib/spree_reviews/engine.rb` loads every `app/**/*_decorator*.rb` file at boot and again on each code reload in development. Name the file with a `_decorator` suffix and there is nothing else to wire up.

## Add admin screens

Admin screens are built as a [dashboard plugin](/developer/dashboard/plugins/overview): a React package that registers navigation entries, pages and product page widgets, and reads and writes data through your Admin API endpoints. Scaffold one with the Spree CLI:

```bash
npx @spree/cli plugin new reviews
```

See [Scaffolding](/developer/dashboard/plugins/scaffolding) and [Backend integration](/developer/dashboard/customization/backend) to connect it to the endpoints above, and [Distributing](/developer/dashboard/plugins/distributing) to ship the gem and the npm package together.

## Add the extension to your application

From your Spree application's backend directory, add the gem to the `Gemfile`. Adjust the path to point at your extension:

```ruby Gemfile
gem 'spree_reviews', path: '../spree_reviews'
```

Install it, then copy the extension's migrations into the application and run them:

```bash
bundle install
bin/rails g spree_reviews:install
```

The Store API now serves reviews at `/api/v3/store/reviews`, and the Admin API manages them at `/api/v3/admin/reviews`.

Once you publish the gem, Spree projects install it with one command, which adds the gem, runs your install generator, runs the migrations and restarts the server:

```bash
spree add --gem spree_reviews
```

To work well with it:

- **Make the install generator optional.** The CLI runs `spree_reviews:install` only if it exists, so the gem must work without it.
- **Put any manual setup in the gemspec's `post_install_message`**, such as an environment variable to set. Bundler prints it during the install. Keep it short; most extensions need none.

## Test the extension

An extension is not a full Rails application, so its tests run against a small generated Spree application. Create it from the extension's root directory:

```bash
bundle exec rake test_app
```

Run this again whenever you add a migration. Tests use RSpec and Factory Bot, with Spree's factories and test helpers coming from [`spree_dev_tools`](https://github.com/spree/spree_dev_tools). Add a factory for your model:

```ruby lib/spree_reviews/factories.rb
FactoryBot.define do
  factory :review, class: Spree::Review do
    product
    rating { 5 }
    approved { true }
  end
end
```

Then test your endpoints:

```ruby spec/controllers/spree/api/v3/admin/reviews_controller_spec.rb
require 'spec_helper'

RSpec.describe Spree::Api::V3::Admin::ReviewsController, type: :controller do
  render_views
  routes { Spree::Core::Engine.routes }

  include_context 'API v3 Admin authenticated'

  let!(:review) { create(:review, store: store) }

  before { request.headers.merge!(headers) }

  it 'lists reviews' do
    get :index, as: :json

    expect(response).to have_http_status(:ok)
    expect(json_response['data'].map { |r| r['id'] }).to include(review.prefixed_id)
  end
end
```

Run the suite:

```bash
bundle exec rspec
```

Test the logic you wrote — the approved-only scope, your hook handler, your subscriber — rather than behavior that Rails and Spree already guarantee.

## Related documentation

- [Customization Quickstart](/developer/customization/quickstart) - Choose the right extension point
- [Customizing the API](/developer/customization/api) - Controllers, serializers and permitted attributes
- [Services & Workflows](/developer/customization/workflows) - The full list of workflow hooks
- [Events](/developer/core-concepts/events) - Subscribe to Spree events
- [Permissions](/developer/customization/permissions) - Register permission scopes
- [Dashboard plugins](/developer/dashboard/plugins/overview) - Admin UI for your extension