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.

Added documentation on Preferences (#12520)

Damian Legawiecc2c63b25c4e2
diff --git a/core/app/models/spree/address.rb b/core/app/models/spree/address.rb
index a15968468c..965a5b0712 100644
--- a/core/app/models/spree/address.rb
+++ b/core/app/models/spree/address.rb
@@ -10,11 +10,7 @@ module Spree
include Spree::Security::Addresses
end
- if Rails::VERSION::STRING >= '7.1.0'
- serialize :preferences, type: Hash, coder: YAML, default: {}
- else
- serialize :preferences, Hash, default: {}
- end
+ serialize :preferences, type: Hash, coder: YAML, default: {}
NO_ZIPCODE_ISO_CODES ||= [
'AO', 'AG', 'AW', 'BS', 'BZ', 'BJ', 'BM', 'BO', 'BW', 'BF', 'BI', 'CM', 'CF', 'KM', 'CG',
diff --git a/core/app/models/spree/base.rb b/core/app/models/spree/base.rb
index 2ac7795c11..9ddd705155 100644
--- a/core/app/models/spree/base.rb
+++ b/core/app/models/spree/base.rb
@@ -1,11 +1,5 @@
class Spree::Base < ApplicationRecord
include Spree::Preferences::Preferable
- if Rails::VERSION::STRING >= '7.1.0'
- serialize :preferences, type: Hash, coder: YAML
- else
- serialize :preferences, Hash
- end
-
include Spree::RansackableAttributes
include Spree::TranslatableResourceScopes
diff --git a/core/lib/spree/core/preferences/preferable.rb b/core/lib/spree/core/preferences/preferable.rb
index f6a016b2ed..35b93922b4 100644
--- a/core/lib/spree/core/preferences/preferable.rb
+++ b/core/lib/spree/core/preferences/preferable.rb
@@ -38,6 +38,7 @@ module Spree::Preferences::Preferable
extend ActiveSupport::Concern
included do
+ serialize :preferences, type: Hash, coder: YAML if defined?(serialize)
extend Spree::Preferences::PreferableClassMethods
end
diff --git a/core/spec/models/spree/preferences/preferable_spec.rb b/core/spec/models/spree/preferences/preferable_spec.rb
index ff3f1d0072..38ab599a5c 100644
--- a/core/spec/models/spree/preferences/preferable_spec.rb
+++ b/core/spec/models/spree/preferences/preferable_spec.rb
@@ -3,6 +3,7 @@ require 'spec_helper'
describe Spree::Preferences::Preferable, type: :model do
before :all do
class A
+ include ActiveModel::Model
include Spree::Preferences::Preferable
attr_reader :id
diff --git a/docs/developer/core-concepts/preferences.mdx b/docs/developer/core-concepts/preferences.mdx
new file mode 100644
index 0000000000..b77ff946d3
--- /dev/null
+++ b/docs/developer/core-concepts/preferences.mdx
@@ -0,0 +1,175 @@
+## Runtime Preferences
+
+Runtime preferences are used as a configuration object for your application. They are stored in memory. The main use case is for application-wide preferences. For example, `Spree::Config.track_inventory_levels` is a runtime preference. All Spree preferences are defined in [core/lib/spree/core/configuration.rb](https://github.com/spree/spree/blob/main/core/lib/spree/core/configuration.rb).
+
+### Spree Configuration
+
+Here is a list of all the runtime preferences that are available in Spree.
+
+ | Configuration Key | Description | Default Value |
+ |------------------------------------|-------------------------------------------------------------------------------------------------------|---------------------|
+ | `allow_checkout_on_gateway_error` | Continues the checkout process even if the payment gateway error failed. | `false` |
+ | `address_requires_phone` | Determines whether a phone number is required for Addresses. | `true` |
+ | `alternative_shipping_phone` | Determines if an alternative phone number should be present for the shipping address on the checkout page. | `false` |
+ | `allow_guest_checkout` | Determines if guests can proceed to checkout without creating an account. | `true` |
+ | `always_include_confirm_step` | Determines if the confirmation step is always included in the checkout process, regardless of the payment method. | `false` |
+ | `auto_capture` | Depending on whether or not Spree is configured to "auto capture" the credit card, either a purchase or an authorize operation will be performed on the card (via the current credit card gateway). | `false` |
+ | `auto_capture_on_dispatch` | Captures payment for each shipment in Shipment#after_ship callback, and makes Shipment.ready when payment authorized. | `false` |
+ | `company` | Determines whether or not a field for "Company" displays on the address form. | `false` |
+ | `credit_to_new_allocation` | Determines if a new allocation is created anytime store credit is added. If not set, it will update the store credit's amount in place. | `false` |
+ | `disable_sku_validation` | Determines if the built-in SKU uniqueness validation is disabled. | `false` |
+ | `disable_store_presence_validation` | Determines if Store presence validation for Products and Payment Methods is disabled. | `false` |
+ | `expedited_exchanges` | Determines if an exchange shipment is kicked off upon return authorization save. Requires payment profiles to be supported on your gateway and a configured delayed job handler. | `false` |
+ | `expedited_exchanges_days_window` | The number of days the customer has to return their item after the expedited exchange is shipped to avoid being charged. | `14` |
+ | `restock_inventory` | Determines if inventory should be restocked when an order is canceled or returned | `true` |
+ | `return_eligibility_number_of_days` | The number of days after purchase within which a return can be initiated. | `365` |
+ | `send_core_emails` | Determines if core emails should be sent. This includes order confirmation and shipment tracking emails. | `true` |
+ | `show_products_without_price` | Determines if products without a price are shown in the storefront and Storefront API | `false` |
+ | `tax_using_ship_address` | Determines if tax information should be based on shipping address, rather than the billing address. | `true` |
+ | `track_inventory_levels` | Determines if inventory levels should be tracked when products are purchased at checkout. This option causes new `InventoryUnit` objects to be created when a product is bought. | `true` |
+
+### Spree Initializer
+
+To change values for these preferences, you need to edit your `config/initializers/spree.rb` file.
+
+For example, to disable the `expedited_exchanges` feature, you would add the following line:
+
+```ruby
+Spree.config do |config|
+ config.expedited_exchanges = false
+end
+```
+
+<Note>
+ Remember to restart your Rails server after changing these values.
+</Note>
+
+### Accessing Configuration
+
+To access these preferences in your application, you can use the `Spree::Config` module. For example, to access the `expedited_exchanges` preference, you can do the following:
+
+```ruby
+Spree::Config.expedited_exchanges
+```
+
+This will return the current value of the `expedited_exchanges` preference. You can also set the value of a preference using the `Spree::Config` module. For example, to set the `expedited_exchanges` preference to `true`, you can do the following:
+
+```ruby
+Spree::Config.expedited_exchanges = true
+```
+
+This will set the `expedited_exchanges` preference to `true` for the current process. After restarting the Rails server, the preference will return to the default value or the one set in the initializer.
+
+## Model Preferences
+
+Model preferences are used to store preferences for a specific model instance. They are stored in the database. The main use case is for user-specific preferences. For example, `user.preferred_language` is a model preference.
+
+### Defining Model Preferences
+
+To define a model preference, you need to add them to your model class.
+
+Firstly generate a migration to add the `preferences` column to the table.
+
+```ruby
+rails g migration AddPreferencesToSpreeUsers preferences:text
+```
+
+Run the migration.
+
+```ruby
+rails db:migrate
+```
+
+Define the preference in your model.
+
+```ruby
+class Spree::User < ApplicationRecord
+ # ... you existing code ...
+
+ # include the preferable module
+ include Spree::Preferences::Preferable
+ # define the preferences
+ preference :language, :string, default: "English"
+ preference :sms_marketing, :boolean, default: false
+end
+```
+
+This will add a `language` preference to the `User` model. The preference will be stored in the newly created `preferences` column of the `spree_users` table. You can add more preferences to the model in the same way.
+
+### Accessing Model Preferences
+
+Once preferences have been defined for a model, they can be accessed either using the shortcut methods that are generated for each preference or the generic methods that are not specific to a particular preference.
+
+#### Shortcut Methods
+
+There are several shortcut methods that are generated. They are shown below.
+
+Query methods:
+
+```ruby
+user.prefers_sms_marketing? # => false
+```
+
+Reader methods:
+
+```ruby
+user.preferred_sms_marketing # => false
+user.preferred_language # => "English"
+```
+
+Writer methods:
+
+```ruby
+user.prefers_sms_marketing = false # => false
+user.preferred_language = "English" # => "English"
+```
+
+<Note>
+ Remember to run `user.save` after setting the preference value to save the changes to the database.
+</Note>
+
+Check if a preference is available:
+
+```ruby
+user.has_preference? :sms_marketing
+```
+
+#### Generic Methods
+
+Each shortcut method is essentially a wrapper for the various generic methods shown below:
+
+Query method:
+
+```ruby
+user.prefers?(:sms_marketing) # => false
+user.prefers?(:language) # => false
+```
+
+Reader methods:
+
+```ruby
+user.preferred(:sms_marketing) # => false
+user.preferred(:language) # => "English"
+```
+
+```ruby
+user.get_preference :sms_marketing
+user.get_preference :language
+```
+
+Writer method:
+
+```ruby
+user.set_preference(:sms_marketing, false) # => false
+user.set_preference(:language, "English") # => "English"
+```
+
+#### Accessing All Preferences
+
+You can get a hash of all stored preferences by accessing the `preferences` helper:
+
+```ruby
+user.preferences # => {"language"=>"English", "sms_marketing"=>false}
+```
+
+This hash will contain the value for every preference that has been defined for the model instance, whether the value is the default or one that has been previously stored.
\ No newline at end of file
diff --git a/docs/developer/customization/preferences.mdx b/docs/developer/customization/preferences.mdx
deleted file mode 100644
index 3ad395dedd..0000000000
--- a/docs/developer/customization/preferences.mdx
+++ /dev/null
@@ -1,302 +0,0 @@
-# Preferences
-
-## Overview
-
-Spree Preferences support general application configuration and preferences per model instance. Spree comes with preferences for your application like `track_inventory_levels`. Additional preferences can be added by your application or included extensions.
-
-To implement preferences for a model, simply add a new column called `preferences`. This is an example migration for the `spree_products` table:
-
-```ruby
-class AddPreferencesColumnToSpreeProducts < ActiveRecord::Migration[4.2]
- def change
- add_column :spree_products, :preferences, :text
- end
-end
-```
-
-This will work because `Spree::Product` is a subclass of `Spree::Base`. If found, the `preferences` attribute gets serialized into a `Hash` and merged with the default values.
-
-As another example, you might want to add preferences for users to manage their notification settings. Just make sure your `User` model inherits from `Spree::Base` then add the `preferences` column. You'll then be able to define preferences for `User`s without adding extra columns to the database table.
-
-> If you're using `spree_auth_devise`, note that the provided `Spree::User` doesn't inherit from `Spree::Base`.
-
-Extensions may add to the Spree General Settings or create their own namespaced preferences.
-
-The first several sections of this guide describe preferences in a very general way. If you're just interested in making modifications to the existing preferences, you can skip ahead to the [Configuring Spree Preferences section](preferences#configuring-spree-preferences). If you would like a more in-depth understanding of the underlying concepts used by the preference system, please read on.
-
-### Motivation
-
-Preferences for models within an application are very common. Although the rule of thumb is to keep the number of preferences available to a minimum, sometimes it's necessary if you want users to have optional preferences like disabling e-mail notifications.
-
-Both use cases are handled by Spree Preferences. They are easy to define, provide quick cached reads, persist across restarts and do not require additional columns to be added to your models' tables.
-
-## General Settings
-
-Spree comes with many application-wide preferences. They are defined in `core/app/models/spree/app_configuration.rb` and made available to your code through `Spree::Config`, e.g., `Spree::Config.track_inventory_levels`.
-
-A limited set of the general settings are available in the admin interface of your store (`/admin/general_settings`).
-
-You can add additional preferences under the `spree/app_configuration` namespace or create your own subclass of `Preferences::Configuration`.
-
-```ruby
-# These will be saved with key: spree/app_configuration/hot_salsa
-Spree::AppConfiguration.class_eval do
- preference :hot_salsa, :boolean
- preference :dark_chocolate, :boolean, default: true
- preference :color, :string
- preference :favorite_number
- preference :language, :string, default: 'English'
-end
-
-# Spree::Config is an instance of Spree::AppConfiguration
-Spree::Config.hot_salsa = false
-
-# Create your own class
-# These will be saved with key: kona/store_configuration/hot_coffee
-Kona::StoreConfiguration < Preferences::Configuration
- preference :hot_coffee, :boolean
- preference :color, :string, default: 'black'
-end
-
-KONA::STORE_CONFIG = Kona::StoreConfiguration.new
-puts KONA::STORE_CONFIG.hot_coffee
-```
-
-## Defining Preferences
-
-You can define preferences for a model within the model itself:
-
-```ruby
-class User < ActiveRecord::Base
- preference :hot_salsa, :boolean
- preference :dark_chocolate, :boolean, default: true
- preference :color, :string
- preference :favorite_number, :integer
- preference :language, :string, default: "English"
-end
-```
-
-In the above model, five preferences have been defined:
-
-* `hot_salsa`
-* `dark_chocolate`
-* `color`
-* `favorite_number`
-* `language`
-
-For each preference, a data type is provided. The types available are:
-
-* `boolean`
-* `string`
-* `password`
-* `integer`
-* `text`
-* `array`
-* `hash`
-
-An optional default value may be defined which will be used unless a value has been set for that specific instance.
-
-## Accessing Preferences
-
-Once preferences have been defined for a model, they can be accessed either using the shortcut methods that are generated for each preference or the generic methods that are not specific to a particular preference.
-
-### Shortcut Methods
-
-There are several shortcut methods that are generated. They are shown below.
-
-Query methods:
-
-```ruby
-user.prefers_hot_salsa? # => false
-user.prefers_dark_chocolate? # => false
-```
-
-Reader methods:
-
-```ruby
-user.preferred_color # => nil
-user.preferred_language # => "English"
-```
-
-Writer methods:
-
-```ruby
-user.prefers_hot_salsa = false # => false
-user.preferred_language = "English" # => "English"
-```
-
-Check if a preference is available:
-
-```ruby
-user.has_preference? :hot_salsa
-```
-
-### Generic Methods
-
-Each shortcut method is essentially a wrapper for the various generic methods shown below:
-
-Query method:
-
-```ruby
-user.prefers?(:hot_salsa) # => false
-user.prefers?(:dark_chocolate) # => false
-```
-
-Reader methods:
-
-```ruby
-user.preferred(:color) # => nil
-user.preferred(:language) # => "English"
-```
-
-```ruby
-user.get_preference :color
-user.get_preference :language
-```
-
-Writer method:
-
-```ruby
-user.set_preference(:hot_salsa, false) # => false
-user.set_preference(:language, "English") # => "English"
-```
-
-### Accessing All Preferences
-
-You can get a hash of all stored preferences by accessing the `preferences` helper:
-
-```ruby
-user.preferences # => {"language"=>"English", "color"=>nil}
-```
-
-This hash will contain the value for every preference that has been defined for the model instance, whether the value is the default or one that has been previously stored.
-
-### Default and Type
-
-You can access the default value for a preference:
-
-```ruby
-user.preferred_color_default # => 'blue'
-```
-
-Types are used to generate forms or display the preference. You can also get the type defined for a preference:
-
-```ruby
-user.preferred_color_type # => :string
-```
-
-## Configuring Spree Preferences
-
-Up until now we've been discussing the general preference system that was adapted to Spree. This has given you a general idea of what types of preference features are theoretically supported. Now, let's start to look specifically at how Spree is using these preferences for configuration.
-
-### Reading the Current Preferences
-
-At the heart of Spree preferences lies the `Spree::Config` constant. This object provides general access to the configuration settings anywhere in the application.
-
-These settings can be accessed from initializers, models, controllers, views, etc.
-
-The `Spree::Config` constant returns an instance of `Spree::AppConfiguration` which is where the default values for all of the general Spree preferences are defined.
-
-You can access these preferences directly in code. To see this in action, just fire up `rails console` and try the following:
-
-```ruby
->> Spree::Config.admin_products_per_page
-=> 10
-```
-
-The above examples show the default configuration values for these preferences. The defaults themselves are coded within the `Spree::AppConfiguration` class.
-
-```ruby
-class Spree::AppConfiguration < Configuration
- #... snip ...
- preference :allow_guest_checkout, :boolean, default: true
- #... snip ...
-end
-```
-
-If you are using the default preferences without any modifications, then nothing will be stored in the database. If you set a value for the preference it will save it to `spree_preferences` or in our `preferences` column. It will use a memory cached version to maintain performance.
-
-### Overriding the Default Preferences
-
-The default Spree preferences in `Spree::AppConfiguration` can be changed using the `set` method of the `Spree::Config` module. For example to set the number of products shown on the products listing in the admin interface we could do the following:
-
-```ruby
->> Spree::Config.admin_products_per_page = 20
-=> 20
->> Spree::Config.admin_products_per_page
-=> 20
-```
-
-Here we are changing a preference to something other than the default as specified in `Spree::AppConfiguration`. In this case the preference system will persist the new value in the `spree_preferences` table.
-
-### Configuration Through the Spree Initializer
-
-During the Spree installation process, an initializer file is created within your application's source code. The initializer is found under `config/initializers/spree.rb`:
-
-```ruby
-Rails.application.config.after_initialize do
- Spree.config do |config|
- # Example:
- # Uncomment to stop tracking inventory levels in the application
- # config.track_inventory_levels = false
- end
-end
-```
-
-Note that if using Rails 7, you'll need to wrap the `Spree.config` block in an `Rails.application.config.after_initialize` block to avoid getting an error when booting up the app.
-
-The `Spree.config` block acts as a shortcut to setting `Spree::Config` multiple times. If you have multiple default preferences you would like to override within your code you may override them here. Using the initializer for setting the defaults is a nice shortcut, and helps keep your preferences organized in a standard location.
-
-For example, if you would like to tax using the shipping address you can accomplish this by doing the following:
-
-```ruby
-Spree.config do |config|
- config.tax_using_ship_address = true
-end
-```
-
-Initializing preferences in `config/initializers/spree.rb` will overwrite any changes that were made through the admin user interface when you restart.
-
-### Configuration Through the Admin Interface
-
-The Spree admin interface has several different screens where various settings can be configured. For instance, the `admin/general_settings` URL in your Spree application can be used to configure the values for the site name and the site URL. This is basically equivalent to calling `Spree::Config.set(currency: "CDN", currency_thousands_separator: " ")` directly in your Ruby code.
-
-## Site-Wide Preferences
-
-You can define preferences that are site-wide and don't apply to a specific instance of a model by creating a configuration file that inherits from `Spree::Preferences::Configuration`.
-
-```ruby
-class Spree::MyApplicationConfiguration < Spree::Preferences::Configuration
- preference :theme, :string, default: "Default"
- preference :show_splash_page, :boolean
- preference :number_of_articles, :integer
-end
-```
-
-In the above configuration file, three preferences have been defined:
-
-* theme
-* show_splash_page
-* number_of_articles
-
-It is recommended to create the configuration file in the `lib/` directory.
-
-Extensions can also define site-wide preferences. For more information on using preferences like this with extensions, check out the [Extensions Tutorial](/developer/contributing/creating-an-extension).
-
-### Configuring Site-Wide Preferences
-
-The recommended way to configure site-wide preferences is through an initializer. Let's take a look at configuring the preferences defined in the previous configuration example.
-
-```ruby
-module Spree
- MyApp::Config = Spree::MyApplicationConfiguration.new
-end
-
-MyApp::Config[:theme] = "blue_theme"
-MyApp::Config[:show_spash_page] = true
-MyApp::Config[:number_of_articles] = 5
-```
-
-The `MyApp` name used here is an example and should be replaced with your actual application's name, found in `config/application.rb`.
-
-The above example will configure the preferences we defined earlier. Take note of the second line. In order to set and get preferences using `MyApp::Config`, we must first instantiate the configuration object.
\ No newline at end of file
diff --git a/docs/mint.json b/docs/mint.json
index dbf8c6d9c1..f43e8720ef 100644
--- a/docs/mint.json
+++ b/docs/mint.json
@@ -92,7 +92,8 @@
"developer/core-concepts/promotions",
"developer/core-concepts/shipments",
"developer/core-concepts/addresses",
- "developer/core-concepts/i18n"
+ "developer/core-concepts/i18n",
+ "developer/core-concepts/preferences"
]
},