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.

Rename metafields to custom fields (#14415)

Damian Legawiec268b28b30352
diff --git a/docs/developer/upgrades/5.6-to-6.0.mdx b/docs/developer/upgrades/5.6-to-6.0.mdx
index e89b47a078..ecded983e7 100644
--- a/docs/developer/upgrades/5.6-to-6.0.mdx
+++ b/docs/developer/upgrades/5.6-to-6.0.mdx
@@ -310,6 +310,21 @@ These were deprecated in 5.x and are **gone now** — there is no bridge, so cal
| `Product.add_search_scope` | plain `scope :name, -> { ... }` |
| `Spree::Image::Configuration::ActiveStorage` | deleted — an empty no-op module; all logic lives in `Spree::Asset` |
| `Spree::OrderRouting::Strategy::Legacy` | `Spree::OrderRouting::Strategy::Rules` (see below) |
+| `private_metafields` association | read `custom_fields` and filter, or query `Spree::CustomField.admin_only` |
+
+### Custom fields replace metafields
+
+The metafields system is now custom fields: `Spree::CustomField` and `Spree::CustomFieldDefinition`, stored in `spree_custom_fields` and `spree_custom_field_definitions`. The legacy class names, the concern, and the reader methods all keep working for one release with a deprecation warning (see the table further down), so most applications need no code change to upgrade.
+
+Two things do change under you, both handled by `db:migrate`:
+
+- **Visibility is a boolean.** The tri-state `display_on` column collapses into `storefront_visible`. Definitions that were `back_end` become `storefront_visible: false`; everything else becomes `true`. The `front_end`-only value never meant hidden-from-staff and folds into `true`.
+- **Two columns are renamed.** `name` becomes `label`, and `metafield_type` becomes `field_type`. Reading `field_type` returns the API token (`short_text`) rather than the Ruby class name; use `field_type_class_name` when you need the class.
+- **Rich-text values leave Action Text.** `Spree::CustomFields::RichText` stores sanitized HTML in the same `value` column as every other type, so reading `value` returns a String rather than an `ActionText::RichText`. Existing bodies are copied across by the migration; the Action Text rows stay behind as a rollback path until 6.1. Code calling `custom_field.value.body` should read `value` directly.
+
+Two behavior notes for extension authors: `Spree::Metadata` no longer includes the custom-fields concern (metadata is the private, schemaless system — include `Spree::HasCustomFields` explicitly if a model needs both), and rich-text values are now sanitized on save, so markup outside the allowlist is stripped rather than stored.
+
+**BREAKING — product CSV.** Custom-field columns are now prefixed `custom_field.` instead of `metafield.` (for example `custom_field.custom.material`). Exports emit the new prefix and imports only recognise the new prefix, so update any saved import templates and any integration that reads the export. A file still using the old prefix imports without its custom-field values rather than failing.
### The Legacy order-routing strategy is gone
@@ -387,6 +402,13 @@ Every rename keeps the legacy name working for one release with a deprecation wa
| `order.completed` event | `order.placed` |
| Calling cart services with `order:` kwargs | `cart:` kwargs |
| `OrderWalkthrough` (testing support) | factories: `:cart_ready_for_delivery`, `:cart_ready_to_complete`, `:completed_order_with_totals` |
+| `Spree::Metafield`, `Spree::MetafieldDefinition`, `Spree::Metafields::*` | `Spree::CustomField`, `Spree::CustomFieldDefinition`, `Spree::CustomFields::*` |
+| `include Spree::Metafields` | `include Spree::HasCustomFields` |
+| `#set_metafield`, `#get_metafield`, `#has_metafield?` | `#set_custom_field`, `#get_custom_field`, `#has_custom_field?` |
+| `metafields` / `public_metafields` associations | `custom_fields` / `storefront_custom_fields` |
+| `.with_metafield_key`, `.with_metafield_key_value` | `.with_custom_field_key`, `.with_custom_field_key_value` |
+| `Spree.metafields` | `Spree.custom_fields` |
+| `CustomFieldDefinition#name`, `#metafield_type`, `#display_on` | `#label`, `#field_type`, `#storefront_visible` (columns renamed) |
## Staff permissions: roles are data
diff --git a/docs/plans/5.4-6.0-custom-fields-rename.md b/docs/plans/5.4-6.0-custom-fields-rename.md
index f92d683b1f..e645ca64a9 100644
--- a/docs/plans/5.4-6.0-custom-fields-rename.md
+++ b/docs/plans/5.4-6.0-custom-fields-rename.md
@@ -1,10 +1,24 @@
# Metafields → Custom Fields Rename
-**Status:** 5.4 serializer bridge ✓; 5.5 alias classes (`Spree::CustomField`, `Spree::CustomFieldDefinition`) ✓; 6.0 model/table rename pending
-**Target:** 5.4 (Store API serializer bridge ✓) + 5.5 (Admin CRUD API + SDK + `Spree::CustomField` constant alias ✓) + 6.0 (model/table rename + visibility simplification + STI rename)
+**Status:** COMPLETE — 5.4 serializer bridge ✓; 5.5 alias classes ✓; 6.0 model/table rename + visibility simplification ✓ (2026-08-09)
+**Target:** 5.4 (Store API serializer bridge ✓) + 5.5 (Admin CRUD API + SDK + `Spree::CustomField` constant alias ✓) + 6.0 (model/table rename + visibility simplification + STI rename ✓)
**Depends on:** None — 5.4/5.5 changes are additive. 6.0 rename is part of the model rename wave.
**Author:** Damian + Claude
-**Last updated:** 2026-07-27
+**Last updated:** 2026-08-09
+
+## 6.0 delivery notes (what actually shipped)
+
+The rename landed in one wave. Deviations from the plan as written above:
+
+- **Deprecation bridges everywhere, not a clean break.** Per the standing convention, every legacy name keeps working for one release with a warning: `Spree::Metafield`, `Spree::MetafieldDefinition`, `Spree::Metafields::*` (constant aliases), `include Spree::Metafields` (the module doubles as concern and STI namespace), `Spree.metafields`, the `metafields`/`public_metafields`/`private_metafields` associations, `set_metafield`/`get_metafield`/`has_metafield?`/`metafields_attributes=`, `.with_metafield_key*`, and the renamed definition columns (`name`, `metafield_type`, `display_on`). All are removed in 6.1.
+- **`private_metafields` has no forward equivalent.** The plan dropped it; the deprecated association still resolves (backed by the new `admin_only` scope), but there is no `admin_only_custom_fields` association. Read `custom_fields` and filter, or query `Spree::CustomField.admin_only`.
+- **`name` → `label` is a real column rename**, not the 5.5 `alias_attribute`. The definitions table now has `label`; `field_type` replaces `metafield_type` and holds the STI class name while the `field_type` *reader* returns the API token (`short_text`). `field_type_class_name` exposes the raw class name — internal callers that set a custom field's STI `type` must use it.
+- **CSV headers are a clean break** (decision 2026-08-09): export and import both use `custom_field.<namespace>.<key>`; the legacy `metafield.` prefix is not accepted. Documented as BREAKING in the 5.6→6.0 upgrade guide.
+- **No upgrade rake task.** All persisted data (STI type strings, both column renames, the `display_on` → `storefront_visible` conversion) is handled inside the migration, because a renamed STI class cannot load its own legacy rows — the substitution has to happen before the app boots on the new code. Nothing was left for the manifest.
+- **The metadata cleanup was deferred** (decision 2026-08-09). Dropping `public_metadata` and renaming `private_metadata` → `metadata` spans nearly every table and is independent of this rename; it needs its own migration and review.
+- **`Spree::DisplayOn` stays** for PaymentMethod and DeliveryMethod. Only `CustomFieldDefinition` left the concern, gaining a real `storefront_visible` boolean column.
+- **Rich-text custom fields left ActionText** (the slice of `6.0-rich-text-descriptions.md` that overlaps this rename). `Spree::CustomFields::RichText` now stores sanitized HTML in the shared `value` column like every other type; the migration copies existing bodies across, leaving the Action Text rows as the rollback path. The other five ActionText users (Category, Collection, Policy, `Order#internal_note`, customer internal notes) and the gem dependency stay with that plan.
+- **`Spree::Metadata` no longer includes the custom-fields concern.** Including one silently pulled in the other, which contradicts the two-system boundary this rename exists to draw — and the guard was inert anyway, testing the concern's own ancestors rather than the including model's. Models wanting both now include both.
## Summary
@@ -443,7 +457,7 @@ Full internal rename. Part of the 6.0 model rename wave alongside Shipment→Ful
| `Spree::MetafieldDefinition` | `Spree::CustomFieldDefinition` | |
| `Spree::Metafields::ShortText` | `Spree::CustomFields::ShortText` | STI subclass |
| `Spree::Metafields::LongText` | `Spree::CustomFields::LongText` | STI subclass |
-| `Spree::Metafields::RichText` | `Spree::CustomFields::RichText` | STI subclass. **Value storage also migrates in the same 6.0 wave**: `has_rich_text :value` (ActionText) → the existing `value` text column, sanitized — owned by `6.0-rich-text-descriptions.md` Phase 5 (the dashboard already writes Tiptap HTML through ActionText's Trix allowlist today) |
+| `Spree::Metafields::RichText` | `Spree::CustomFields::RichText` | STI subclass. Value storage migrated in the same wave ✓: `has_rich_text :value` (ActionText) → the existing `value` text column, sanitized via `sanitizes_rich_text` — the slice of `6.0-rich-text-descriptions.md` Phase 5 that this plan owns |
| `Spree::Metafields::Number` | `Spree::CustomFields::Number` | STI subclass |
| `Spree::Metafields::Boolean` | `Spree::CustomFields::Boolean` | STI subclass |
| `Spree::Metafields::Json` | `Spree::CustomFields::Json` | STI subclass |
diff --git a/docs/plans/6.0-rich-text-descriptions.md b/docs/plans/6.0-rich-text-descriptions.md
index 008d1be288..7c1e54a946 100644
--- a/docs/plans/6.0-rich-text-descriptions.md
+++ b/docs/plans/6.0-rich-text-descriptions.md
@@ -143,7 +143,7 @@ Both target columns **already exist** (`spree_taxons.description`, `spree_taxon_
### Phase 5: CustomFields::RichText + internal notes + consumer sweep + drop ActionText
-- `CustomFields::RichText`: `has_rich_text :value` → the already-existing `value` text column (currently ignored by the model), sanitized; rake copy task. Listed in `5.4-6.0-custom-fields-rename.md`'s 6.0 wave alongside the STI rename.
+- `CustomFields::RichText`: **shipped** with the custom-fields rename (spree/spree#14415). `has_rich_text :value` is gone; the model stores sanitized HTML in the existing `value` text column via `sanitizes_rich_text`. The copy runs inside the rename migration rather than a rake task — the STI class name changes in the same migration, so the Action Text rows (filed under the pre-rename base class `Spree::Metafield`) are unreachable afterwards. Source rows are left in place as the rollback path and are dropped with the tables in 6.1.
- `Order#internal_note` + `User` internal_note → text columns + `sanitizes_rich_text`; serializers/params standardized (`internal_note` + `internal_note_html` on both).
- Consumer sweep: Meilisearch serialize, Google feed, CSV export (above); model generator template's ActionText line (`generators/spree/model/templates/model.rb.tt:22`).
- Then: remove `mobility-actiontext` from `spree_core.gemspec`, drop migrated `action_text_rich_texts` rows, drop the ActionText tables in 6.1 alongside the other legacy drops.
diff --git a/packages/admin-sdk/src/types/generated/Category.ts b/packages/admin-sdk/src/types/generated/Category.ts
index f2247de17e..f44d8e70bb 100644
--- a/packages/admin-sdk/src/types/generated/Category.ts
+++ b/packages/admin-sdk/src/types/generated/Category.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 6c717d21c07f4658e3af496b37777bc4
+// Typelizer digest a664c2965050201bf085ede78defb625
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {CustomField} from '@/types'
diff --git a/packages/admin-sdk/src/types/generated/Collection.ts b/packages/admin-sdk/src/types/generated/Collection.ts
index f83e5b6797..98bd1513ba 100644
--- a/packages/admin-sdk/src/types/generated/Collection.ts
+++ b/packages/admin-sdk/src/types/generated/Collection.ts
@@ -1,4 +1,4 @@
-// Typelizer digest e0804a3a826b203f579dedf3d9bd6989
+// Typelizer digest cb15e99ce865820888863d10f686358a
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {CustomField, CollectionRule} from '@/types'
diff --git a/packages/admin-sdk/src/types/generated/CustomField.ts b/packages/admin-sdk/src/types/generated/CustomField.ts
index 479277a3b1..5c1344ae01 100644
--- a/packages/admin-sdk/src/types/generated/CustomField.ts
+++ b/packages/admin-sdk/src/types/generated/CustomField.ts
@@ -1,11 +1,11 @@
-// Typelizer digest faa4fda8999ba5b715e8304148c4fa66
+// Typelizer digest 86edfcd31c0cfb6e8af0430394da09a8
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
interface CustomField {
id: string;
label: string;
- /** @deprecated Use `field_type` instead. The legacy `type` field returns the Ruby STI class name (e.g. `Spree::Metafields::ShortText`) and will be removed in a future minor. */
+ /** @deprecated Use `field_type` instead. The legacy `type` field returns the Ruby STI class name (e.g. `Spree::CustomFields::ShortText`) and will be removed in a future minor. */
type: string;
field_type: 'short_text' | 'long_text' | 'rich_text' | 'number' | 'boolean' | 'json';
key: string;
diff --git a/packages/admin-sdk/src/types/generated/Product.ts b/packages/admin-sdk/src/types/generated/Product.ts
index 4e58c10413..7b4625da28 100644
--- a/packages/admin-sdk/src/types/generated/Product.ts
+++ b/packages/admin-sdk/src/types/generated/Product.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 49bc26abda41323cbfc7ead43c7bb48f
+// Typelizer digest 3853e4b436716a36144fad3ea8ed46f0
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {Price, PriceHistory, Media, Variant, OptionType, OptionValue, Category, CustomField, Collection, ProductPublication, Channel, ProductType} from '@/types'
diff --git a/packages/admin-sdk/src/types/generated/Variant.ts b/packages/admin-sdk/src/types/generated/Variant.ts
index 2c2d96942e..31f61b321f 100644
--- a/packages/admin-sdk/src/types/generated/Variant.ts
+++ b/packages/admin-sdk/src/types/generated/Variant.ts
@@ -1,4 +1,4 @@
-// Typelizer digest bf292878d4138bfabe39f056fe2dc9d9
+// Typelizer digest d796ffae294976865ef0fdb4ec0a4f34
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {Price, PriceHistory, Media, OptionValue, CustomField, StockItem} from '@/types'
diff --git a/packages/admin-sdk/tests/mocks/handlers.ts b/packages/admin-sdk/tests/mocks/handlers.ts
index b905eed166..f3cf355085 100644
--- a/packages/admin-sdk/tests/mocks/handlers.ts
+++ b/packages/admin-sdk/tests/mocks/handlers.ts
@@ -7,7 +7,7 @@ export const fixtures = {
customField: {
id: 'cf_1',
label: 'Fabric',
- type: 'Spree::Metafields::ShortText',
+ type: 'Spree::CustomFields::ShortText',
field_type: 'short_text',
key: 'specs.fabric',
value: 'wool',
diff --git a/packages/dashboard-core/src/components/resource-table.tsx b/packages/dashboard-core/src/components/resource-table.tsx
index 64e7c2e6d7..9c4f63233f 100644
--- a/packages/dashboard-core/src/components/resource-table.tsx
+++ b/packages/dashboard-core/src/components/resource-table.tsx
@@ -180,6 +180,8 @@ interface ResourceTableProps<T> {
* `filter_key` (`cf_*`), which the backend accepts as sort and
* filter attributes.
*/
+ customFieldColumns?: ColumnDef<T>[]
+ /** @deprecated Use `customFieldColumns` — removed in Spree 6.1. */
metafieldColumns?: ColumnDef<T>[]
}
@@ -204,6 +206,7 @@ export function ResourceTable<T extends Record<string, any>>({
reorder,
bulkActions,
rowActions,
+ customFieldColumns,
metafieldColumns,
}: ResourceTableProps<T>) {
const table = getTable<T>(tableKey)
@@ -244,11 +247,12 @@ export function ResourceTable<T extends Record<string, any>>({
const [searchInput, setSearchInput] = useState(search ?? '')
const deferredSearch = useDeferredValue(searchInput)
- // Registry columns + dynamic metafield columns. Memoized so the toolbar's
+ // Registry columns + dynamic custom-field columns. Memoized so the toolbar's
// internal memos (FilterPanel `items` stability) keep stable deps.
+ const extraColumns = customFieldColumns ?? metafieldColumns
const allColumns = useMemo(
- () => [...table.columns, ...(metafieldColumns ?? [])],
- [table, metafieldColumns],
+ () => [...table.columns, ...(extraColumns ?? [])],
+ [table, extraColumns],
)
const displayableColumns = useMemo(
() => allColumns.filter((c) => c.displayable !== false),
diff --git a/packages/dashboard-core/src/lib/permissions.ts b/packages/dashboard-core/src/lib/permissions.ts
index d43e0f5faa..66f512fd08 100644
--- a/packages/dashboard-core/src/lib/permissions.ts
+++ b/packages/dashboard-core/src/lib/permissions.ts
@@ -29,7 +29,7 @@ export const Subject = {
ReturnReason: 'Spree::ReturnReason',
ClaimReason: 'Spree::ClaimReason',
RefundReason: 'Spree::RefundReason',
- CustomFieldDefinition: 'Spree::MetafieldDefinition',
+ CustomFieldDefinition: 'Spree::CustomFieldDefinition',
PaymentMethod: 'Spree::PaymentMethod',
DeliveryMethod: 'Spree::DeliveryMethod',
DeliveryZone: 'Spree::DeliveryZone',
diff --git a/packages/dashboard/src/components/spree/custom-fields/custom-fields-inline.tsx b/packages/dashboard/src/components/spree/custom-fields/custom-fields-inline.tsx
index 6728160ada..6a9698a49b 100644
--- a/packages/dashboard/src/components/spree/custom-fields/custom-fields-inline.tsx
+++ b/packages/dashboard/src/components/spree/custom-fields/custom-fields-inline.tsx
@@ -146,7 +146,7 @@ function useCustomFieldsContext() {
}
// Deep-equality check for custom-field values. Reference equality (`===`) is
-// wrong for JSON metafields because each query refetch hands back a fresh
+// wrong for JSON custom fields because each query refetch hands back a fresh
// object reference even when the content hasn't changed — every blur would
// then re-commit a no-op mutation. Canonical JSON stringification handles
// scalars (returns the same canonical form for "a" / 1 / true / null) and
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/index.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/index.tsx
index 33fbd40356..60fba78a3d 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/index.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/index.tsx
@@ -337,7 +337,7 @@ function ProductsPage() {
// Searchable/sortable custom fields become full table columns: displayable
// (opt-in via the column selector), sortable when the definition allows it,
// and filterable with the operator set matching the field type.
- const metafieldColumns = useMemo<ColumnDef<Product>[]>(() => {
+ const customFieldColumns = useMemo<ColumnDef<Product>[]>(() => {
const definitions = definitionsResponse?.data ?? []
return definitions
.filter(
@@ -370,7 +370,7 @@ function ProductsPage() {
searchParams={searchParams}
bulkActions={bulkActions}
rowActions={renderRowActions}
- metafieldColumns={metafieldColumns}
+ customFieldColumns={customFieldColumns}
actions={(ctx) => (
<>
<ImportButton
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsx
index bcec8b862f..fdbc263bb3 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsx
@@ -67,7 +67,7 @@ function NewProductPage() {
...extensionSubmitValues('product', form),
}
// Only ship custom_fields when there are some — empty arrays are noise
- // and Spree::Metafields#custom_fields= already no-ops on empty input.
+ // and Spree::HasCustomFields#custom_fields= already no-ops on empty input.
if (custom_fields && custom_fields.length > 0) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(payload as any).custom_fields = custom_fields
diff --git a/packages/dashboard/src/schemas/category.ts b/packages/dashboard/src/schemas/category.ts
index afcec41c03..15f4e55069 100644
--- a/packages/dashboard/src/schemas/category.ts
+++ b/packages/dashboard/src/schemas/category.ts
@@ -26,7 +26,7 @@ export const categoryFormSchema = z.object({
meta_title: z.string(),
meta_description: z.string(),
// Inline custom field values keyed by definition id, upserted server-side via
- // Spree::Metafields#custom_fields= (the categories controller permits them).
+ // Spree::HasCustomFields#custom_fields= (the categories controller permits them).
// Persisted with the rest of the category on the page's Save button.
custom_fields: z.array(customFieldFormSchema).optional(),
...imageFields,
diff --git a/packages/dashboard/src/schemas/custom-field-definition.ts b/packages/dashboard/src/schemas/custom-field-definition.ts
index 52ca035ece..7537bff7aa 100644
--- a/packages/dashboard/src/schemas/custom-field-definition.ts
+++ b/packages/dashboard/src/schemas/custom-field-definition.ts
@@ -6,7 +6,7 @@ import { i18n } from '@spree/dashboard-core'
import { requiredMessage } from '@spree/dashboard-ui'
import { z } from 'zod/v4'
-// Mirrors `Spree::Metafield::FIELD_TYPE_TOKENS` on the backend. Keep in sync
+// Mirrors `Spree::CustomField::FIELD_TYPE_TOKENS` on the backend. Keep in sync
// with the typelized `field_type` union on `CustomFieldDefinition`. Labels
// come from i18n via `fieldTypeLabel()` below.
export const FIELD_TYPES = [
@@ -41,7 +41,7 @@ export function fieldTypeLabel(value: string): string {
}
// Owner types that have a first-class admin UI. The server allows more (see
-// `Spree.metafields.enabled_resources`); these are the ones admins can pick
+// `Spree.custom_fields.enabled_resources`); these are the ones admins can pick
// when defining a field. Extending this is a one-line add — the API already
// accepts any resource type registered in core.
export const DEFAULT_RESOURCE_TYPES = [
@@ -120,7 +120,7 @@ export function customFieldDefinitionValuesToUpdateParams(
v: CustomFieldDefinitionFormValues,
): CustomFieldDefinitionUpdateParams {
// `resource_type` and `field_type` are intentionally omitted — changing
- // either would orphan or invalidate stored values. `Spree::Metafield` rows
+ // either would orphan or invalidate stored values. `Spree::CustomField` rows
// serialize via their own STI subclass (set from the definition at write
// time), so flipping `field_type` post-hoc would leave existing values
// misinterpreted by the UI. The controller still accepts these fields;
diff --git a/packages/dashboard/src/schemas/product.ts b/packages/dashboard/src/schemas/product.ts
index 138efb5891..f56f069587 100644
--- a/packages/dashboard/src/schemas/product.ts
+++ b/packages/dashboard/src/schemas/product.ts
@@ -124,7 +124,7 @@ export const productFormSchema = z.object({
variants: z.array(variantFormSchema).optional(),
// Inline custom field values, keyed by definition id (upserted server-side
- // via Spree::Metafields#custom_fields=). Partial updates: omitting a
+ // via Spree::HasCustomFields#custom_fields=). Partial updates: omitting a
// definition leaves its value untouched.
custom_fields: z.array(customFieldFormSchema).optional(),
diff --git a/packages/sdk/src/types/generated/Category.ts b/packages/sdk/src/types/generated/Category.ts
index a3178a84cb..f07ed1e4ab 100644
--- a/packages/sdk/src/types/generated/Category.ts
+++ b/packages/sdk/src/types/generated/Category.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 147673e724648591c36c6c0345cd4272
+// Typelizer digest 4a4eaa6142cd8caa6149e5771b9afcfc
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {CustomField} from '@/types'
diff --git a/packages/sdk/src/types/generated/Collection.ts b/packages/sdk/src/types/generated/Collection.ts
index cf580639d0..05678c63ff 100644
--- a/packages/sdk/src/types/generated/Collection.ts
+++ b/packages/sdk/src/types/generated/Collection.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 0b9f33a1c89939e25130e731369b0f80
+// Typelizer digest a7e6fd6063a93a58924c567439e30449
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {CustomField} from '@/types'
diff --git a/packages/sdk/src/types/generated/CustomField.ts b/packages/sdk/src/types/generated/CustomField.ts
index 9845503528..65f5bde217 100644
--- a/packages/sdk/src/types/generated/CustomField.ts
+++ b/packages/sdk/src/types/generated/CustomField.ts
@@ -1,11 +1,11 @@
-// Typelizer digest ff1e6016f1b576b10d24ee23ac110163
+// Typelizer digest 56b576d6ef0d9c0fb9565241c1a2e115
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
interface CustomField {
id: string;
label: string;
- /** @deprecated Use `field_type` instead. The legacy `type` field returns the Ruby STI class name (e.g. `Spree::Metafields::ShortText`) and will be removed in a future minor. */
+ /** @deprecated Use `field_type` instead. The legacy `type` field returns the Ruby STI class name (e.g. `Spree::CustomFields::ShortText`) and will be removed in a future minor. */
type: string;
field_type: 'short_text' | 'long_text' | 'rich_text' | 'number' | 'boolean' | 'json';
key: string;
diff --git a/packages/sdk/src/types/generated/Product.ts b/packages/sdk/src/types/generated/Product.ts
index 3f65ae1496..a7b6fd6727 100644
--- a/packages/sdk/src/types/generated/Product.ts
+++ b/packages/sdk/src/types/generated/Product.ts
@@ -1,4 +1,4 @@
-// Typelizer digest b2e948164151b01e23a6d84ad624195b
+// Typelizer digest 18a248afd35e9af13e218fb6b62576f7
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {Price, PriceHistory, Media, Variant, OptionType, OptionValue, Category, CustomField} from '@/types'
diff --git a/packages/sdk/src/types/generated/Variant.ts b/packages/sdk/src/types/generated/Variant.ts
index 7fa215597d..28e596a3e5 100644
--- a/packages/sdk/src/types/generated/Variant.ts
+++ b/packages/sdk/src/types/generated/Variant.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 60f48e98014c8bb17ecd142b8f9ae110
+// Typelizer digest 38bbefbdf6fa332789331b0ded11a43e
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {Price, PriceHistory, Media, OptionValue, CustomField} from '@/types'
diff --git a/spree/api/app/controllers/spree/api/v3/admin/categories_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/categories_controller.rb
index 780d4c72ca..21f05ce6f6 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/categories_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/categories_controller.rb
@@ -71,9 +71,9 @@ module Spree
:meta_title, :meta_description, :meta_keywords,
:image, :square_image,
# Inline custom field values keyed by definition id. The model
- # setter (Spree::Metafields#custom_fields=) validates each entry
+ # setter (Spree::HasCustomFields#custom_fields=) validates each entry
# against its definition. `value` is permitted as a scalar AND as
- # `value: []` / `value: {}` so JSON metafields round-trip whether
+ # `value: []` / `value: {}` so JSON custom_fields round-trip whether
# the parsed payload is an array or an object, while
# text/number/boolean ship scalars.
custom_fields: [:id, :custom_field_definition_id, :value, { value: [] }, { value: {} }]
diff --git a/spree/api/app/controllers/spree/api/v3/admin/custom_field_definitions_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/custom_field_definitions_controller.rb
index f6d43dc2c5..2629b69091 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/custom_field_definitions_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/custom_field_definitions_controller.rb
@@ -20,9 +20,6 @@ module Spree
Spree.api.admin_custom_field_definition_serializer
end
- # `label`, `field_type`, `storefront_visible` are model-side aliases
- # (alias_attribute / accessors) on Spree::CustomFieldDefinition. The
- # API → DB column rename lands in 6.0 and this controller stays flat.
def permitted_params
params.permit(:namespace, :key, :label, :field_type,
:resource_type, :storefront_visible,
diff --git a/spree/api/app/controllers/spree/api/v3/admin/custom_fields_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/custom_fields_controller.rb
index 2784fcf596..73ed5dedc4 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/custom_fields_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/custom_fields_controller.rb
@@ -9,7 +9,7 @@ module Spree
class CustomFieldsController < ResourceController
# POST /api/v3/admin/<parent>/<parent_id>/custom_fields
def create
- @resource = @parent.metafields.new(permitted_params)
+ @resource = @parent.custom_fields.new(permitted_params)
authorize_resource!(@resource, :create)
if @resource.save
@@ -44,7 +44,7 @@ module Spree
end
def parent_association
- :metafields
+ :custom_fields
end
def set_parent
@@ -104,7 +104,7 @@ module Spree
# and `'category'` because the routes expose taxons as categories
# (5.5 rename) while the model's element is still `'taxon'`.
def parent_route_map
- @parent_route_map ||= Spree.metafields.enabled_resources.each_with_object({}) do |klass, m|
+ @parent_route_map ||= Spree.custom_fields.enabled_resources.each_with_object({}) do |klass, m|
m[klass.model_name.element.to_s] = klass.name
end.merge('customer' => Spree.customer_class.name, 'category' => 'Spree::Category')
end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/imports_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/imports_controller.rb
index 3de981722d..f0590efb83 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/imports_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/imports_controller.rb
@@ -136,7 +136,7 @@ module Spree
# GET /api/v3/admin/imports/template?type=Spree::Imports::Products
#
- # CSV header row for the type's schema (including the metafield
+ # CSV header row for the type's schema (including the custom_field
# columns available for the model) — the "Download template" link
# in the admin dashboard.
def template
diff --git a/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb
index 9448486aee..bd78868c33 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/products_controller.rb
@@ -186,9 +186,9 @@ module Spree
metadata: {},
prices: [:amount, :compare_at_amount, :currency],
# Inline custom field values keyed by definition id. The model
- # setter (`Spree::Metafields#custom_fields=`) validates each
+ # setter (`Spree::HasCustomFields#custom_fields=`) validates each
# entry against its definition. We permit `value` as a scalar AND
- # as `value: []` / `value: {}` so JSON metafields round-trip
+ # as `value: []` / `value: {}` so JSON custom_fields round-trip
# whether the parsed payload is an array or an object, while
# text/number/boolean ship scalars.
custom_fields: [:id, :custom_field_definition_id, :value, { value: [] }, { value: {} }],
diff --git a/spree/api/app/controllers/spree/api/v3/store/products/filters_controller.rb b/spree/api/app/controllers/spree/api/v3/store/products/filters_controller.rb
index 4f5a6cbed6..6875f91e37 100644
--- a/spree/api/app/controllers/spree/api/v3/store/products/filters_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/store/products/filters_controller.rb
@@ -46,7 +46,7 @@ module Spree
search_filters&.sort_by(&:first)&.to_json,
max_updated,
product_count,
- search_provider.metafield_schema.schema_version
+ search_provider.custom_field_schema.schema_version
]
parts.compact.join('/')
diff --git a/spree/api/app/serializers/spree/api/v3/admin/category_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/category_serializer.rb
index 333084ea45..3da5d1d1ec 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/category_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/category_serializer.rb
@@ -26,8 +26,7 @@ module Spree
resource: proc { Spree.api.admin_category_serializer },
if: proc { expand?('ancestors') }
- many :metafields,
- key: :custom_fields,
+ many :custom_fields,
resource: proc { Spree.api.admin_custom_field_serializer },
if: proc { expand?('custom_fields') }
end
diff --git a/spree/api/app/serializers/spree/api/v3/admin/collection_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/collection_serializer.rb
index 47b1c235ec..6e27cdd5d3 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/collection_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/collection_serializer.rb
@@ -19,8 +19,7 @@ module Spree
if: proc { expand?('rules') }
# Override inherited custom_fields to use the admin serializer.
- many :metafields,
- key: :custom_fields,
+ many :custom_fields,
resource: proc { Spree.api.admin_custom_field_serializer },
if: proc { expand?('custom_fields') }
end
diff --git a/spree/api/app/serializers/spree/api/v3/admin/custom_field_definition_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/custom_field_definition_serializer.rb
index 61fd87734c..74ddbec559 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/custom_field_definition_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/custom_field_definition_serializer.rb
@@ -8,7 +8,7 @@ module Spree
typelize namespace: :string,
key: :string,
label: :string,
- field_type: Spree::Metafield::FIELD_TYPE_TOKENS,
+ field_type: Spree::CustomField::FIELD_TYPE_TOKENS,
resource_type: :string,
storefront_visible: :boolean,
searchable: :boolean,
diff --git a/spree/api/app/serializers/spree/api/v3/admin/custom_field_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/custom_field_serializer.rb
index dc70e9c270..318211df8b 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/custom_field_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/custom_field_serializer.rb
@@ -11,11 +11,11 @@ module Spree
attributes created_at: :iso8601, updated_at: :iso8601
attribute :storefront_visible do |custom_field|
- custom_field.metafield_definition.available_on_front_end?
+ custom_field.custom_field_definition.storefront_visible
end
attribute :custom_field_definition_id do |custom_field|
- custom_field.metafield_definition.prefixed_id
+ custom_field.custom_field_definition.prefixed_id
end
end
end
diff --git a/spree/api/app/serializers/spree/api/v3/admin/product_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/product_serializer.rb
index f4dfc2ce62..19bbdd0e4f 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/product_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/product_serializer.rb
@@ -80,8 +80,7 @@ module Spree
resource: proc { Spree.api.admin_collection_serializer },
if: proc { expand?('collections') }
- many :metafields,
- key: :custom_fields,
+ many :custom_fields,
resource: proc { Spree.api.admin_custom_field_serializer },
if: proc { expand?('custom_fields') }
diff --git a/spree/api/app/serializers/spree/api/v3/admin/product_type_custom_field_definition_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/product_type_custom_field_definition_serializer.rb
index db4bf5b836..b1d3604e86 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/product_type_custom_field_definition_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/product_type_custom_field_definition_serializer.rb
@@ -12,7 +12,7 @@ module Spree
key: :string,
namespace: :string,
label: :string,
- field_type: Spree::Metafield::FIELD_TYPE_TOKENS,
+ field_type: Spree::CustomField::FIELD_TYPE_TOKENS,
required: :boolean,
sort_order: :number
diff --git a/spree/api/app/serializers/spree/api/v3/admin/variant_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/variant_serializer.rb
index 5342abfac6..2a0428c44b 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/variant_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/variant_serializer.rb
@@ -67,8 +67,7 @@ module Spree
resource: proc { Spree.api.admin_price_serializer },
if: proc { expand?('prices') }
- many :metafields,
- key: :custom_fields,
+ many :custom_fields,
resource: proc { Spree.api.admin_custom_field_serializer },
if: proc { expand?('custom_fields') }
diff --git a/spree/api/app/serializers/spree/api/v3/category_serializer.rb b/spree/api/app/serializers/spree/api/v3/category_serializer.rb
index 188338035d..2be163a511 100644
--- a/spree/api/app/serializers/spree/api/v3/category_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/category_serializer.rb
@@ -60,7 +60,7 @@ module Spree
resource: proc { Spree.api.category_serializer },
if: proc { expand?('ancestors') }
- many :public_metafields,
+ many :storefront_custom_fields,
key: :custom_fields,
resource: proc { Spree.api.custom_field_serializer },
if: proc { expand?('custom_fields') }
diff --git a/spree/api/app/serializers/spree/api/v3/collection_serializer.rb b/spree/api/app/serializers/spree/api/v3/collection_serializer.rb
index 358644ac5d..2311d32911 100644
--- a/spree/api/app/serializers/spree/api/v3/collection_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/collection_serializer.rb
@@ -31,7 +31,7 @@ module Spree
image_url_for(collection.square_image)
end
- many :public_metafields,
+ many :storefront_custom_fields,
key: :custom_fields,
resource: proc { Spree.api.custom_field_serializer },
if: proc { expand?('custom_fields') }
diff --git a/spree/api/app/serializers/spree/api/v3/custom_field_serializer.rb b/spree/api/app/serializers/spree/api/v3/custom_field_serializer.rb
index 187b8f15f2..6f68d84416 100644
--- a/spree/api/app/serializers/spree/api/v3/custom_field_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/custom_field_serializer.rb
@@ -6,8 +6,8 @@ module Spree
class CustomFieldSerializer < BaseSerializer
typelize key: :string,
label: :string,
- type: [:string, deprecated: 'Use `field_type` instead. The legacy `type` field returns the Ruby STI class name (e.g. `Spree::Metafields::ShortText`) and will be removed in a future minor.'],
- field_type: Spree::Metafield::FIELD_TYPE_TOKENS,
+ type: [:string, deprecated: 'Use `field_type` instead. The legacy `type` field returns the Ruby STI class name (e.g. `Spree::CustomFields::ShortText`) and will be removed in a future minor.'],
+ field_type: Spree::CustomField::FIELD_TYPE_TOKENS,
value: :any
attributes :label, :type, :field_type
diff --git a/spree/api/app/serializers/spree/api/v3/product_serializer.rb b/spree/api/app/serializers/spree/api/v3/product_serializer.rb
index 831f1e9dcb..2633f7eb7f 100644
--- a/spree/api/app/serializers/spree/api/v3/product_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/product_serializer.rb
@@ -120,7 +120,7 @@ module Spree
resource: proc { Spree.api.category_serializer },
if: proc { expand?('categories') }
- many :public_metafields,
+ many :storefront_custom_fields,
key: :custom_fields,
resource: proc { Spree.api.custom_field_serializer },
if: proc { expand?('custom_fields') }
diff --git a/spree/api/app/serializers/spree/api/v3/variant_serializer.rb b/spree/api/app/serializers/spree/api/v3/variant_serializer.rb
index 1ca1fce4ad..35ab39830e 100644
--- a/spree/api/app/serializers/spree/api/v3/variant_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/variant_serializer.rb
@@ -91,7 +91,7 @@ module Spree
many :option_values, resource: proc { Spree.api.option_value_serializer }
- many :public_metafields,
+ many :storefront_custom_fields,
key: :custom_fields,
resource: proc { Spree.api.custom_field_serializer },
if: proc { expand?('custom_fields') }
diff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rb
index 527ad103b7..916993a913 100644
--- a/spree/api/config/routes.rb
+++ b/spree/api/config/routes.rb
@@ -122,7 +122,7 @@ Spree::Core::Engine.add_routes do
namespace :admin do
# Mounts a nested `custom_fields` resource on parents that include
- # Spree::Metafields. See docs/plans/5.4-6.0-custom-fields-rename.md.
+ # Spree::HasCustomFields. See docs/plans/5.4-6.0-custom-fields-rename.md.
concern :custom_fieldable do
resources :custom_fields
end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/categories_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/categories_controller_spec.rb
index 5bec89779e..925e5bf597 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/categories_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/categories_controller_spec.rb
@@ -96,21 +96,21 @@ RSpec.describe Spree::Api::V3::Admin::CategoriesController, type: :controller do
# Category custom-field definitions are stored under Spree::Category (the
# category route maps to the Taxon class). The dashboard ships values inline
- # with the category form, persisted via Spree::Metafields#custom_fields=.
+ # with the category form, persisted via Spree::HasCustomFields#custom_fields=.
context 'with inline custom fields' do
let!(:fabric_definition) do
- create(:metafield_definition,
+ create(:custom_field_definition,
resource_type: 'Spree::Category',
namespace: 'category',
key: 'fabric',
- metafield_type: 'Spree::Metafields::ShortText')
+ field_type: 'Spree::CustomFields::ShortText')
end
let!(:specs_definition) do
- create(:metafield_definition,
+ create(:custom_field_definition,
resource_type: 'Spree::Category',
namespace: 'category',
key: 'specs',
- metafield_type: 'Spree::Metafields::Json')
+ field_type: 'Spree::CustomFields::Json')
end
it 'round-trips an array-shaped JSON custom field value' do
@@ -122,7 +122,7 @@ RSpec.describe Spree::Api::V3::Admin::CategoriesController, type: :controller do
}, as: :json
expect(response).to have_http_status(:ok)
- stored = category.reload.metafields.find_by(metafield_definition: specs_definition)
+ stored = category.reload.custom_fields.find_by(custom_field_definition: specs_definition)
expect(stored.serialize_value).to eq(%w[a b c])
end
@@ -135,7 +135,7 @@ RSpec.describe Spree::Api::V3::Admin::CategoriesController, type: :controller do
}, as: :json
expect(response).to have_http_status(:ok)
- stored = category.reload.metafields.find_by(metafield_definition: specs_definition)
+ stored = category.reload.custom_fields.find_by(custom_field_definition: specs_definition)
expect(stored.serialize_value).to eq('color' => 'red')
end
@@ -147,19 +147,19 @@ RSpec.describe Spree::Api::V3::Admin::CategoriesController, type: :controller do
{ custom_field_definition_id: fabric_definition.prefixed_id, value: 'Linen' }
]
}, as: :json
- }.to change(Spree::Metafield, :count).by(1)
+ }.to change(Spree::CustomField, :count).by(1)
expect(response).to have_http_status(:ok)
- expect(category.reload.metafields.find_by(metafield_definition: fabric_definition).value).to eq('Linen')
+ expect(category.reload.custom_fields.find_by(custom_field_definition: fabric_definition).value).to eq('Linen')
end
it 'leaves existing values untouched when custom_fields is omitted' do
- category.metafields.create!(metafield_definition: fabric_definition, value: 'Wool')
+ category.custom_fields.create!(custom_field_definition: fabric_definition, value: 'Wool')
patch :update, params: { id: category.prefixed_id, name: 'Apparel' }, as: :json
expect(response).to have_http_status(:ok)
- expect(category.reload.metafields.find_by(metafield_definition: fabric_definition).value).to eq('Wool')
+ expect(category.reload.custom_fields.find_by(custom_field_definition: fabric_definition).value).to eq('Wool')
end
end
end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/custom_field_definitions_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/custom_field_definitions_controller_spec.rb
index 55f4010f19..6ebfcb488a 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/custom_field_definitions_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/custom_field_definitions_controller_spec.rb
@@ -6,9 +6,9 @@ RSpec.describe Spree::Api::V3::Admin::CustomFieldDefinitionsController, type: :c
include_context 'API v3 Admin authenticated'
let!(:product_definition) do
- create(:metafield_definition, :short_text_field, namespace: 'specs', key: 'fabric')
+ create(:custom_field_definition, :short_text_field, namespace: 'specs', key: 'fabric')
end
- let!(:order_definition) { create(:metafield_definition, :for_order) }
+ let!(:order_definition) { create(:custom_field_definition, :for_order) }
before { request.headers.merge!(headers) }
@@ -83,14 +83,14 @@ RSpec.describe Spree::Api::V3::Admin::CustomFieldDefinitionsController, type: :c
end
context 'with storefront_visible: false' do
- it 'maps to display_on: back_end internally' do
+ it 'persists storefront_visible as false' do
post :create, params: create_params.merge(storefront_visible: false), as: :json
expect(response).to have_http_status(:created)
expect(json_response['storefront_visible']).to eq(false)
defn = Spree::CustomFieldDefinition.find_by_prefix_id(json_response['id'])
- expect(defn.display_on).to eq('back_end')
+ expect(defn.storefront_visible).to be(false)
end
end
@@ -104,7 +104,7 @@ RSpec.describe Spree::Api::V3::Admin::CustomFieldDefinitionsController, type: :c
context 'when field_type is not a registered type' do
it 'returns 422' do
- post :create, params: create_params.merge(field_type: 'Spree::Metafields::FakeKind'), as: :json
+ post :create, params: create_params.merge(field_type: 'Spree::CustomFields::FakeKind'), as: :json
expect(response).to have_http_status(:unprocessable_content)
end
@@ -127,11 +127,11 @@ RSpec.describe Spree::Api::V3::Admin::CustomFieldDefinitionsController, type: :c
end
end
- it 'silently drops `metafield_type` (no longer a permitted API param)' do
- # 5.4 leaks no `metafield_type` API key; sending one is ignored. The
- # `field_type` API param is the only way to set the column.
+ it 'silently drops the legacy `metafield_type` param' do
+ # `metafield_type` was never an API key and is not permitted; sending one
+ # is ignored, leaving the default type in place.
post :create,
- params: create_params.merge(metafield_type: 'Spree::Metafields::Number'),
+ params: create_params.merge(metafield_type: 'Spree::CustomFields::Number'),
as: :json
expect(response).to have_http_status(:created)
@@ -139,11 +139,11 @@ RSpec.describe Spree::Api::V3::Admin::CustomFieldDefinitionsController, type: :c
end
it 'accepts the legacy class-name form on `field_type` writes' do
- # Back-compat: external integrations that wrote `Spree::Metafields::*`
+ # Back-compat: external integrations that wrote `Spree::CustomFields::*`
# under the old API contract keep working. Writes are translated; reads
# always emit the token form.
post :create,
- params: create_params.merge(field_type: 'Spree::Metafields::Number', key: 'priority'),
+ params: create_params.merge(field_type: 'Spree::CustomFields::Number', key: 'priority'),
as: :json
expect(response).to have_http_status(:created)
@@ -164,14 +164,14 @@ RSpec.describe Spree::Api::V3::Admin::CustomFieldDefinitionsController, type: :c
expect(response).to have_http_status(:ok)
expect(json_response['label']).to eq('Fabric Composition')
expect(json_response['storefront_visible']).to eq(false)
- expect(product_definition.reload.display_on).to eq('back_end')
+ expect(product_definition.reload.storefront_visible).to be(false)
end
end
describe 'DELETE #destroy' do
it 'destroys the definition and cascades to its custom fields' do
product = create(:product)
- create(:metafield, resource: product, metafield_definition: product_definition, value: 'wool')
+ create(:custom_field, resource: product, custom_field_definition: product_definition, value: 'wool')
delete :destroy, params: { id: product_definition.prefixed_id }, as: :json
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/custom_fields_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/custom_fields_controller_spec.rb
index b290b8b6e7..d80b312798 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/custom_fields_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/custom_fields_controller_spec.rb
@@ -6,14 +6,14 @@ RSpec.describe Spree::Api::V3::Admin::CustomFieldsController, type: :controller
include_context 'API v3 Admin authenticated'
let(:product) { create(:product) }
- let(:short_text_definition) { create(:metafield_definition, :short_text_field) }
- let(:long_text_definition) { create(:metafield_definition, :long_text_field) }
+ let(:short_text_definition) { create(:custom_field_definition, :short_text_field) }
+ let(:long_text_definition) { create(:custom_field_definition, :long_text_field) }
before { request.headers.merge!(headers) }
describe 'GET #index' do
let!(:custom_field) do
- create(:metafield, resource: product, metafield_definition: short_text_definition, value: 'wool')
+ create(:custom_field, resource: product, custom_field_definition: short_text_definition, value: 'wool')
end
it 'returns the parent custom fields' do
@@ -33,8 +33,8 @@ RSpec.describe Spree::Api::V3::Admin::CustomFieldsController, type: :controller
it 'scopes the collection to the parent — sibling products are not returned' do
other_product = create(:product)
- create(:metafield, resource: other_product, metafield_definition: long_text_definition,
- type: 'Spree::Metafields::LongText', value: 'unrelated')
+ create(:custom_field, resource: other_product, custom_field_definition: long_text_definition,
+ type: 'Spree::CustomFields::LongText', value: 'unrelated')
get :index, params: { product_id: product.prefixed_id }, as: :json
@@ -55,7 +55,7 @@ RSpec.describe Spree::Api::V3::Admin::CustomFieldsController, type: :controller
it 'creates a custom field on the parent' do
expect { post :create, params: create_params, as: :json }.
- to change { product.metafields.count }.by(1)
+ to change { product.custom_fields.count }.by(1)
expect(response).to have_http_status(:created)
expect(json_response['value']).to eq('wool')
@@ -80,7 +80,7 @@ RSpec.describe Spree::Api::V3::Admin::CustomFieldsController, type: :controller
context 'when a custom field for the same definition already exists' do
before do
- create(:metafield, resource: product, metafield_definition: short_text_definition, value: 'cotton')
+ create(:custom_field, resource: product, custom_field_definition: short_text_definition, value: 'cotton')
end
it 'returns 422 (uniqueness on definition + resource)' do
@@ -101,7 +101,7 @@ RSpec.describe Spree::Api::V3::Admin::CustomFieldsController, type: :controller
describe 'PATCH #update' do
let!(:custom_field) do
- create(:metafield, resource: product, metafield_definition: short_text_definition, value: 'wool')
+ create(:custom_field, resource: product, custom_field_definition: short_text_definition, value: 'wool')
end
it "updates the custom field's value" do
@@ -125,13 +125,13 @@ RSpec.describe Spree::Api::V3::Admin::CustomFieldsController, type: :controller
as: :json
expect(response).to have_http_status(:ok)
- expect(custom_field.reload.metafield_definition_id).to eq(short_text_definition.id)
+ expect(custom_field.reload.custom_field_definition_id).to eq(short_text_definition.id)
end
it 'returns 404 when the custom field does not belong to the parent' do
sibling = create(:product)
- foreign = create(:metafield, resource: sibling, metafield_definition: long_text_definition,
- type: 'Spree::Metafields::LongText', value: 'foreign')
+ foreign = create(:custom_field, resource: sibling, custom_field_definition: long_text_definition,
+ type: 'Spree::CustomFields::LongText', value: 'foreign')
patch :update,
params: { product_id: product.prefixed_id, id: foreign.prefixed_id, value: 'x' },
@@ -143,7 +143,7 @@ RSpec.describe Spree::Api::V3::Admin::CustomFieldsController, type: :controller
describe 'DELETE #destroy' do
let!(:custom_field) do
- create(:metafield, resource: product, metafield_definition: short_text_definition, value: 'wool')
+ create(:custom_field, resource: product, custom_field_definition: short_text_definition, value: 'wool')
end
it 'destroys the custom field' do
@@ -155,8 +155,8 @@ RSpec.describe Spree::Api::V3::Admin::CustomFieldsController, type: :controller
it 'does not destroy a custom field that belongs to a sibling parent' do
sibling = create(:product)
- foreign = create(:metafield, resource: sibling, metafield_definition: long_text_definition,
- type: 'Spree::Metafields::LongText', value: 'foreign')
+ foreign = create(:custom_field, resource: sibling, custom_field_definition: long_text_definition,
+ type: 'Spree::CustomFields::LongText', value: 'foreign')
delete :destroy, params: { product_id: product.prefixed_id, id: foreign.prefixed_id }, as: :json
@@ -169,7 +169,7 @@ RSpec.describe Spree::Api::V3::Admin::CustomFieldsController, type: :controller
let(:other_store) { create(:store) }
let(:other_product) { create(:product, store: other_store) }
let!(:foreign_field) do
- create(:metafield, resource: other_product, metafield_definition: short_text_definition, value: 'secret')
+ create(:custom_field, resource: other_product, custom_field_definition: short_text_definition, value: 'secret')
end
it 'does not list custom fields of another store\'s product' do
@@ -187,7 +187,7 @@ RSpec.describe Spree::Api::V3::Admin::CustomFieldsController, type: :controller
value: 'injected'
},
as: :json
- }.not_to change { other_product.metafields.count }
+ }.not_to change { other_product.custom_fields.count }
expect(response).to have_http_status(:not_found)
end
@@ -227,7 +227,7 @@ RSpec.describe Spree::Api::V3::Admin::CustomFieldsController, type: :controller
let(:granted_scope) { 'read_products' }
it 'allows reading' do
- create(:metafield, resource: product, metafield_definition: short_text_definition, value: 'wool')
+ create(:custom_field, resource: product, custom_field_definition: short_text_definition, value: 'wool')
get :index, params: { product_id: product.prefixed_id }, as: :json
@@ -271,7 +271,7 @@ RSpec.describe Spree::Api::V3::Admin::CustomFieldsController, type: :controller
let(:granted_scope) { 'write_products' }
let(:variant) { create(:variant) }
let(:variant_definition) do
- create(:metafield_definition, :short_text_field, resource_type: 'Spree::Variant')
+ create(:custom_field_definition, :short_text_field, resource_type: 'Spree::Variant')
end
it 'allows creating a variant custom field with write_products' do
@@ -294,7 +294,7 @@ RSpec.describe Spree::Api::V3::Admin::CustomFieldsController, type: :controller
let(:granted_scope) { 'write_categories' }
let(:category) { create(:category) }
let(:category_definition) do
- create(:metafield_definition, :short_text_field, resource_type: 'Spree::Category')
+ create(:custom_field_definition, :short_text_field, resource_type: 'Spree::Category')
end
it 'resolves the parent and gates by the categories scope' do
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/custom_fields_polymorphic_parent_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/custom_fields_polymorphic_parent_spec.rb
index 7f45909a4d..d4f1456abd 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/custom_fields_polymorphic_parent_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/custom_fields_polymorphic_parent_spec.rb
@@ -12,10 +12,10 @@ RSpec.describe Spree::Api::V3::Admin::CustomFieldsController, type: :controller
shared_examples 'parent-from-route inference' do |parent_factory:, definition_trait:, param_key:|
let!(:parent) { create(parent_factory) }
- let!(:definition) { create(:metafield_definition, definition_trait) }
+ let!(:definition) { create(:custom_field_definition, definition_trait) }
let!(:custom_field) do
- create(:metafield, resource: parent, metafield_definition: definition,
- type: definition.metafield_type,
+ create(:custom_field, resource: parent, custom_field_definition: definition,
+ type: definition.field_type_class_name,
value: 'value-for-parent')
end
@@ -55,18 +55,18 @@ RSpec.describe Spree::Api::V3::Admin::CustomFieldsController, type: :controller
# route must still resolve in that case.
describe 'when enabled_resources does not contain Spree.customer_class' do
let!(:parent) { create(:user) }
- let!(:definition) { create(:metafield_definition, :for_user) }
+ let!(:definition) { create(:custom_field_definition, :for_user) }
let!(:custom_field) do
- create(:metafield, resource: parent, metafield_definition: definition,
- type: definition.metafield_type, value: 'value-for-parent')
+ create(:custom_field, resource: parent, custom_field_definition: definition,
+ type: definition.field_type_class_name, value: 'value-for-parent')
end
before do
- @original_resources = Rails.application.config.spree.metafields.enabled_resources
- Rails.application.config.spree.metafields.enabled_resources = @original_resources - [Spree.customer_class]
+ @original_resources = Rails.application.config.spree.custom_fields.enabled_resources
+ Rails.application.config.spree.custom_fields.enabled_resources = @original_resources - [Spree.customer_class]
end
- after { Rails.application.config.spree.metafields.enabled_resources = @original_resources }
+ after { Rails.application.config.spree.custom_fields.enabled_resources = @original_resources }
it 'returns the customer\'s custom fields' do
get :index, params: { customer_id: parent.prefixed_id }, as: :json
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/payment_methods_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/payment_methods_controller_spec.rb
index 362c9a3a68..ff9745382d 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/payment_methods_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/payment_methods_controller_spec.rb
@@ -31,10 +31,10 @@ RSpec.describe Spree::Api::V3::Admin::PaymentMethodsController, type: :controlle
context 'when filtering by storefront_visible' do
let!(:storefront_visible_method) do
- create(:check_payment_method, store: store, display_on: 'both')
+ create(:check_payment_method, store: store)
end
let!(:admin_only_method) do
- create(:check_payment_method, store: store, display_on: 'back_end')
+ create(:check_payment_method, store: store, storefront_visible: false)
end
it 'returns only storefront-visible methods when q[storefront_visible_eq]=true' do
@@ -196,7 +196,7 @@ RSpec.describe Spree::Api::V3::Admin::PaymentMethodsController, type: :controlle
describe 'storefront_visible' do
context 'GET #show' do
it 'returns storefront_visible: false when display_on is back_end' do
- payment_method.update!(display_on: 'back_end')
+ payment_method.update!(storefront_visible: false)
get :show, params: { id: payment_method.prefixed_id }, as: :json
@@ -224,7 +224,7 @@ RSpec.describe Spree::Api::V3::Admin::PaymentMethodsController, type: :controlle
end
it 'maps storefront_visible: true to display_on: both' do
- payment_method.update!(display_on: 'back_end')
+ payment_method.update!(storefront_visible: false)
patch :update,
params: { id: payment_method.prefixed_id, storefront_visible: true },
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/products_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/products_controller_spec.rb
index b90b7919a3..ebb6388448 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/products_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/products_controller_spec.rb
@@ -37,20 +37,20 @@ RSpec.describe Spree::Api::V3::Admin::ProductsController, type: :controller do
context 'with custom field filtering and sorting' do
let!(:material) do
- create(:metafield_definition, :short_text_field, :searchable,
+ create(:custom_field_definition, :short_text_field, :searchable,
namespace: 'custom', key: 'material')
end
let!(:weight) do
- create(:metafield_definition, :number_field, :sortable,
+ create(:custom_field_definition, :number_field, :sortable,
namespace: 'custom', key: 'weight')
end
let!(:other_product) { create(:product, name: 'Unique Widget') }
before do
- product.set_metafield(material, 'wool')
- product.set_metafield(weight, '10')
- other_product.set_metafield(material, 'cotton')
- other_product.set_metafield(weight, '2')
+ product.set_custom_field(material, 'wool')
+ product.set_custom_field(weight, '10')
+ other_product.set_custom_field(material, 'cotton')
+ other_product.set_custom_field(weight, '2')
end
it 'filters by a cf_* text predicate' do
@@ -461,18 +461,18 @@ RSpec.describe Spree::Api::V3::Admin::ProductsController, type: :controller do
context 'with inline custom fields' do
let!(:material_definition) do
- create(:metafield_definition,
+ create(:custom_field_definition,
resource_type: 'Spree::Product',
namespace: 'product',
key: 'material',
- metafield_type: 'Spree::Metafields::ShortText')
+ field_type: 'Spree::CustomFields::ShortText')
end
let!(:waterproof_definition) do
- create(:metafield_definition,
+ create(:custom_field_definition,
resource_type: 'Spree::Product',
namespace: 'product',
key: 'waterproof',
- metafield_type: 'Spree::Metafields::Boolean')
+ field_type: 'Spree::CustomFields::Boolean')
end
it 'persists custom_fields inline on create' do
@@ -485,15 +485,15 @@ RSpec.describe Spree::Api::V3::Admin::ProductsController, type: :controller do
]
}, as: :json
}.to change(Spree::Product, :count).by(1)
- .and change(Spree::Metafield, :count).by(2)
+ .and change(Spree::CustomField, :count).by(2)
expect(response).to have_http_status(:created)
created = Spree::Product.find_by(name: 'Custom Fields Product')
- material = created.metafields.find_by(metafield_definition: material_definition)
- waterproof = created.metafields.find_by(metafield_definition: waterproof_definition)
+ material = created.custom_fields.find_by(custom_field_definition: material_definition)
+ waterproof = created.custom_fields.find_by(custom_field_definition: waterproof_definition)
expect(material.value).to eq('Cotton')
- # Boolean metafields store the value as a serialized string ("f"/"t"
+ # Boolean custom_fields store the value as a serialized string ("f"/"t"
# on SQLite). The dashboard reads them back via the API which casts.
expect(waterproof.value).to be_in(['false', 'f', false])
end
@@ -508,12 +508,12 @@ RSpec.describe Spree::Api::V3::Admin::ProductsController, type: :controller do
]
}, as: :json
}.to change(Spree::Product, :count).by(1)
- .and change(Spree::Metafield, :count).by(1)
+ .and change(Spree::CustomField, :count).by(1)
expect(response).to have_http_status(:created)
created = Spree::Product.find_by(name: 'Half-Filled Custom Fields')
- expect(created.metafields.find_by(metafield_definition: material_definition).value).to eq('Cotton')
- expect(created.metafields.find_by(metafield_definition: waterproof_definition)).to be_nil
+ expect(created.custom_fields.find_by(custom_field_definition: material_definition).value).to eq('Cotton')
+ expect(created.custom_fields.find_by(custom_field_definition: waterproof_definition)).to be_nil
end
it 'skips entries with a missing custom_field_definition_id' do
@@ -526,20 +526,20 @@ RSpec.describe Spree::Api::V3::Admin::ProductsController, type: :controller do
]
}, as: :json
}.to change(Spree::Product, :count).by(1)
- .and change(Spree::Metafield, :count).by(1)
+ .and change(Spree::CustomField, :count).by(1)
expect(response).to have_http_status(:created)
created = Spree::Product.find_by(name: 'Custom Fields No Def')
- expect(created.metafields.find_by(metafield_definition: material_definition).value).to eq('Silk')
+ expect(created.custom_fields.find_by(custom_field_definition: material_definition).value).to eq('Silk')
end
it 'persists a Hash value for a JSON-typed custom field' do
json_definition = create(
- :metafield_definition,
+ :custom_field_definition,
resource_type: 'Spree::Product',
namespace: 'product',
key: 'spec',
- metafield_type: 'Spree::Metafields::Json'
+ field_type: 'Spree::CustomFields::Json'
)
post :create, params: {
@@ -551,9 +551,9 @@ RSpec.describe Spree::Api::V3::Admin::ProductsController, type: :controller do
expect(response).to have_http_status(:created)
created = Spree::Product.find_by(name: 'JSON Custom Field Product')
- mf = created.metafields.find_by(metafield_definition: json_definition)
+ mf = created.custom_fields.find_by(custom_field_definition: json_definition)
expect(mf).to be_present
- # Json metafields store the hash as serialized JSON. We only care
+ # Json custom_fields store the hash as serialized JSON. We only care
# that the content survived strong-params (would be nil if dropped)
# — the precise on-disk representation depends on the type.
parsed = mf.value.is_a?(Hash) ? mf.value : JSON.parse(mf.value.to_s)
@@ -1052,25 +1052,25 @@ RSpec.describe Spree::Api::V3::Admin::ProductsController, type: :controller do
context 'with inline custom fields' do
let!(:material_definition) do
- create(:metafield_definition,
+ create(:custom_field_definition,
resource_type: 'Spree::Product',
namespace: 'product',
key: 'material',
- metafield_type: 'Spree::Metafields::ShortText')
+ field_type: 'Spree::CustomFields::ShortText')
end
let!(:fit_definition) do
- create(:metafield_definition,
+ create(:custom_field_definition,
resource_type: 'Spree::Product',
namespace: 'product',
key: 'fit',
- metafield_type: 'Spree::Metafields::ShortText')
+ field_type: 'Spree::CustomFields::ShortText')
end
let!(:waterproof_definition) do
- create(:metafield_definition,
+ create(:custom_field_definition,
resource_type: 'Spree::Product',
namespace: 'product',
key: 'waterproof',
- metafield_type: 'Spree::Metafields::Boolean')
+ field_type: 'Spree::CustomFields::Boolean')
end
it 'creates new custom field values on PATCH' do
@@ -1081,16 +1081,16 @@ RSpec.describe Spree::Api::V3::Admin::ProductsController, type: :controller do
{ custom_field_definition_id: material_definition.prefixed_id, value: 'Wool' }
]
}, as: :json
- }.to change(Spree::Metafield, :count).by(1)
+ }.to change(Spree::CustomField, :count).by(1)
expect(response).to have_http_status(:ok)
- metafield = product.metafields.find_by(metafield_definition: material_definition)
- expect(metafield.value).to eq('Wool')
+ custom_field = product.custom_fields.find_by(custom_field_definition: material_definition)
+ expect(custom_field.value).to eq('Wool')
end
it 'upserts an existing custom field value by definition id' do
- existing = product.metafields.create!(
- metafield_definition: material_definition,
+ existing = product.custom_fields.create!(
+ custom_field_definition: material_definition,
value: 'Cotton'
)
@@ -1103,12 +1103,12 @@ RSpec.describe Spree::Api::V3::Admin::ProductsController, type: :controller do
expect(response).to have_http_status(:ok)
expect(existing.reload.value).to eq('Polyester')
- expect(product.metafields.where(metafield_definition: material_definition).count).to eq(1)
+ expect(product.custom_fields.where(custom_field_definition: material_definition).count).to eq(1)
end
it 'leaves unrelated custom fields untouched on partial PATCH' do
- product.metafields.create!(metafield_definition: material_definition, value: 'Cotton')
- product.metafields.create!(metafield_definition: fit_definition, value: 'Regular')
+ product.custom_fields.create!(custom_field_definition: material_definition, value: 'Cotton')
+ product.custom_fields.create!(custom_field_definition: fit_definition, value: 'Regular')
patch :update, params: {
id: product.prefixed_id,
@@ -1118,14 +1118,14 @@ RSpec.describe Spree::Api::V3::Admin::ProductsController, type: :controller do
}, as: :json
expect(response).to have_http_status(:ok)
- expect(product.metafields.count).to eq(2)
- expect(product.metafields.find_by(metafield_definition: material_definition).value).to eq('Cotton')
- expect(product.metafields.find_by(metafield_definition: fit_definition).value).to eq('Slim')
+ expect(product.custom_fields.count).to eq(2)
+ expect(product.custom_fields.find_by(custom_field_definition: material_definition).value).to eq('Cotton')
+ expect(product.custom_fields.find_by(custom_field_definition: fit_definition).value).to eq('Slim')
end
it 'destroys an existing custom field when value is blank on PATCH' do
- existing = product.metafields.create!(
- metafield_definition: material_definition,
+ existing = product.custom_fields.create!(
+ custom_field_definition: material_definition,
value: 'Cotton'
)
@@ -1136,15 +1136,15 @@ RSpec.describe Spree::Api::V3::Admin::ProductsController, type: :controller do
{ custom_field_definition_id: material_definition.prefixed_id, value: '' }
]
}, as: :json
- }.to change(Spree::Metafield, :count).by(-1)
+ }.to change(Spree::CustomField, :count).by(-1)
expect(response).to have_http_status(:ok)
- expect(Spree::Metafield.find_by(id: existing.id)).to be_nil
+ expect(Spree::CustomField.find_by(id: existing.id)).to be_nil
end
it 'persists a Boolean false value instead of treating it as blank' do
- existing = product.metafields.create!(
- metafield_definition: waterproof_definition,
+ existing = product.custom_fields.create!(
+ custom_field_definition: waterproof_definition,
value: true
)
@@ -1155,10 +1155,10 @@ RSpec.describe Spree::Api::V3::Admin::ProductsController, type: :controller do
{ custom_field_definition_id: waterproof_definition.prefixed_id, value: false }
]
}, as: :json
- }.not_to change(Spree::Metafield, :count)
+ }.not_to change(Spree::CustomField, :count)
expect(response).to have_http_status(:ok)
- # Boolean metafields store as a stringified value; the entry should
+ # Boolean custom_fields store as a stringified value; the entry should
# still exist with the new false value.
expect(existing.reload.value).to be_in(['false', 'f', false])
end
@@ -1172,10 +1172,10 @@ RSpec.describe Spree::Api::V3::Admin::ProductsController, type: :controller do
{ custom_field_definition_id: material_definition.prefixed_id, value: 'Linen' }
]
}, as: :json
- }.to change(Spree::Metafield, :count).by(1)
+ }.to change(Spree::CustomField, :count).by(1)
expect(response).to have_http_status(:ok)
- expect(product.metafields.find_by(metafield_definition: material_definition).value).to eq('Linen')
+ expect(product.custom_fields.find_by(custom_field_definition: material_definition).value).to eq('Linen')
end
it 'accepts a raw (non-prefixed) custom_field_definition_id' do
@@ -1187,7 +1187,7 @@ RSpec.describe Spree::Api::V3::Admin::ProductsController, type: :controller do
}, as: :json
expect(response).to have_http_status(:ok)
- expect(product.metafields.find_by(metafield_definition: material_definition).value).to eq('Velvet')
+ expect(product.custom_fields.find_by(custom_field_definition: material_definition).value).to eq('Velvet')
end
end
diff --git a/spree/api/spec/controllers/spree/api/v3/store/products/filters_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/products/filters_controller_spec.rb
index 1edf4be67d..19940670a3 100644
--- a/spree/api/spec/controllers/spree/api/v3/store/products/filters_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/store/products/filters_controller_spec.rb
@@ -100,12 +100,12 @@ RSpec.describe Spree::Api::V3::Store::Products::FiltersController, type: :contro
)
end
- it 'invalidates cached sort options when a metafield definition becomes sortable' do
+ it 'invalidates cached sort options when a custom_field definition becomes sortable' do
get :index
expect(json_response['sort_options'].map { |s| s['id'] }).not_to include('cf_custom_weight')
- create(:metafield_definition, :number_field, :sortable,
- namespace: 'custom', key: 'weight', name: 'Weight')
+ create(:custom_field_definition, :number_field, :sortable,
+ namespace: 'custom', key: 'weight', label: 'Weight')
get :index
expect(json_response['sort_options'].map { |s| s['id'] }).to include(
diff --git a/spree/api/spec/controllers/spree/api/v3/store/products/meilisearch_integration_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/products/meilisearch_integration_spec.rb
index a782c50e6a..6dcd3a43d1 100644
--- a/spree/api/spec/controllers/spree/api/v3/store/products/meilisearch_integration_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/store/products/meilisearch_integration_spec.rb
@@ -248,40 +248,40 @@ RSpec.describe 'Meilisearch Integration', type: :controller, if: ENV['MEILISEARC
end
end
- describe 'searchable / sortable metafields' do
+ describe 'searchable / sortable custom_fields' do
let!(:label_definition) do
- create(:metafield_definition, :short_text_field, :searchable, :sortable,
+ create(:custom_field_definition, :short_text_field, :searchable, :sortable,
namespace: 'custom', key: 'label')
end
let!(:weight_definition) do
- create(:metafield_definition, :number_field, :sortable,
+ create(:custom_field_definition, :number_field, :sortable,
namespace: 'custom', key: 'weight')
end
- # Product with neither metafield — exercises missing-attribute sort placement.
- let!(:missing_metafield_product) do
+ # Product with neither custom_field — exercises missing-attribute sort placement.
+ let!(:missing_custom_field_product) do
create(:product, name: 'Green Linen Shirt', status: 'active', store: store, categories: [clothing_category])
end
before do
- cheap_red_shirt.set_metafield(label_definition, 'Apple')
- expensive_blue_shirt.set_metafield(label_definition, 'Cherry')
- # blue_shoes left without label metafield
+ cheap_red_shirt.set_custom_field(label_definition, 'Apple')
+ expensive_blue_shirt.set_custom_field(label_definition, 'Cherry')
+ # blue_shoes left without label custom_field
- cheap_red_shirt.set_metafield(weight_definition, '10')
- expensive_blue_shirt.set_metafield(weight_definition, '2')
- blue_shoes.set_metafield(weight_definition, '3')
+ cheap_red_shirt.set_custom_field(weight_definition, '10')
+ expensive_blue_shirt.set_custom_field(weight_definition, '2')
+ blue_shoes.set_custom_field(weight_definition, '3')
provider.reindex(store.products)
wait_for_meilisearch_indexing!
end
- it 'includes metafield keys in searchable and sortable settings' do
+ it 'includes custom_field keys in searchable and sortable settings' do
settings = ::Meilisearch::Client.new(ENV['MEILISEARCH_URL']).index(index_name).get_settings
expect(settings['searchableAttributes']).to include('cf_custom_label')
expect(settings['sortableAttributes']).to include('cf_custom_label', 'cf_custom_weight')
end
- it 'finds products by searchable metafield value' do
+ it 'finds products by searchable custom_field value' do
get :index, params: { q: { search: 'Apple' } }
expect(response).to have_http_status(:ok)
@@ -290,7 +290,7 @@ RSpec.describe 'Meilisearch Integration', type: :controller, if: ENV['MEILISEARC
expect(names).not_to include('Blue Silk Shirt')
end
- it 'sorts by short_text metafield ascending and descending with missing values last' do
+ it 'sorts by short_text custom_field ascending and descending with missing values last' do
get :index, params: { sort: 'cf_custom_label' }
expect(response).to have_http_status(:ok)
asc_names = json_response['data'].map { |p| p['name'] }
@@ -304,7 +304,7 @@ RSpec.describe 'Meilisearch Integration', type: :controller, if: ENV['MEILISEARC
expect(desc_names.last(2)).to match_array(['Green Linen Shirt', 'Blue Running Shoes'])
end
- it 'sorts by number metafield numerically' do
+ it 'sorts by number custom_field numerically' do
get :index, params: { sort: 'cf_custom_weight' }
expect(response).to have_http_status(:ok)
expect(json_response['data'].map { |p| p['name'] }.first(3)).to eq(
@@ -319,16 +319,16 @@ RSpec.describe 'Meilisearch Integration', type: :controller, if: ENV['MEILISEARC
end
end
- describe 'sorting by a newly sortable metafield' do
+ describe 'sorting by a newly sortable custom_field' do
it 'self-heals when the sort attribute is not yet configured on the index' do
- definition = create(:metafield_definition, :short_text_field, :sortable,
+ definition = create(:custom_field_definition, :short_text_field, :sortable,
namespace: 'custom', key: 'label')
- cheap_red_shirt.set_metafield(definition, 'aaa')
- expensive_blue_shirt.set_metafield(definition, 'zzz')
+ cheap_red_shirt.set_custom_field(definition, 'aaa')
+ expensive_blue_shirt.set_custom_field(definition, 'zzz')
provider.reindex(store.products)
wait_for_meilisearch_indexing!
- # Strip the metafield from sortable attributes so the next sort request
+ # Strip the custom_field from sortable attributes so the next sort request
# hits invalid_search_sort and must refresh settings + retry.
client = ::Meilisearch::Client.new(ENV['MEILISEARCH_URL'])
client.index(index_name).update_sortable_attributes(%w[name price created_at available_on units_sold_count]).await
diff --git a/spree/api/spec/controllers/spree/api/v3/store/products_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/products_controller_spec.rb
index 35bad0faea..9e706e59a5 100644
--- a/spree/api/spec/controllers/spree/api/v3/store/products_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/store/products_controller_spec.rb
@@ -57,13 +57,13 @@ RSpec.describe Spree::Api::V3::Store::ProductsController, type: :controller do
# predicates as the Admin API — both route through the search provider.
context 'with custom field filtering and sorting' do
let!(:definition) do
- create(:metafield_definition, :short_text_field, :searchable, :sortable,
+ create(:custom_field_definition, :short_text_field, :searchable, :sortable,
namespace: 'custom', key: 'warranty')
end
before do
- product.set_metafield(definition, '2 Years')
- product2.set_metafield(definition, '90 Days')
+ product.set_custom_field(definition, '2 Years')
+ product2.set_custom_field(definition, '90 Days')
end
it 'filters by a cf_* predicate' do
diff --git a/spree/api/spec/integration/spree/api/v3/admin/custom_field_definitions_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/custom_field_definitions_spec.rb
index 83fea501e6..637191430d 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/custom_field_definitions_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/custom_field_definitions_spec.rb
@@ -6,10 +6,10 @@ RSpec.describe 'Admin Custom Field Definitions API', type: :request, swagger_doc
include_context 'API v3 Admin'
let!(:product_definition) do
- create(:metafield_definition, :short_text_field, namespace: 'specs', key: 'fabric')
+ create(:custom_field_definition, :short_text_field, namespace: 'specs', key: 'fabric')
end
let!(:order_definition) do
- create(:metafield_definition, :for_order)
+ create(:custom_field_definition, :for_order)
end
let(:Authorization) { "Bearer #{admin_jwt_token}" }
@@ -75,7 +75,7 @@ RSpec.describe 'Admin Custom Field Definitions API', type: :request, swagger_doc
},
storefront_visible: {
type: :boolean,
- description: 'When false, definition is admin-only (was `display_on: back_end`)'
+ description: 'When false, the definition is admin-only and never exposed in the Store API'
},
searchable: {
type: :boolean,
diff --git a/spree/api/spec/integration/spree/api/v3/admin/products/custom_fields_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/products/custom_fields_spec.rb
index e6d62eaeeb..3b36bb3483 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/products/custom_fields_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/products/custom_fields_spec.rb
@@ -6,9 +6,9 @@ RSpec.describe 'Admin Product Custom Fields API', type: :request, swagger_doc: '
include_context 'API v3 Admin'
let!(:product) { create(:product) }
- let!(:definition) { create(:metafield_definition, :short_text_field) }
+ let!(:definition) { create(:custom_field_definition, :short_text_field) }
let!(:custom_field) do
- create(:metafield, resource: product, metafield_definition: definition, value: 'wool')
+ create(:custom_field, resource: product, custom_field_definition: definition, value: 'wool')
end
let(:Authorization) { "Bearer #{admin_jwt_token}" }
@@ -69,7 +69,7 @@ RSpec.describe 'Admin Product Custom Fields API', type: :request, swagger_doc: '
response '201', 'custom field created' do
let(:'x-spree-api-key') { secret_api_key.plaintext_token }
- let(:other_definition) { create(:metafield_definition, :long_text_field) }
+ let(:other_definition) { create(:custom_field_definition, :long_text_field) }
let(:body) do
{
custom_field_definition_id: other_definition.prefixed_id,
diff --git a/spree/api/spec/serializers/spree/api/v3/admin/product_serializer_spec.rb b/spree/api/spec/serializers/spree/api/v3/admin/product_serializer_spec.rb
index 0199556f59..b34c48906d 100644
--- a/spree/api/spec/serializers/spree/api/v3/admin/product_serializer_spec.rb
+++ b/spree/api/spec/serializers/spree/api/v3/admin/product_serializer_spec.rb
@@ -13,10 +13,10 @@ RSpec.describe Spree::Api::V3::Admin::ProductSerializer do
end
it 'includes all custom fields with storefront_visible when expanded' do
- public_def = create(:metafield_definition, resource_type: 'Spree::Product', display_on: 'both')
- private_def = create(:metafield_definition, :back_end_only, resource_type: 'Spree::Product')
- create(:metafield, resource: product, metafield_definition: public_def, value: 'public')
- create(:metafield, resource: product, metafield_definition: private_def, value: 'private')
+ public_def = create(:custom_field_definition, resource_type: 'Spree::Product')
+ private_def = create(:custom_field_definition, :admin_only, resource_type: 'Spree::Product')
+ create(:custom_field, resource: product, custom_field_definition: public_def, value: 'public')
+ create(:custom_field, resource: product, custom_field_definition: private_def, value: 'private')
result = described_class.new(product, params: base_params.merge(expand: ['custom_fields'])).to_h
expect(result['custom_fields'].length).to eq(2)
diff --git a/spree/api/spec/serializers/spree/api/v3/custom_field_serializer_spec.rb b/spree/api/spec/serializers/spree/api/v3/custom_field_serializer_spec.rb
index db1dd825b6..79da698900 100644
--- a/spree/api/spec/serializers/spree/api/v3/custom_field_serializer_spec.rb
+++ b/spree/api/spec/serializers/spree/api/v3/custom_field_serializer_spec.rb
@@ -3,24 +3,24 @@ require 'spec_helper'
RSpec.describe Spree::Api::V3::CustomFieldSerializer do
let(:store) { @default_store }
let(:product) { create(:product) }
- let(:metafield_definition) { create(:metafield_definition, resource_type: 'Spree::Product', display_on: 'both') }
- let(:metafield) { create(:metafield, resource: product, metafield_definition: metafield_definition, value: 'test value') }
+ let(:custom_field_definition) { create(:custom_field_definition, resource_type: 'Spree::Product') }
+ let(:custom_field) { create(:custom_field, resource: product, custom_field_definition: custom_field_definition, value: 'test value') }
let(:base_params) { { store: store, currency: 'USD' } }
describe 'store serializer' do
- subject { described_class.new(metafield, params: base_params).to_h }
+ subject { described_class.new(custom_field, params: base_params).to_h }
it 'includes key as full_key' do
- expect(subject['key']).to eq(metafield.full_key)
+ expect(subject['key']).to eq(custom_field.full_key)
expect(subject['key']).to include('.')
end
it 'includes label' do
- expect(subject['label']).to eq(metafield.label)
+ expect(subject['label']).to eq(custom_field.label)
end
it 'includes type' do
- expect(subject['type']).to eq(metafield.type)
+ expect(subject['type']).to eq(custom_field.type)
end
it 'includes serialized value' do
@@ -36,30 +36,30 @@ end
RSpec.describe Spree::Api::V3::Admin::CustomFieldSerializer do
let(:store) { @default_store }
let(:product) { create(:product) }
- let(:metafield_definition) { create(:metafield_definition, resource_type: 'Spree::Product', display_on: 'back_end') }
- let(:metafield) { create(:metafield, resource: product, metafield_definition: metafield_definition, value: 'admin value') }
+ let(:custom_field_definition) { create(:custom_field_definition, resource_type: 'Spree::Product', storefront_visible: false) }
+ let(:custom_field) { create(:custom_field, resource: product, custom_field_definition: custom_field_definition, value: 'admin value') }
let(:base_params) { { store: store, currency: 'USD' } }
describe 'admin serializer' do
- subject { described_class.new(metafield, params: base_params).to_h }
+ subject { described_class.new(custom_field, params: base_params).to_h }
it 'includes standard attributes' do
expect(subject).to include(
- 'key' => metafield.full_key,
- 'label' => metafield.label,
- 'type' => metafield.type,
+ 'key' => custom_field.full_key,
+ 'label' => custom_field.label,
+ 'type' => custom_field.type,
'value' => 'admin value'
)
end
- it 'includes storefront_visible as false for back_end display_on' do
+ it 'includes storefront_visible as false for admin-only definitions' do
expect(subject['storefront_visible']).to be false
end
- it 'includes storefront_visible as true for both display_on' do
- public_definition = create(:metafield_definition, resource_type: 'Spree::Product', display_on: 'both')
- public_metafield = create(:metafield, resource: product, metafield_definition: public_definition, value: 'public value')
- result = described_class.new(public_metafield, params: base_params).to_h
+ it 'includes storefront_visible as true for storefront-visible definitions' do
+ public_definition = create(:custom_field_definition, resource_type: 'Spree::Product')
+ public_custom_field = create(:custom_field, resource: product, custom_field_definition: public_definition, value: 'public value')
+ result = described_class.new(public_custom_field, params: base_params).to_h
expect(result['storefront_visible']).to be true
end
diff --git a/spree/api/spec/serializers/spree/api/v3/product_serializer_spec.rb b/spree/api/spec/serializers/spree/api/v3/product_serializer_spec.rb
index c48f5a4360..9b419b0964 100644
--- a/spree/api/spec/serializers/spree/api/v3/product_serializer_spec.rb
+++ b/spree/api/spec/serializers/spree/api/v3/product_serializer_spec.rb
@@ -64,10 +64,10 @@ RSpec.describe Spree::Api::V3::ProductSerializer do
end
describe 'custom_fields' do
- let(:public_definition) { create(:metafield_definition, resource_type: 'Spree::Product', display_on: 'both') }
- let(:private_definition) { create(:metafield_definition, :back_end_only, resource_type: 'Spree::Product') }
- let!(:public_metafield) { create(:metafield, resource: product, metafield_definition: public_definition, value: 'public') }
- let!(:private_metafield) { create(:metafield, resource: product, metafield_definition: private_definition, value: 'private') }
+ let(:public_definition) { create(:custom_field_definition, resource_type: 'Spree::Product') }
+ let(:private_definition) { create(:custom_field_definition, :admin_only, resource_type: 'Spree::Product') }
+ let!(:public_custom_field) { create(:custom_field, resource: product, custom_field_definition: public_definition, value: 'public') }
+ let!(:private_custom_field) { create(:custom_field, resource: product, custom_field_definition: private_definition, value: 'private') }
it 'does not include custom_fields without expand param' do
expect(subject).not_to have_key('custom_fields')
diff --git a/spree/core/app/jobs/spree/images/save_from_url_job.rb b/spree/core/app/jobs/spree/images/save_from_url_job.rb
index 6fcbcd1b96..6371bc900c 100644
--- a/spree/core/app/jobs/spree/images/save_from_url_job.rb
+++ b/spree/core/app/jobs/spree/images/save_from_url_job.rb
@@ -14,7 +14,7 @@ module Spree
def perform(viewable_id, viewable_type, external_url, external_id = nil, position = nil, link_variant_id = nil)
viewable = viewable_type.safe_constantize.find(viewable_id)
- Spree::Image.ensure_metafield_definition_exists!(Spree::Image::EXTERNAL_URL_METAFIELD_KEY)
+ Spree::Image.ensure_custom_field_definition_exists!(Spree::Image::EXTERNAL_URL_CUSTOM_FIELD_KEY)
external_url = external_url.strip
external_id = external_id.to_s.downcase.strip if external_id.present?
diff --git a/spree/core/app/models/concerns/spree/metafield_filterable.rb b/spree/core/app/models/concerns/spree/custom_field_filterable.rb
similarity index 68%
rename from spree/core/app/models/concerns/spree/metafield_filterable.rb
rename to spree/core/app/models/concerns/spree/custom_field_filterable.rb
index eec2cb2f70..4f014cb1cd 100644
--- a/spree/core/app/models/concerns/spree/metafield_filterable.rb
+++ b/spree/core/app/models/concerns/spree/custom_field_filterable.rb
@@ -3,11 +3,11 @@
module Spree
# Resolves `cf_*` custom-field predicates (e.g. +cf_custom_material_i_cont+)
# into scopes. Ransack has no such attributes, so callers split them out of a
- # filter hash with {with_metafield_filters} before handing the rest to
+ # filter hash with {with_custom_field_filters} before handing the rest to
# Ransack. Lives on the model rather than in a SearchProvider so every
# consumer — the search providers, CSV export, any other Ransack entry
# point — resolves the same vocabulary.
- module MetafieldFilterable
+ module CustomFieldFilterable
extend ActiveSupport::Concern
# Arel comparison methods for numeric predicates.
@@ -35,22 +35,22 @@ module Spree
# "no filter" instead of a 500.
#
# @param filters [Hash]
- # @param schema [Spree::SearchProvider::MetafieldSchema, nil]
+ # @param schema [Spree::SearchProvider::CustomFieldSchema, nil]
# @return [Array(ActiveRecord::Relation, Hash)] scoped relation + remaining filters
- def with_metafield_filters(filters, schema: nil)
+ def with_custom_field_filters(filters, schema: nil)
return [all, filters] if filters.blank?
# Skip the schema's DB query entirely for the common case of a filter
# hash with no custom-field predicates at all.
return [all, filters] unless filters.any? { |key, _| key.to_s.start_with?('cf_') }
- schema ||= Spree::SearchProvider::MetafieldSchema.new
+ schema ||= Spree::SearchProvider::CustomFieldSchema.new
scope = all
remaining = filters.reject do |key, value|
parsed = schema.parse_filter(key)
next false unless parsed
- condition = metafield_filter_condition(parsed[:definition], parsed[:predicate], value)
+ condition = custom_field_filter_condition(parsed[:definition], parsed[:predicate], value)
scope = scope.where(condition) if condition
true
end
@@ -61,42 +61,42 @@ module Spree
# One EXISTS / NOT EXISTS subquery per predicate — composes with other
# filters without duplicating rows the way a join would.
#
- # @param definition [Spree::MetafieldDefinition]
+ # @param definition [Spree::CustomFieldDefinition]
# @param predicate [String]
# @param value [Object]
# @return [Arel::Nodes::Node, nil] nil when the value is unusable
- def metafield_filter_condition(definition, predicate, value)
+ def custom_field_filter_condition(definition, predicate, value)
case predicate
when 'present'
- metafield_exists(definition)
+ custom_field_exists(definition)
when 'blank'
- metafield_exists(definition).not
+ custom_field_exists(definition).not
else
- value_condition = metafield_value_condition(definition.field_type, predicate, value)
- value_condition && metafield_exists(definition, value_condition)
+ value_condition = custom_field_value_condition(definition.field_type, predicate, value)
+ value_condition && custom_field_exists(definition, value_condition)
end
end
- # Type-casts a metafield value column so numeric fields compare
- # numerically rather than lexicographically. Public because metafield
+ # Type-casts a custom_field value column so numeric fields compare
+ # numerically rather than lexicographically. Public because custom_field
# sorting in Spree::SearchProvider::Database applies the same cast to a
# differently-aliased join.
#
# @param column [Arel::Attributes::Attribute] value column
# @param field_type [String]
# @return [Arel::Nodes::Node] castable expression
- def metafield_value_expression(column, field_type)
+ def custom_field_value_expression(column, field_type)
return column unless field_type == 'number'
- Arel::Nodes::NamedFunction.new('CAST', [column.as(metafield_numeric_cast_type)])
+ Arel::Nodes::NamedFunction.new('CAST', [column.as(custom_field_numeric_cast_type)])
end
private
- # `CAST(... AS <type>)` target for numeric metafield comparisons. SQLite
+ # `CAST(... AS <type>)` target for numeric custom_field comparisons. SQLite
# has no DECIMAL affinity and PostgreSQL rejects MySQL's precision form,
# so the type is per-adapter.
- def metafield_numeric_cast_type
+ def custom_field_numeric_cast_type
case connection.adapter_name
when /PostgreSQL/i then 'numeric'
when /Mysql|Trilogy/i then 'DECIMAL(30, 10)'
@@ -104,15 +104,15 @@ module Spree
end
end
- # `EXISTS (SELECT 1 FROM spree_metafields WHERE …)` correlated against
+ # `EXISTS (SELECT 1 FROM spree_custom_fields WHERE …)` correlated against
# this model's rows, optionally narrowed by a value condition.
- def metafield_exists(definition, value_condition = nil)
- metafields = metafield_filter_table
- subquery = Arel::SelectManager.new(metafields).
+ def custom_field_exists(definition, value_condition = nil)
+ custom_fields = custom_field_filter_table
+ subquery = Arel::SelectManager.new(custom_fields).
project(Arel.sql('1')).
- where(metafields[:resource_type].eq(name)).
- where(metafields[:resource_id].eq(arel_table[primary_key])).
- where(metafields[:metafield_definition_id].eq(definition.id))
+ where(custom_fields[:resource_type].eq(name)).
+ where(custom_fields[:resource_id].eq(arel_table[primary_key])).
+ where(custom_fields[:custom_field_definition_id].eq(definition.id))
subquery = subquery.where(value_condition) if value_condition
@@ -122,13 +122,13 @@ module Spree
end
# Aliased so the correlated subquery can't collide with an outer join on
- # the same table (metafield sorting joins it as `sort_cf`).
- def metafield_filter_table
- @metafield_filter_table ||= Spree::Metafield.arel_table.alias('filter_cf')
+ # the same table (custom_field sorting joins it as `sort_cf`).
+ def custom_field_filter_table
+ @custom_field_filter_table ||= Spree::CustomField.arel_table.alias('filter_cf')
end
- def metafield_value_condition(field_type, predicate, value)
- column = metafield_filter_table[:value]
+ def custom_field_value_condition(field_type, predicate, value)
+ column = custom_field_filter_table[:value]
if field_type == 'number'
operator = NUMERIC_OPERATORS[predicate]
@@ -140,7 +140,7 @@ module Spree
return nil
end
- metafield_value_expression(column, field_type).public_send(operator, numeric)
+ custom_field_value_expression(column, field_type).public_send(operator, numeric)
elsif (pattern = LIKE_PATTERNS[predicate])
escaped = sanitize_sql_like(value.to_s)
# LIKE is already case-insensitive under MySQL's default collation
diff --git a/spree/core/app/models/concerns/spree/customer_methods.rb b/spree/core/app/models/concerns/spree/customer_methods.rb
index 97a995f1ed..fa90d60c57 100644
--- a/spree/core/app/models/concerns/spree/customer_methods.rb
+++ b/spree/core/app/models/concerns/spree/customer_methods.rb
@@ -3,7 +3,7 @@ module Spree
extend ActiveSupport::Concern
include Spree::PrefixedId
- include Spree::Metafields
+ include Spree::HasCustomFields
include Spree::UserAddress
include Spree::UserPaymentSource
include Spree::UserReporting
diff --git a/spree/core/app/models/concerns/spree/metafields.rb b/spree/core/app/models/concerns/spree/has_custom_fields.rb
similarity index 50%
rename from spree/core/app/models/concerns/spree/metafields.rb
rename to spree/core/app/models/concerns/spree/has_custom_fields.rb
index 0ff88aafda..63eb0e749c 100644
--- a/spree/core/app/models/concerns/spree/metafields.rb
+++ b/spree/core/app/models/concerns/spree/has_custom_fields.rb
@@ -1,11 +1,11 @@
module Spree
- module Metafields
+ module HasCustomFields
extend ActiveSupport::Concern
module ClassMethods
- def ensure_metafield_definition_exists!(key_with_namespace)
+ def ensure_custom_field_definition_exists!(key_with_namespace)
namespace, key = extract_namespace_and_key(key_with_namespace)
- Spree::MetafieldDefinition.find_or_create_by!(namespace: namespace, key: key, resource_type: self.name)
+ Spree::CustomFieldDefinition.find_or_create_by!(namespace: namespace, key: key, resource_type: self.name)
end
def extract_namespace_and_key(key_with_namespace)
@@ -13,24 +13,46 @@ module Spree
key = key_with_namespace.to_s.split('.').last
[namespace, key]
end
+
+ # Deprecated 6.0 names, removed in 6.1.
+ def ensure_metafield_definition_exists!(key_with_namespace)
+ Spree::Deprecation.warn('ensure_metafield_definition_exists! is deprecated and will be removed in Spree 6.1. Use ensure_custom_field_definition_exists! instead.')
+ ensure_custom_field_definition_exists!(key_with_namespace)
+ end
+
+ def with_metafield_key(key_with_namespace)
+ Spree::Deprecation.warn('.with_metafield_key is deprecated and will be removed in Spree 6.1. Use .with_custom_field_key instead.')
+ with_custom_field_key(key_with_namespace)
+ end
+
+ def with_metafield_key_value(key_with_namespace, value)
+ Spree::Deprecation.warn('.with_metafield_key_value is deprecated and will be removed in Spree 6.1. Use .with_custom_field_key_value instead.')
+ with_custom_field_key_value(key_with_namespace, value)
+ end
end
included do
- has_many :metafields, -> { includes(:metafield_definition) }, as: :resource, class_name: 'Spree::Metafield', dependent: :destroy
- has_many :public_metafields, -> { includes(:metafield_definition).available_on_front_end }, as: :resource, class_name: 'Spree::Metafield'
- has_many :private_metafields, -> { includes(:metafield_definition).available_on_back_end }, as: :resource, class_name: 'Spree::Metafield'
-
- accepts_nested_attributes_for :metafields, allow_destroy: true, reject_if: lambda { |mf|
- mf[:metafield_definition_id].blank? || (mf[:id].blank? && mf[:value].blank?)
+ has_many :custom_fields, -> { includes(:custom_field_definition) }, as: :resource, class_name: 'Spree::CustomField', dependent: :destroy
+ has_many :storefront_custom_fields, -> { includes(:custom_field_definition).storefront_visible }, as: :resource, class_name: 'Spree::CustomField'
+
+ # Deprecated 6.0 association names, removed in 6.1. `private_metafields`
+ # has no replacement — read `custom_fields` and filter, or query
+ # Spree::CustomField.admin_only directly.
+ has_many :metafields, -> { includes(:custom_field_definition) }, as: :resource, class_name: 'Spree::CustomField', deprecated: true
+ has_many :public_metafields, -> { includes(:custom_field_definition).storefront_visible }, as: :resource, class_name: 'Spree::CustomField', deprecated: true
+ has_many :private_metafields, -> { includes(:custom_field_definition).admin_only }, as: :resource, class_name: 'Spree::CustomField', deprecated: true
+
+ accepts_nested_attributes_for :custom_fields, allow_destroy: true, reject_if: lambda { |attrs|
+ attrs[:custom_field_definition_id].blank? || (attrs[:id].blank? && attrs[:value].blank?)
}
- # Override metafields_attributes= to automatically mark existing metafields
+ # Override custom_fields_attributes= to automatically mark existing custom fields
# with empty values for destruction
- def metafields_attributes=(attributes)
+ def custom_fields_attributes=(attributes)
attributes = attributes.values if attributes.is_a?(Hash)
attributes.each do |attrs|
- # If this is an existing metafield (has an id) and value is blank,
+ # If this is an existing custom field (has an id) and value is blank,
# mark it for destruction
if attrs[:id].present? && value_blank?(attrs[:value])
attrs[:_destroy] = true
@@ -40,37 +62,36 @@ module Spree
super(attributes)
end
- # API-facing alias for the 6.0 rename (`5.4-6.0-custom-fields-rename.md`):
- # callers see "custom fields" everywhere even though the underlying
- # tables/columns still use `metafield*`. Reached via flat params on the
- # admin API v3 (`custom_fields: [...]`); also works through
+ # Bulk writer reached via flat params on the admin API v3
+ # (`custom_fields: [...]`); also works through
# `Model.new(permitted_params)` since Rails routes the key to this writer.
#
# Upsert semantics by `custom_field_definition_id`: existing entries
# for the same definition are updated, missing entries are created.
# Partial: definitions NOT in the array are left untouched, so the
# client can patch one field at a time without resending the rest.
- # Blank values on an existing metafield destroy it (mirrors the dedicated
- # endpoint's behavior via `metafields_attributes=`).
+ # Blank values on an existing custom field destroy it (mirrors the dedicated
+ # endpoint's behavior via `custom_fields_attributes=`).
def custom_fields=(attributes)
return if attributes.blank?
- return super(attributes) if attributes.first.is_a?(Spree::Metafield)
+ return super(attributes) if attributes.first.is_a?(Spree::CustomField)
assign_custom_field_attrs(attributes)
end
after_save :apply_pending_custom_fields, if: -> { @pending_custom_field_attrs.present? }
- scope :with_metafield_key, ->(key_with_namespace) {
+ scope :with_custom_field_key, ->(key_with_namespace) {
namespace, key = extract_namespace_and_key(key_with_namespace)
- joins(metafields: :metafield_definition).where(spree_metafield_definitions: { namespace: namespace, key: key })
+ joins(custom_fields: :custom_field_definition).
+ where(Spree::CustomFieldDefinition.table_name => { namespace: namespace, key: key })
}
- scope :with_metafield_key_value, ->(key_with_namespace, value) {
+ scope :with_custom_field_key_value, ->(key_with_namespace, value) {
namespace, key = extract_namespace_and_key(key_with_namespace)
- joins(metafields: :metafield_definition)
- .where(spree_metafield_definitions: { namespace: namespace, key: key })
- .where(spree_metafields: { value: value })
+ joins(custom_fields: :custom_field_definition)
+ .where(Spree::CustomFieldDefinition.table_name => { namespace: namespace, key: key })
+ .where(Spree::CustomField.table_name => { value: value })
}
def extract_namespace_and_key(key_with_namespace)
@@ -82,51 +103,51 @@ module Spree
#
# - `"namespace.key"` string — auto-creates the definition if missing
# (backend-internal callers that don't know the id upfront).
- # - {Spree::MetafieldDefinition} instance.
+ # - {Spree::CustomFieldDefinition} instance.
# - Integer / numeric String — raw definition id.
# - Prefixed-id String (`"cfdef_..."`) — decoded to the definition id.
#
# Blank values (nil or empty/whitespace string) destroy any existing
- # metafield for the definition. Empty containers (`[]`, `{}`) and
+ # custom field for the definition. Empty containers (`[]`, `{}`) and
# numeric / boolean falsy values are real values, not blanks.
#
- # @param definition_or_key [String, Integer, Spree::MetafieldDefinition]
+ # @param definition_or_key [String, Integer, Spree::CustomFieldDefinition]
# @param value [Object] the value to persist; type is enforced by the
- # typed metafield subclass (Boolean, Number, Json, ShortText, …).
- # @return [Spree::Metafield, nil] the persisted metafield, or nil when
+ # typed custom-field subclass (Boolean, Number, Json, ShortText, …).
+ # @return [Spree::CustomField, nil] the persisted custom field, or nil when
# the value was blank and any existing row was destroyed.
# @raise [ArgumentError] if `definition_or_key` doesn't resolve to a
# known definition.
- def set_metafield(definition_or_key, value)
- definition_id = resolve_metafield_definition_id(definition_or_key)
- metafield = metafields.find_or_initialize_by(metafield_definition_id: definition_id)
+ def set_custom_field(definition_or_key, value)
+ definition_id = resolve_custom_field_definition_id(definition_or_key)
+ custom_field = custom_fields.find_or_initialize_by(custom_field_definition_id: definition_id)
if value_blank?(value)
- metafield.destroy if metafield.persisted?
+ custom_field.destroy if custom_field.persisted?
return nil
end
- # JSON metafields store canonical JSON in the underlying text column.
+ # JSON custom fields store canonical JSON in the underlying text column.
# Coerce Hash/Array values BEFORE assignment, since the STI subclass
- # (`Spree::Metafields::Json`) isn't switched on until before_validation,
+ # (`Spree::CustomFields::Json`) isn't switched on until before_validation,
# so its custom `value=` writer doesn't run yet on a fresh
# `find_or_initialize_by` record.
if (value.is_a?(Hash) || value.is_a?(Array)) &&
- metafield.metafield_definition&.metafield_type == 'Spree::Metafields::Json'
+ custom_field.custom_field_definition&.field_type == 'json'
value = value.to_json
end
- metafield.value = value
- metafield.save!
- metafield
+ custom_field.value = value
+ custom_field.save!
+ custom_field
end
- def get_metafield(key_with_namespace)
+ def get_custom_field(key_with_namespace)
namespace, key = extract_namespace_and_key(key_with_namespace)
- metafields.with_key(namespace, key).first
+ custom_fields.with_key(namespace, key).first
end
- def has_metafield?(key_with_namespace)
- if key_with_namespace.is_a?(Spree::MetafieldDefinition)
+ def has_custom_field?(key_with_namespace)
+ if key_with_namespace.is_a?(Spree::CustomFieldDefinition)
namespace = key_with_namespace.namespace
key = key_with_namespace.key
elsif key_with_namespace.is_a?(String)
@@ -135,17 +156,49 @@ module Spree
raise ArgumentError, "Invalid key_with_namespace: #{key_with_namespace.inspect}"
end
- metafields.with_key(namespace, key).exists?
+ custom_fields.with_key(namespace, key).exists?
+ end
+
+ # Deprecated 6.0 names, removed in 6.1.
+ def set_metafield(definition_or_key, value)
+ Spree::Deprecation.warn('#set_metafield is deprecated and will be removed in Spree 6.1. Use #set_custom_field instead.')
+ set_custom_field(definition_or_key, value)
+ end
+
+ def get_metafield(key_with_namespace)
+ Spree::Deprecation.warn('#get_metafield is deprecated and will be removed in Spree 6.1. Use #get_custom_field instead.')
+ get_custom_field(key_with_namespace)
+ end
+
+ def has_metafield?(key_with_namespace)
+ Spree::Deprecation.warn('#has_metafield? is deprecated and will be removed in Spree 6.1. Use #has_custom_field? instead.')
+ has_custom_field?(key_with_namespace)
+ end
+
+ # Legacy payloads key the definition as `metafield_definition_id`, which
+ # the new writer rejects — translate rather than silently dropping them.
+ def metafields_attributes=(attributes)
+ Spree::Deprecation.warn('#metafields_attributes= is deprecated and will be removed in Spree 6.1. Use #custom_fields_attributes= instead.')
+
+ attributes = attributes.values if attributes.is_a?(Hash)
+ translated = attributes.map do |attrs|
+ attrs = attrs.respond_to?(:to_h) ? attrs.to_h : attrs
+ attrs = attrs.with_indifferent_access
+ attrs[:custom_field_definition_id] ||= attrs.delete(:metafield_definition_id)
+ attrs
+ end
+
+ self.custom_fields_attributes = translated
end
private
- # Decide whether a metafield value should trigger the destroy-existing
+ # Decide whether a custom-field value should trigger the destroy-existing
# branch. Ruby's `blank?` reports `false`, `0`, `[]`, `{}` as blank, but
- # for typed metafields those are real values:
+ # for typed custom fields those are real values:
#
# - Boolean `false` / Numeric `0` — real values, never destroy.
- # - Empty Array / Hash — a JSON metafield storing `[]` or `{}` is a
+ # - Empty Array / Hash — a JSON custom field storing `[]` or `{}` is a
# meaningful value (an empty list / object), not a clear signal.
#
# Only `nil` and empty/whitespace strings count as "missing".
@@ -161,7 +214,7 @@ module Spree
def assign_custom_field_attrs(attributes)
if new_record?
- # Persisting metafields requires a persisted parent (resource_id NOT
+ # Persisting custom_fields requires a persisted parent (resource_id NOT
# NULL). Stash the attrs and replay them after the parent is saved.
@pending_custom_field_attrs = attributes
return
@@ -181,11 +234,11 @@ module Spree
attributes.each_with_index do |raw, index|
attrs = raw.respond_to?(:to_h) ? raw.to_h : raw
attrs = attrs.with_indifferent_access
- definition_id = attrs[:metafield_definition_id] || attrs[:custom_field_definition_id]
+ definition_id = attrs[:custom_field_definition_id] || attrs[:metafield_definition_id]
next if definition_id.blank?
begin
- set_metafield(definition_id, attrs[:value])
+ set_custom_field(definition_id, attrs[:value])
rescue ArgumentError => e
# Convert an unknown / malformed definition id into a field-level
# validation error so the controller returns 422 with structured
@@ -197,20 +250,20 @@ module Spree
end
# Resolve any of the supported reference shapes to a raw definition id.
- # See {#set_metafield} for the accepted shapes.
+ # See {#set_custom_field} for the accepted shapes.
#
- # @param definition_or_key [String, Integer, Spree::MetafieldDefinition]
+ # @param definition_or_key [String, Integer, Spree::CustomFieldDefinition]
# @return [Integer, String] the definition's primary key value (Integer
# for legacy integer-id setups, String for UUID setups).
# @raise [ArgumentError] for unknown / malformed input.
- def resolve_metafield_definition_id(definition_or_key)
+ def resolve_custom_field_definition_id(definition_or_key)
case definition_or_key
- when Spree::MetafieldDefinition
+ when Spree::CustomFieldDefinition
definition_or_key.id
when Integer
definition_or_key
when String
- resolve_metafield_definition_id_from_string(definition_or_key)
+ resolve_custom_field_definition_id_from_string(definition_or_key)
else
raise ArgumentError, "Invalid definition_or_key: #{definition_or_key.inspect}"
end
@@ -220,12 +273,12 @@ module Spree
# (`"cfdef_..."`), or a bare numeric id (`"42"`).
# @return [Integer, String] the resolved definition's primary key value.
# @raise [ArgumentError] if the string doesn't match any known shape.
- def resolve_metafield_definition_id_from_string(value)
+ def resolve_custom_field_definition_id_from_string(value)
# `"namespace.key"` — backend-internal callers that don't know the id;
# auto-create the definition if missing.
if value.include?('.')
namespace, key = extract_namespace_and_key(value)
- return Spree::MetafieldDefinition.find_or_create_by!(
+ return Spree::CustomFieldDefinition.find_or_create_by!(
namespace: namespace, key: key, resource_type: self.class.name
).id
end
@@ -235,21 +288,22 @@ module Spree
# don't get mistaken for prefixed ids. We must verify the decoded id
# actually exists — Sqids will happily decode any all-lowercase
# alphanumeric string to a phantom integer; without the existence
- # check `find_or_initialize_by(metafield_definition_id: phantom_id)`
- # would later raise a confusing "Metafield definition must exist"
+ # check `find_or_initialize_by(custom_field_definition_id: phantom_id)`
+ # would later raise a confusing "CustomField definition must exist"
# 422 instead of an "unknown id" 422.
if Spree::PrefixedId.prefixed_id?(value)
- decoded = Spree::MetafieldDefinition.decode_prefixed_id(value)
- existing = decoded && Spree::MetafieldDefinition.find_by(id: decoded)
- raise ArgumentError, "Unknown metafield definition id: #{value.inspect}" if existing.nil?
+ decoded = Spree::CustomFieldDefinition.decode_prefixed_id(value)
+ existing = decoded && Spree::CustomFieldDefinition.find_by(id: decoded)
+ raise ArgumentError, "Unknown custom field definition id: #{value.inspect}" if existing.nil?
return existing.id
end
- # Bare numeric id ("42"). Reject anything else outright.
- raise ArgumentError, "Invalid metafield definition reference: #{value.inspect}" unless /\A\d+\z/.match?(value)
+ # Bare numeric id ("42"). Reject anything else outright. Returned as
+ # the original string — casting would rewrite zero-padded ids.
+ raise ArgumentError, "Invalid custom field definition reference: #{value.inspect}" unless /\A\d+\z/.match?(value)
- value.to_i
+ value
end
end
end
diff --git a/spree/core/app/models/concerns/spree/metadata.rb b/spree/core/app/models/concerns/spree/metadata.rb
index 0653e3652d..06c10ea6d3 100644
--- a/spree/core/app/models/concerns/spree/metadata.rb
+++ b/spree/core/app/models/concerns/spree/metadata.rb
@@ -1,9 +1,10 @@
module Spree
+ # Private, schemaless developer data. Deliberately does NOT pull in
+ # {Spree::HasCustomFields} — custom fields are the separate, public,
+ # schema-defined system. Models that want both include both.
module Metadata
extend ActiveSupport::Concern
- include Spree::Metafields unless included_modules.include?(Spree::Metafields)
-
included do
attribute :metadata, default: {}
diff --git a/spree/core/app/models/spree/address.rb b/spree/core/app/models/spree/address.rb
index ae5aa801a6..a8bfe973ea 100644
--- a/spree/core/app/models/spree/address.rb
+++ b/spree/core/app/models/spree/address.rb
@@ -4,7 +4,7 @@ module Spree
require 'validates_zipcode'
- include Spree::Metafields
+ include Spree::HasCustomFields
include Spree::Metadata
serialize :preferences, type: Hash, coder: YAML, default: {}
@@ -41,7 +41,7 @@ module Spree
belongs_to :country, class_name: 'Spree::Country'
belongs_to :state, class_name: 'Spree::State', optional: true
- # we need a safe operator here as Address is added to metafield_enabled_resources in Engine
+ # we need a safe operator here as Address is added to custom_field_enabled_resources in Engine
belongs_to :customer, class_name: Spree.customer_class&.name, optional: true, touch: true
include Spree::DeprecatedCustomerAlias
diff --git a/spree/core/app/models/spree/asset.rb b/spree/core/app/models/spree/asset.rb
index 36e1829270..d2d3b3f90f 100644
--- a/spree/core/app/models/spree/asset.rb
+++ b/spree/core/app/models/spree/asset.rb
@@ -4,7 +4,7 @@ module Spree
include Support::ActiveStorage
include Rails.application.routes.url_helpers
- include Spree::Metafields
+ include Spree::HasCustomFields
include Spree::Metadata
# Legacy styles support (was in Spree::Image::Configuration::ActiveStorage)
@@ -21,7 +21,7 @@ module Spree
publishes_lifecycle_events
- EXTERNAL_URL_METAFIELD_KEY = 'external.url'
+ EXTERNAL_URL_CUSTOM_FIELD_KEY = 'external.url'
MEDIA_TYPES = %w[image video external_video].freeze
after_initialize { self.media_type ||= 'image' }
@@ -74,7 +74,7 @@ module Spree
scope :with_session_uploaded_assets_uuid, lambda { |uuid|
where(session_id: uuid)
}
- scope :with_external_url, ->(url) { url.present? ? with_metafield_key_value(EXTERNAL_URL_METAFIELD_KEY, url.strip) : none }
+ scope :with_external_url, ->(url) { url.present? ? with_custom_field_key_value(EXTERNAL_URL_CUSTOM_FIELD_KEY, url.strip) : none }
# Callbacks merged from Spree::Image
after_commit :touch_product_variants, if: :should_touch_product_variants?, on: :update
@@ -119,11 +119,11 @@ module Spree
end
def external_url
- get_metafield(EXTERNAL_URL_METAFIELD_KEY)&.value
+ get_custom_field(EXTERNAL_URL_CUSTOM_FIELD_KEY)&.value
end
def external_url=(url)
- set_metafield(EXTERNAL_URL_METAFIELD_KEY, url.strip)
+ set_custom_field(EXTERNAL_URL_CUSTOM_FIELD_KEY, url.strip)
end
def skip_import?
diff --git a/spree/core/app/models/spree/category.rb b/spree/core/app/models/spree/category.rb
index f9ab27164e..11c3c73197 100644
--- a/spree/core/app/models/spree/category.rb
+++ b/spree/core/app/models/spree/category.rb
@@ -14,7 +14,7 @@ module Spree
include Spree::TranslatableResource
include Spree::TranslatableResourceSlug
- include Spree::Metafields
+ include Spree::HasCustomFields
include Spree::Metadata
include Spree::MemoizedData
diff --git a/spree/core/app/models/spree/channel.rb b/spree/core/app/models/spree/channel.rb
index 8d942671f9..9e44569af9 100644
--- a/spree/core/app/models/spree/channel.rb
+++ b/spree/core/app/models/spree/channel.rb
@@ -8,7 +8,7 @@ module Spree
has_prefix_id :ch
include Spree::SingleStoreResource
- include Spree::Metafields
+ include Spree::HasCustomFields
include Spree::Metadata
include Spree::OrderRouting::HasStrategyPreference
include Spree::Channel::Gating
diff --git a/spree/core/app/models/spree/claim.rb b/spree/core/app/models/spree/claim.rb
index 7a6d71832b..45273f8d66 100644
--- a/spree/core/app/models/spree/claim.rb
+++ b/spree/core/app/models/spree/claim.rb
@@ -13,7 +13,7 @@ module Spree
include Spree::NumberIdentifier
include Spree::SingleStoreResource
include Spree::HasStatus
- include Spree::Metafields
+ include Spree::HasCustomFields
include Spree::Metadata
publishes_lifecycle_events
diff --git a/spree/core/app/models/spree/collection.rb b/spree/core/app/models/spree/collection.rb
index 6885d3b3bb..3d9453f10c 100644
--- a/spree/core/app/models/spree/collection.rb
+++ b/spree/core/app/models/spree/collection.rb
@@ -24,6 +24,7 @@ module Spree
include Spree::TranslatableResource
include Spree::TranslatableResourceSlug
+ include Spree::HasCustomFields
include Spree::Metadata
#
diff --git a/spree/core/app/models/spree/credit_card.rb b/spree/core/app/models/spree/credit_card.rb
index 27f5bb211c..df9b10d1b2 100644
--- a/spree/core/app/models/spree/credit_card.rb
+++ b/spree/core/app/models/spree/credit_card.rb
@@ -2,7 +2,7 @@ module Spree
class CreditCard < Spree.base_class
has_prefix_id :card # Stripe: card_
- include Spree::Metafields
+ include Spree::HasCustomFields
include Spree::Metadata
include Spree::PaymentSourceConcern
diff --git a/spree/core/app/models/spree/custom_field.rb b/spree/core/app/models/spree/custom_field.rb
index bef54706ee..36ffb6de87 100644
--- a/spree/core/app/models/spree/custom_field.rb
+++ b/spree/core/app/models/spree/custom_field.rb
@@ -1,9 +1,146 @@
module Spree
- # Constant alias for the legacy Spree::Metafield class. Lets controllers,
- # serializers, and 5.5+ extensions reference the model by its 6.0-bound name
- # without the actual class rename (which lands with the table rename in 6.0).
- #
- # This is a true constant alias — the underlying class, table, STI subclasses,
- # and `model_name` are all `Spree::Metafield`. Only the constant name differs.
- CustomField = Metafield
+ class CustomField < Spree.base_class
+ # Map of API-facing tokens to Ruby STI class names. The wire format is the
+ # token (`short_text`); the database column stores the class name. Reads
+ # translate to the token via `field_type`; writes accept either form.
+ # Plugin-defined types fall through to the raw class name until a
+ # registration API lands.
+ TYPE_TOKENS = {
+ 'short_text' => 'Spree::CustomFields::ShortText',
+ 'long_text' => 'Spree::CustomFields::LongText',
+ 'rich_text' => 'Spree::CustomFields::RichText',
+ 'number' => 'Spree::CustomFields::Number',
+ 'boolean' => 'Spree::CustomFields::Boolean',
+ 'json' => 'Spree::CustomFields::Json'
+ }.freeze
+ TYPE_CLASS_TO_TOKEN = TYPE_TOKENS.invert.freeze
+
+ # Array form consumed by serializers via
+ # `typelize field_type: Spree::CustomField::FIELD_TYPE_TOKENS`. Typelizer
+ # emits a string-literal union in TypeScript and `{type: string, enum: […]}`
+ # in OpenAPI (string-array form was added in typelizer 0.10.0).
+ FIELD_TYPE_TOKENS = TYPE_TOKENS.keys.freeze
+
+ # Whether CustomFieldDefinition may enable `searchable` / `sortable` for
+ # this STI type. Used only by definition validations (not by SearchProvider
+ # indexing). Defaults to false; subclasses override (e.g. ShortText).
+ def self.searchable?
+ false
+ end
+
+ def self.sortable?
+ false
+ end
+
+ has_prefix_id :cf
+
+ #
+ # Associations
+ #
+ belongs_to :resource, polymorphic: true, touch: true
+ belongs_to :custom_field_definition, class_name: 'Spree::CustomFieldDefinition'
+
+ # API-facing form of the STI `type` column. Returns the token
+ # (`short_text`) when the row's type is a registered built-in; falls
+ # through to the raw class name for plugin types.
+ #
+ # `self[:type]` reads the raw column to bypass AR's STI reader (which
+ # returns the resolved class constant, not a string).
+ def field_type
+ TYPE_CLASS_TO_TOKEN[self[:type]] || self[:type]
+ end
+
+ #
+ # Delegations
+ #
+ delegate :key, :full_key, :label, :storefront_visible, to: :custom_field_definition, allow_nil: true
+
+ #
+ # Callbacks
+ #
+ before_validation :set_type_from_custom_field_definition, on: :create
+
+ #
+ # Validations
+ #
+ validates :custom_field_definition, :type, :resource, :value, presence: true
+ validates :custom_field_definition_id, uniqueness: { scope: [:resource_type, :resource_id] }
+ validate :type_must_match_custom_field_definition
+ validate :resource_type_must_match_custom_field_definition
+
+ #
+ # Scopes
+ #
+ scope :storefront_visible, -> { joins(:custom_field_definition).merge(Spree::CustomFieldDefinition.storefront_visible) }
+ scope :admin_only, -> { joins(:custom_field_definition).merge(Spree::CustomFieldDefinition.admin_only) }
+ scope :with_key, ->(namespace, key) {
+ joins(:custom_field_definition).
+ where(Spree::CustomFieldDefinition.table_name => { namespace: namespace, key: key })
+ }
+
+ def serialize_value
+ value
+ end
+
+ def csv_value
+ value.to_s
+ end
+
+ #
+ # Deprecated 6.0 names, removed in 6.1
+ #
+ def metafield_definition
+ Spree::Deprecation.warn('#metafield_definition is deprecated and will be removed in Spree 6.1. Use #custom_field_definition instead.')
+ custom_field_definition
+ end
+
+ def metafield_definition_id
+ Spree::Deprecation.warn('#metafield_definition_id is deprecated and will be removed in Spree 6.1. Use #custom_field_definition_id instead.')
+ custom_field_definition_id
+ end
+
+ def metafield_definition_id=(value)
+ Spree::Deprecation.warn('#metafield_definition_id= is deprecated and will be removed in Spree 6.1. Use #custom_field_definition_id= instead.')
+ self.custom_field_definition_id = value
+ end
+
+ def metafield_definition=(value)
+ Spree::Deprecation.warn('#metafield_definition= is deprecated and will be removed in Spree 6.1. Use #custom_field_definition= instead.')
+ self.custom_field_definition = value
+ end
+
+ def name
+ Spree::Deprecation.warn('#name is deprecated and will be removed in Spree 6.1. Use #label instead.')
+ label
+ end
+
+ private
+
+ def set_type_from_custom_field_definition
+ return if custom_field_definition.blank?
+
+ self.type ||= custom_field_definition.field_type_class_name
+ end
+
+ def type_must_match_custom_field_definition
+ return if custom_field_definition.blank?
+
+ errors.add(:type, 'must match custom field definition') unless type == custom_field_definition.field_type_class_name
+ end
+
+ # A definition belongs to one resource type; attaching it to a different
+ # one produces a row no lookup for either type would return. STI resources
+ # store their base class in the polymorphic column (an Image row reads
+ # `Spree::Asset`) while definitions name the concrete class, so compare
+ # against the definition's base class too.
+ def resource_type_must_match_custom_field_definition
+ return if custom_field_definition.blank? || resource_type.blank?
+
+ definition_type = custom_field_definition.resource_type
+ return if resource_type == definition_type
+ return if definition_type.safe_constantize&.base_class&.name == resource_type
+
+ errors.add(:resource_type, 'must match custom field definition')
+ end
+ end
end
diff --git a/spree/core/app/models/spree/custom_field_definition.rb b/spree/core/app/models/spree/custom_field_definition.rb
index a9bd22ac02..d238f32954 100644
--- a/spree/core/app/models/spree/custom_field_definition.rb
+++ b/spree/core/app/models/spree/custom_field_definition.rb
@@ -1,7 +1,172 @@
module Spree
- # Constant alias for the legacy Spree::MetafieldDefinition class. Lets
- # controllers, serializers, and 5.5+ extensions reference the model by its
- # 6.0-bound name without the actual class rename (which lands with the table
- # rename in 6.0).
- CustomFieldDefinition = MetafieldDefinition
+ class CustomFieldDefinition < Spree.base_class
+ has_prefix_id :cfdef
+
+ include Spree::CustomFieldDefinition::SearchCapabilities
+
+ #
+ # Associations
+ #
+ has_many :custom_fields, class_name: 'Spree::CustomField', dependent: :destroy
+
+ #
+ # Validations
+ #
+ validates :namespace, :key, :label, :resource_type, presence: true
+ validates :resource_type, presence: true, inclusion: { in: :valid_available_resources }
+ validates :key, uniqueness: { scope: spree_base_uniqueness_scope + [:resource_type, :namespace] }
+ validate :field_type_input_must_be_recognized
+ validate :field_type_must_be_available
+
+ #
+ # Scopes
+ #
+ scope :for_resource_type, ->(resource_type) { where(resource_type: resource_type) }
+ scope :storefront_visible, -> { where(storefront_visible: true) }
+ scope :admin_only, -> { where(storefront_visible: false) }
+ scope :search, ->(query) do
+ return all if query.blank?
+
+ search_term = "%#{query.downcase}%"
+ namespace_condition = arel_table[:namespace].lower.matches(search_term)
+ key_condition = arel_table[:key].lower.matches(search_term)
+ label_condition = arel_table[:label].lower.matches(search_term)
+
+ where(namespace_condition.or(key_condition).or(label_condition))
+ end
+
+ #
+ # Callbacks
+ #
+ normalizes :key, with: ->(value) { value.to_s.parameterize.underscore.strip }
+ normalizes :namespace, with: ->(value) { value.to_s.parameterize.underscore.strip }
+ before_validation :set_default_type, if: -> { self[:field_type].blank? }, on: :create
+ before_validation :set_label_from_key, if: -> { label.blank? }, on: :create
+
+ #
+ # Ransack
+ #
+ self.whitelisted_ransackable_attributes = %w[key namespace label resource_type storefront_visible searchable sortable]
+ self.whitelisted_ransackable_scopes = %w[search]
+
+ # API-facing token for the STI subclass name stored in the `field_type`
+ # column. Reader returns the registered token (`short_text`); writer
+ # accepts either the token or the class-name form, which is what the
+ # column itself holds.
+ def field_type
+ Spree::CustomField::TYPE_CLASS_TO_TOKEN[self[:field_type]] || self[:field_type]
+ end
+
+ def field_type=(value)
+ string_value = value.to_s
+ mapped = Spree::CustomField::TYPE_TOKENS[string_value]
+ # An input is "recognized" when it's a known token (mapped to a class) or
+ # any registered class name — extensions register their own types, which
+ # have no token. Anything else gets surfaced as an error on `field_type`
+ # so API clients get a token-vocabulary message instead of a raw
+ # class-name inclusion error.
+ @field_type_input_recognized = !mapped.nil? || valid_available_types.include?(string_value)
+ super(mapped || value)
+ end
+
+ # The raw STI class name stored in the column, as opposed to the API token
+ # returned by {#field_type}.
+ # @return [String]
+ def field_type_class_name
+ self[:field_type]
+ end
+
+ #
+ # Deprecated 6.0 column names, removed in 6.1
+ #
+ def name
+ Spree::Deprecation.warn('#name is deprecated and will be removed in Spree 6.1. Use #label instead.')
+ label
+ end
+
+ def name=(value)
+ Spree::Deprecation.warn('#name= is deprecated and will be removed in Spree 6.1. Use #label= instead.')
+ self.label = value
+ end
+
+ def metafield_type
+ Spree::Deprecation.warn('#metafield_type is deprecated and will be removed in Spree 6.1. Use #field_type (which returns an API token) or #field_type_class_name instead.')
+ field_type_class_name
+ end
+
+ def metafield_type=(value)
+ Spree::Deprecation.warn('#metafield_type= is deprecated and will be removed in Spree 6.1. Use #field_type= instead.')
+ self.field_type = value
+ end
+
+ # The tri-state display_on collapsed into the storefront_visible boolean;
+ # 'front_end' folds into visible since it never meant hidden-from-storefront.
+ def display_on
+ Spree::Deprecation.warn('#display_on is deprecated and will be removed in Spree 6.1. Use #storefront_visible instead.')
+ storefront_visible? ? 'both' : 'back_end'
+ end
+
+ def display_on=(value)
+ Spree::Deprecation.warn('#display_on= is deprecated and will be removed in Spree 6.1. Use #storefront_visible= instead.')
+ self.storefront_visible = value.to_s != 'back_end'
+ end
+
+ # Returns the full key with namespace
+ # @return [String] eg. custom.id
+ def full_key
+ "#{namespace}.#{key}"
+ end
+
+ # Returns the CSV header name for this custom field
+ # @return [String] eg. custom_field.custom.id
+ def csv_header_name
+ "custom_field.#{full_key}"
+ end
+
+ # Returns the available types
+ # @return [Array<Class>]
+ def self.available_types
+ Spree.custom_fields.types
+ end
+
+ # Returns the available resources
+ # @return [Array<Class>]
+ def self.available_resources
+ Spree.custom_fields.enabled_resources
+ end
+
+ private
+
+ def valid_available_types
+ self.class.available_types.map(&:to_s)
+ end
+
+ def field_type_input_must_be_recognized
+ return if @field_type_input_recognized.nil? || @field_type_input_recognized
+
+ tokens = Spree::CustomField::TYPE_TOKENS.keys.join(', ')
+ errors.add(:field_type, "is not a known custom field type (expected one of: #{tokens})")
+ end
+
+ # Validates the stored class name, not the token the reader returns.
+ def field_type_must_be_available
+ class_name = field_type_class_name
+ return errors.add(:field_type, :blank) if class_name.blank?
+ return if valid_available_types.include?(class_name)
+
+ errors.add(:field_type, :inclusion)
+ end
+
+ def valid_available_resources
+ self.class.available_resources.map(&:to_s)
+ end
+
+ def set_default_type
+ self[:field_type] ||= Spree.custom_fields.types.first.to_s
+ end
+
+ def set_label_from_key
+ self.label ||= key.titleize
+ end
+ end
end
diff --git a/spree/core/app/models/spree/metafield_definition/search_capabilities.rb b/spree/core/app/models/spree/custom_field_definition/search_capabilities.rb
similarity index 89%
rename from spree/core/app/models/spree/metafield_definition/search_capabilities.rb
rename to spree/core/app/models/spree/custom_field_definition/search_capabilities.rb
index 6146078e34..2fe03d41f1 100644
--- a/spree/core/app/models/spree/metafield_definition/search_capabilities.rb
+++ b/spree/core/app/models/spree/custom_field_definition/search_capabilities.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true
module Spree
- class MetafieldDefinition
+ class CustomFieldDefinition
module SearchCapabilities
extend ActiveSupport::Concern
@@ -29,13 +29,13 @@ module Spree
private
- # Builds API tokens from {Spree::MetafieldDefinition.available_types}
- # (`Spree.metafields.types` — in-memory registry, not a DB query).
+ # Builds API tokens from {Spree::CustomFieldDefinition.available_types}
+ # (`Spree.custom_fields.types` — in-memory registry, not a DB query).
def build_field_type_tokens(&block)
available_types.filter_map do |klass|
next unless block.call(klass)
- Spree::Metafield::TYPE_CLASS_TO_TOKEN[klass.to_s] || klass.to_s
+ Spree::CustomField::TYPE_CLASS_TO_TOKEN[klass.to_s] || klass.to_s
end
end
end
@@ -73,14 +73,14 @@ module Spree
errors.add(:key, :taken) if scope.exists?
end
- def metafield_type_class
- metafield_type.presence&.safe_constantize
+ def field_type_class
+ field_type_class_name.presence&.safe_constantize
end
def search_sort_capabilities_compatible_with_type
return unless searchable? || sortable?
- klass = metafield_type_class
+ klass = field_type_class
return if klass.nil?
%i[searchable sortable].each do |capability|
diff --git a/spree/core/app/models/spree/metafields/boolean.rb b/spree/core/app/models/spree/custom_fields/boolean.rb
similarity index 79%
rename from spree/core/app/models/spree/metafields/boolean.rb
rename to spree/core/app/models/spree/custom_fields/boolean.rb
index 2a6770f45a..3ac1578f09 100644
--- a/spree/core/app/models/spree/metafields/boolean.rb
+++ b/spree/core/app/models/spree/custom_fields/boolean.rb
@@ -1,6 +1,6 @@
module Spree
- module Metafields
- class Boolean < Spree::Metafield
+ module CustomFields
+ class Boolean < Spree::CustomField
normalizes :value, with: ->(value) { value.to_b.to_s }
def csv_value
diff --git a/spree/core/app/models/spree/metafields/json.rb b/spree/core/app/models/spree/custom_fields/json.rb
similarity index 93%
rename from spree/core/app/models/spree/metafields/json.rb
rename to spree/core/app/models/spree/custom_fields/json.rb
index d4fa6aec38..ba598c5dd1 100644
--- a/spree/core/app/models/spree/metafields/json.rb
+++ b/spree/core/app/models/spree/custom_fields/json.rb
@@ -1,6 +1,6 @@
module Spree
- module Metafields
- class Json < Spree::Metafield
+ module CustomFields
+ class Json < Spree::CustomField
validate :value_must_be_valid_json
# Accept either a JSON-serialized String (from CSV / Admin UI text
diff --git a/spree/core/app/models/spree/metafields/long_text.rb b/spree/core/app/models/spree/custom_fields/long_text.rb
similarity index 69%
rename from spree/core/app/models/spree/metafields/long_text.rb
rename to spree/core/app/models/spree/custom_fields/long_text.rb
index c022e80a65..903308ec12 100644
--- a/spree/core/app/models/spree/metafields/long_text.rb
+++ b/spree/core/app/models/spree/custom_fields/long_text.rb
@@ -1,6 +1,6 @@
module Spree
- module Metafields
- class LongText < Spree::Metafield
+ module CustomFields
+ class LongText < Spree::CustomField
normalizes :value, with: ->(value) { value.to_s.strip }
def self.searchable?
diff --git a/spree/core/app/models/spree/metafields/number.rb b/spree/core/app/models/spree/custom_fields/number.rb
similarity index 82%
rename from spree/core/app/models/spree/metafields/number.rb
rename to spree/core/app/models/spree/custom_fields/number.rb
index bd996a417b..c046146720 100644
--- a/spree/core/app/models/spree/metafields/number.rb
+++ b/spree/core/app/models/spree/custom_fields/number.rb
@@ -1,6 +1,6 @@
module Spree
- module Metafields
- class Number < Spree::Metafield
+ module CustomFields
+ class Number < Spree::CustomField
validates :value, numericality: true
def self.searchable?
diff --git a/spree/core/app/models/spree/custom_fields/rich_text.rb b/spree/core/app/models/spree/custom_fields/rich_text.rb
new file mode 100644
index 0000000000..5dff4d9d99
--- /dev/null
+++ b/spree/core/app/models/spree/custom_fields/rich_text.rb
@@ -0,0 +1,23 @@
+module Spree
+ module CustomFields
+ # Stores sanitized HTML in the shared `value` text column like every other
+ # custom field type. ActionText is gone in 6.0
+ # (docs/plans/6.0-rich-text-descriptions.md) — it round-tripped Tiptap
+ # markup through Trix's narrower allowlist, corrupting content on save.
+ class RichText < Spree::CustomField
+ include Spree::SanitizableRichText
+
+ sanitizes_rich_text :value
+
+ def serialize_value
+ value
+ end
+
+ def csv_value
+ return '' if value.blank?
+
+ Nokogiri::HTML.fragment(value).text
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/metafields/short_text.rb b/spree/core/app/models/spree/custom_fields/short_text.rb
similarity index 75%
rename from spree/core/app/models/spree/metafields/short_text.rb
rename to spree/core/app/models/spree/custom_fields/short_text.rb
index 0f941db062..e7bdd319f8 100644
--- a/spree/core/app/models/spree/metafields/short_text.rb
+++ b/spree/core/app/models/spree/custom_fields/short_text.rb
@@ -1,6 +1,6 @@
module Spree
- module Metafields
- class ShortText < Spree::Metafield
+ module CustomFields
+ class ShortText < Spree::CustomField
normalizes :value, with: ->(value) { value.to_s.strip }
def self.searchable?
diff --git a/spree/core/app/models/spree/delivery_method.rb b/spree/core/app/models/spree/delivery_method.rb
index 86a958c7d4..f6d67a4d72 100644
--- a/spree/core/app/models/spree/delivery_method.rb
+++ b/spree/core/app/models/spree/delivery_method.rb
@@ -5,7 +5,7 @@ module Spree
acts_as_paranoid
include Spree::SingleStoreResource
include Spree::CalculatedAdjustments
- include Spree::Metafields
+ include Spree::HasCustomFields
include Spree::Metadata
if defined?(Spree::VendorConcern)
include Spree::VendorConcern
diff --git a/spree/core/app/models/spree/exchange.rb b/spree/core/app/models/spree/exchange.rb
index 93e9744f5e..acb6a0e6a9 100644
--- a/spree/core/app/models/spree/exchange.rb
+++ b/spree/core/app/models/spree/exchange.rb
@@ -14,7 +14,7 @@ module Spree
include Spree::NumberIdentifier
include Spree::SingleStoreResource
include Spree::HasStatus
- include Spree::Metafields
+ include Spree::HasCustomFields
include Spree::Metadata
publishes_lifecycle_events
diff --git a/spree/core/app/models/spree/export.rb b/spree/core/app/models/spree/export.rb
index 450962e832..bb5114fd90 100644
--- a/spree/core/app/models/spree/export.rb
+++ b/spree/core/app/models/spree/export.rb
@@ -113,11 +113,11 @@ module Spree
raise NotImplementedError, 'csv_headers must be implemented'
end
- # Returns an array of metafield headers for the model
+ # Returns an array of custom_field headers for the model
#
# @return [Array<String>]
- def metafields_headers
- @metafields_headers ||= Spree::MetafieldDefinition.for_resource_type(model_class.to_s).order(:namespace, :key).map(&:csv_header_name)
+ def custom_fields_headers
+ @custom_fields_headers ||= Spree::CustomFieldDefinition.for_resource_type(model_class.to_s).order(:namespace, :key).map(&:csv_header_name)
end
def build_csv_line(_record)
@@ -148,8 +148,8 @@ module Spree
# `cf_*` custom-field predicates aren't Ransack attributes — resolve them
# first so an export of a filtered list matches what the admin sees.
- filtered_scope, params = if scope.respond_to?(:with_metafield_filters)
- scope.with_metafield_filters(params)
+ filtered_scope, params = if scope.respond_to?(:with_custom_field_filters)
+ scope.with_custom_field_filters(params)
else
[scope, params]
end
diff --git a/spree/core/app/models/spree/exports/customers.rb b/spree/core/app/models/spree/exports/customers.rb
index d55284701c..b025f39aaf 100644
--- a/spree/core/app/models/spree/exports/customers.rb
+++ b/spree/core/app/models/spree/exports/customers.rb
@@ -5,12 +5,12 @@ module Spree
[
{ bill_address: :state },
{ ship_address: :state },
- { metafields: :metafield_definition }
+ { custom_fields: :custom_field_definition }
]
end
def csv_headers
- Spree::CSV::CustomerPresenter::HEADERS + metafields_headers
+ Spree::CSV::CustomerPresenter::HEADERS + custom_fields_headers
end
end
end
diff --git a/spree/core/app/models/spree/exports/gift_cards.rb b/spree/core/app/models/spree/exports/gift_cards.rb
index f3f2283777..8eb843f77a 100644
--- a/spree/core/app/models/spree/exports/gift_cards.rb
+++ b/spree/core/app/models/spree/exports/gift_cards.rb
@@ -2,11 +2,11 @@ module Spree
module Exports
class GiftCards < Spree::Export
def scope_includes
- [:user, { metafields: :metafield_definition }]
+ [:user, { custom_fields: :custom_field_definition }]
end
def csv_headers
- Spree::CSV::GiftCardPresenter::HEADERS + metafields_headers
+ Spree::CSV::GiftCardPresenter::HEADERS + custom_fields_headers
end
end
end
diff --git a/spree/core/app/models/spree/exports/newsletter_subscribers.rb b/spree/core/app/models/spree/exports/newsletter_subscribers.rb
index 2a01154ac2..55fba9ff0c 100644
--- a/spree/core/app/models/spree/exports/newsletter_subscribers.rb
+++ b/spree/core/app/models/spree/exports/newsletter_subscribers.rb
@@ -6,11 +6,11 @@ module Spree
end
def scope_includes
- [:user, { metafields: :metafield_definition }]
+ [:user, { custom_fields: :custom_field_definition }]
end
def csv_headers
- Spree::CSV::NewsletterSubscriberPresenter::HEADERS + metafields_headers
+ Spree::CSV::NewsletterSubscriberPresenter::HEADERS + custom_fields_headers
end
end
end
diff --git a/spree/core/app/models/spree/exports/orders.rb b/spree/core/app/models/spree/exports/orders.rb
index d28998e481..d99e3dd3c1 100644
--- a/spree/core/app/models/spree/exports/orders.rb
+++ b/spree/core/app/models/spree/exports/orders.rb
@@ -9,7 +9,7 @@ module Spree
{ bill_address: [:state, :country] },
{ ship_address: [:state, :country] },
{ line_items: { variant: { product: [:categories] } } },
- { metafields: :metafield_definition }
+ { custom_fields: :custom_field_definition }
]
end
@@ -18,7 +18,7 @@ module Spree
end
def csv_headers
- Spree::CSV::OrderLineItemPresenter::HEADERS + metafields_headers
+ Spree::CSV::OrderLineItemPresenter::HEADERS + custom_fields_headers
end
end
end
diff --git a/spree/core/app/models/spree/exports/products.rb b/spree/core/app/models/spree/exports/products.rb
index 2269aee206..9687376a2e 100644
--- a/spree/core/app/models/spree/exports/products.rb
+++ b/spree/core/app/models/spree/exports/products.rb
@@ -4,7 +4,7 @@ module Spree
# to avoid N+1 queries
def scope_includes
includes = [:tax_category, :option_types, :categories, { variants: variant_includes }]
- includes << { metafields: :metafield_definition }
+ includes << { custom_fields: :custom_field_definition }
includes
end
@@ -27,7 +27,7 @@ module Spree
def csv_headers
headers = Spree::CSV::ProductVariantPresenter::CSV_HEADERS.dup
- headers += metafields_headers
+ headers += custom_fields_headers
@csv_headers ||= headers
end
end
diff --git a/spree/core/app/models/spree/fulfillment.rb b/spree/core/app/models/spree/fulfillment.rb
index 53b1d411dd..0ab1c94c8d 100644
--- a/spree/core/app/models/spree/fulfillment.rb
+++ b/spree/core/app/models/spree/fulfillment.rb
@@ -6,7 +6,7 @@ module Spree
include Spree::Core::NumberGenerator.new(prefix: 'F', length: 11)
include Spree::NumberIdentifier
- include Spree::Metafields
+ include Spree::HasCustomFields
include Spree::Metadata
if defined?(Spree::Security::Shipments)
include Spree::Security::Shipments
diff --git a/spree/core/app/models/spree/gift_card.rb b/spree/core/app/models/spree/gift_card.rb
index 6ece607b93..abc619ac57 100644
--- a/spree/core/app/models/spree/gift_card.rb
+++ b/spree/core/app/models/spree/gift_card.rb
@@ -4,7 +4,7 @@ module Spree
extend DisplayMoney
include Spree::SingleStoreResource
- include Spree::Metafields
+ include Spree::HasCustomFields
include Spree::Security::GiftCards if defined?(Spree::Security::GiftCards)
publishes_lifecycle_events
diff --git a/spree/core/app/models/spree/import.rb b/spree/core/app/models/spree/import.rb
index 1327f62781..7de607691a 100644
--- a/spree/core/app/models/spree/import.rb
+++ b/spree/core/app/models/spree/import.rb
@@ -256,20 +256,20 @@ module Spree
end
# Returns the fields for the import schema
- # If model supports metafields, it will include the metafield definitions for this model
+ # If model supports custom_fields, it will include the custom_field definitions for this model
# @return [Array<Hash>]
def schema_fields
base_fields = import_schema.fields
- # Dynamically add metafield definitions if the model supports metafields
- if model_class_supports_metafields?
- metafield_fields = metafield_definitions_for_model.map do |definition|
+ # Dynamically add custom_field definitions if the model supports custom_fields
+ if model_class_supports_custom_fields?
+ custom_field_fields = custom_field_definitions_for_model.map do |definition|
{
name: definition.csv_header_name,
- label: definition.name
+ label: definition.label
}
end
- base_fields + metafield_fields
+ base_fields + custom_field_fields
else
base_fields
end
@@ -385,7 +385,7 @@ module Spree
# Per-instance cache shared by row processors within a single processing job.
# Group jobs funnel every row through the same Import instance, so lookups of
- # shared records (tax/shipping categories, option types, metafield definitions)
+ # shared records (tax/shipping categories, option types, custom_field definitions)
# resolve once per job instead of once per row.
# @return [Hash]
def row_lookup_cache
@@ -486,16 +486,16 @@ module Spree
errors.add(:attachment, :content_type) unless attachment.content_type.in?(%w[text/csv])
end
- def model_class_supports_metafields?
+ def model_class_supports_custom_fields?
return false unless model_class.present?
- model_class.included_modules.include?(Spree::Metafields)
+ model_class.included_modules.include?(Spree::HasCustomFields)
end
- def metafield_definitions_for_model
+ def custom_field_definitions_for_model
return [] unless model_class.present?
- Spree::MetafieldDefinition.for_resource_type(model_class.name)
+ Spree::CustomFieldDefinition.for_resource_type(model_class.name)
end
end
end
diff --git a/spree/core/app/models/spree/line_item.rb b/spree/core/app/models/spree/line_item.rb
index 8d401bfee0..8268df6f34 100644
--- a/spree/core/app/models/spree/line_item.rb
+++ b/spree/core/app/models/spree/line_item.rb
@@ -2,7 +2,7 @@ module Spree
class LineItem < Spree.base_class
has_prefix_id :li # Spree-specific: line item
- include Spree::Metafields
+ include Spree::HasCustomFields
include Spree::Metadata
publishes_lifecycle_events
diff --git a/spree/core/app/models/spree/metafield.rb b/spree/core/app/models/spree/metafield.rb
index 970591f865..212b55dbab 100644
--- a/spree/core/app/models/spree/metafield.rb
+++ b/spree/core/app/models/spree/metafield.rb
@@ -1,104 +1,16 @@
-module Spree
- class Metafield < Spree.base_class
- # Map of API-facing tokens to Ruby STI class names. The wire format is the
- # token (`short_text`); the database column stores the class name. Reads
- # translate to the token via `field_type`; writes accept either form.
- # Plugin-defined types fall through to the raw class name until 6.0 when a
- # registration API lands.
- TYPE_TOKENS = {
- 'short_text' => 'Spree::Metafields::ShortText',
- 'long_text' => 'Spree::Metafields::LongText',
- 'rich_text' => 'Spree::Metafields::RichText',
- 'number' => 'Spree::Metafields::Number',
- 'boolean' => 'Spree::Metafields::Boolean',
- 'json' => 'Spree::Metafields::Json'
- }.freeze
- TYPE_CLASS_TO_TOKEN = TYPE_TOKENS.invert.freeze
-
- # Array form consumed by serializers via
- # `typelize field_type: Spree::Metafield::FIELD_TYPE_TOKENS`. Typelizer
- # emits a string-literal union in TypeScript and `{type: string, enum: […]}`
- # in OpenAPI (string-array form was added in typelizer 0.10.0).
- FIELD_TYPE_TOKENS = TYPE_TOKENS.keys.freeze
-
- # Whether MetafieldDefinition may enable `searchable` / `sortable` for this
- # STI type. Used only by definition validations (not by SearchProvider
- # indexing). Defaults to false; subclasses override (e.g. ShortText).
- def self.searchable?
- false
- end
-
- def self.sortable?
- false
- end
-
- has_prefix_id :cf
-
- #
- # Associations
- #
- belongs_to :resource, polymorphic: true, touch: true
- belongs_to :metafield_definition, class_name: 'Spree::MetafieldDefinition'
-
- #
- # API naming bridge — internal column rename lands in 6.0
- #
- alias_attribute :custom_field_definition_id, :metafield_definition_id
-
- # API-facing form of the STI `type` column. Returns the token
- # (`short_text`) when the row's type is a registered built-in; falls
- # through to the raw class name for plugin types.
- #
- # `self[:type]` reads the raw column to bypass AR's STI reader (which
- # returns the resolved class constant, not a string).
- def field_type
- TYPE_CLASS_TO_TOKEN[self[:type]] || self[:type]
- end
-
- #
- # Delegations
- #
- delegate :key, :full_key, :name, :label, :display_on, to: :metafield_definition, allow_nil: true
-
- #
- # Callbacks
- #
- before_validation :set_type_from_metafield_definition, on: :create
+# frozen_string_literal: true
- #
- # Validations
- #
- validates :metafield_definition, :type, :resource, :value, presence: true
- validates :metafield_definition_id, uniqueness: { scope: [:resource_type, :resource_id] }
- validate :type_must_match_metafield_definition
-
- #
- # Scopes
- #
- scope :available_on_front_end, -> { joins(:metafield_definition).merge(Spree::MetafieldDefinition.available_on_front_end) }
- scope :available_on_back_end, -> { joins(:metafield_definition).merge(Spree::MetafieldDefinition.available_on_back_end) }
- scope :with_key, ->(namespace, key) { joins(:metafield_definition).where(spree_metafield_definitions: { namespace: namespace, key: key }) }
-
- def serialize_value
- value
- end
-
- def csv_value
- value.to_s
- end
-
- private
-
- def set_type_from_metafield_definition
- return if metafield_definition.blank?
-
- self.type ||= metafield_definition.metafield_type
- end
-
- def type_must_match_metafield_definition
- return if metafield_definition.blank?
-
- errors.add(:type, 'must match metafield definition') unless type == metafield_definition.metafield_type
- end
- end
+module Spree
+ # Deprecation alias for Spree::CustomField, renamed from Spree::Metafield in
+ # 6.0. Retained for one release; removed in 6.1.
+ #
+ # A plain constant alias rather than a DeprecatedConstantProxy: the proxy
+ # would warn on first reference and name the calling site, but it fails
+ # `is_a?`/`===` checks, so legacy code branching on the old constant would
+ # silently take the wrong path. Correct behavior beats a better warning —
+ # the rename is documented in the 5.6-to-6.0 upgrade guide instead.
+ #
+ # The underlying class, table (spree_custom_fields), prefix (cf) and
+ # model_name are all Spree::CustomField; only the constant differs.
+ Metafield = CustomField
end
diff --git a/spree/core/app/models/spree/metafield_definition.rb b/spree/core/app/models/spree/metafield_definition.rb
index 111925263c..29db0e3a29 100644
--- a/spree/core/app/models/spree/metafield_definition.rb
+++ b/spree/core/app/models/spree/metafield_definition.rb
@@ -1,130 +1,13 @@
-module Spree
- class MetafieldDefinition < Spree.base_class
- has_prefix_id :cfdef
-
- include Spree::DisplayOn
- include Spree::MetafieldDefinition::SearchCapabilities
-
- DISPLAY = [:both, :back_end]
-
- #
- # Associations
- #
- has_many :metafields, class_name: 'Spree::Metafield', dependent: :destroy
-
- #
- # Validations
- #
- validates :namespace, :key, :name, :resource_type, presence: true
- validates :metafield_type, presence: true, inclusion: { in: :valid_available_types }
- validates :resource_type, presence: true, inclusion: { in: :valid_available_resources }
- validates :key, uniqueness: { scope: spree_base_uniqueness_scope + [:resource_type, :namespace] }
- validate :field_type_input_must_be_recognized
-
- #
- # Scopes
- #
- scope :for_resource_type, ->(resource_type) { where(resource_type: resource_type) }
- scope :search, ->(query) do
- return all if query.blank?
-
- search_term = "%#{query.downcase}%"
- namespace_condition = arel_table[:namespace].lower.matches(search_term)
- key_condition = arel_table[:key].lower.matches(search_term)
- name_condition = arel_table[:name].lower.matches(search_term)
-
- where(namespace_condition.or(key_condition).or(name_condition))
- end
-
- # Backward compatibility alias — remove in Spree 6.0
- scope :multi_search, ->(*args) { search(*args) }
-
- #
- # Callbacks
- #
- normalizes :key, with: ->(value) { value.to_s.parameterize.underscore.strip }
- normalizes :namespace, with: ->(value) { value.to_s.parameterize.underscore.strip }
- before_validation :set_default_type, if: -> { metafield_type.blank? }, on: :create
- before_validation :set_name_from_key, if: -> { name.blank? }, on: :create
-
- #
- # Ransack
- #
- self.whitelisted_ransackable_attributes = %w[key namespace name resource_type display_on searchable sortable]
- self.whitelisted_ransackable_scopes = %w[search multi_search]
-
- # API naming bridge — internal columns rename in 6.0. `label` matches
- # OptionType/OptionValue conventions. (`storefront_visible` lives on
- # the `Spree::DisplayOn` concern, shared with PaymentMethod; DeliveryMethod
- # already owns a real column — see docs/plans/5.5-6.0-display-on-to-boolean.md.)
- alias_attribute :label, :name
-
- # API-facing token for the STI subclass name stored in `metafield_type`.
- # Reader returns the registered token (`short_text`); writer accepts either
- # the token or the legacy class-name form for back-compat.
- def field_type
- Spree::Metafield::TYPE_CLASS_TO_TOKEN[metafield_type] || metafield_type
- end
+# frozen_string_literal: true
- def field_type=(value)
- v = value.to_s
- mapped = Spree::Metafield::TYPE_TOKENS[v]
- # An input is "recognized" when it's either a known token (mapped to a
- # class) or already a known class name. Anything else gets surfaced as
- # an error on `field_type` so API clients get a token-vocabulary
- # message instead of the raw class-name inclusion error on
- # `metafield_type`.
- @field_type_input_recognized = !mapped.nil? || Spree::Metafield::TYPE_CLASS_TO_TOKEN.key?(v)
- self.metafield_type = mapped || value
- end
-
- # Returns the full key with namespace
- # @return [String] eg. custom.id
- def full_key
- "#{namespace}.#{key}"
- end
-
- # Returns the CSV header name for this metafield
- # @return [String] eg. metafield.custom.id
- def csv_header_name
- "metafield.#{full_key}"
- end
-
- # Returns the available types
- # @return [Array<Class>]
- def self.available_types
- Spree.metafields.types
- end
-
- # Returns the available resources
- # @return [Array<Class>]
- def self.available_resources
- Spree.metafields.enabled_resources
- end
-
- private
-
- def valid_available_types
- self.class.available_types.map(&:to_s)
- end
-
- def field_type_input_must_be_recognized
- return if @field_type_input_recognized.nil? || @field_type_input_recognized
-
- tokens = Spree::Metafield::TYPE_TOKENS.keys.join(', ')
- errors.add(:field_type, "is not a known custom field type (expected one of: #{tokens})")
- end
-
- def valid_available_resources
- self.class.available_resources.map(&:to_s)
- end
-
- def set_default_type
- self.metafield_type ||= Spree.metafields.types.first.to_s
- end
-
- def set_name_from_key
- self.name ||= key.titleize
- end
- end
+module Spree
+ # Deprecation alias for Spree::CustomFieldDefinition, renamed from
+ # Spree::MetafieldDefinition in 6.0. Retained for one release; removed in 6.1.
+ # A plain constant alias for the same reason as {Spree::Metafield}.
+ #
+ # Note the columns renamed alongside the class: `name` is now `label`,
+ # `metafield_type` is now `field_type` (which reads back an API token such as
+ # `short_text` rather than the STI class name), and the tri-state `display_on`
+ # collapsed into the `storefront_visible` boolean.
+ MetafieldDefinition = CustomFieldDefinition
end
diff --git a/spree/core/app/models/spree/metafields.rb b/spree/core/app/models/spree/metafields.rb
new file mode 100644
index 0000000000..5bee3150af
--- /dev/null
+++ b/spree/core/app/models/spree/metafields.rb
@@ -0,0 +1,32 @@
+# frozen_string_literal: true
+
+module Spree
+ # Deprecation bridge for the 6.0 custom-fields rename. Serves the two roles
+ # the old `Spree::Metafields` name had, and is removed in 6.1:
+ #
+ # 1. The concern — `include Spree::Metafields` still works and gives a model
+ # the full custom-fields surface via {Spree::HasCustomFields}.
+ # 2. The STI namespace — `Spree::Metafields::ShortText` and friends are
+ # constant aliases for `Spree::CustomFields::*`. The `type` column stores
+ # the new class names, so these resolve to the very same classes and
+ # existing rows keep loading.
+ module Metafields
+ extend ActiveSupport::Concern
+
+ ShortText = CustomFields::ShortText
+ LongText = CustomFields::LongText
+ RichText = CustomFields::RichText
+ Number = CustomFields::Number
+ Boolean = CustomFields::Boolean
+ Json = CustomFields::Json
+
+ included do
+ Spree::Deprecation.warn(
+ "include Spree::Metafields is deprecated and will be removed in Spree 6.1. " \
+ "Use include Spree::HasCustomFields instead (#{name})."
+ )
+
+ include Spree::HasCustomFields
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/metafields/rich_text.rb b/spree/core/app/models/spree/metafields/rich_text.rb
deleted file mode 100644
index e08916054e..0000000000
--- a/spree/core/app/models/spree/metafields/rich_text.rb
+++ /dev/null
@@ -1,18 +0,0 @@
-module Spree
- module Metafields
- class RichText < Spree::Metafield
- # Avoid collision with the `value` column used by other metafield types
- self.ignored_columns = %w[value]
-
- has_rich_text :value
-
- def serialize_value
- value&.body&.to_s
- end
-
- def csv_value
- value&.body&.to_plain_text || ''
- end
- end
- end
-end
diff --git a/spree/core/app/models/spree/newsletter_subscriber.rb b/spree/core/app/models/spree/newsletter_subscriber.rb
index 10ac703bd2..9f6806fe13 100644
--- a/spree/core/app/models/spree/newsletter_subscriber.rb
+++ b/spree/core/app/models/spree/newsletter_subscriber.rb
@@ -2,7 +2,7 @@ module Spree
class NewsletterSubscriber < Spree.base_class
has_prefix_id :sub
- include Spree::Metafields
+ include Spree::HasCustomFields
include Spree::SingleStoreResource
publishes_lifecycle_events
diff --git a/spree/core/app/models/spree/option_type.rb b/spree/core/app/models/spree/option_type.rb
index 642aca1af1..4acd575e15 100644
--- a/spree/core/app/models/spree/option_type.rb
+++ b/spree/core/app/models/spree/option_type.rb
@@ -7,7 +7,7 @@ module Spree
include Spree::ParameterizableName
include Spree::UniqueName
- include Spree::Metafields
+ include Spree::HasCustomFields
include Spree::Metadata
# presentation column, exposed publicly as `label` + translated via Mobility.
include Spree::PresentationTranslatable
diff --git a/spree/core/app/models/spree/option_value.rb b/spree/core/app/models/spree/option_value.rb
index 019cb7bf96..9f7f3cb95b 100644
--- a/spree/core/app/models/spree/option_value.rb
+++ b/spree/core/app/models/spree/option_value.rb
@@ -3,7 +3,7 @@ module Spree
has_prefix_id :optval # Spree-specific: option value
include Spree::ParameterizableName
- include Spree::Metafields
+ include Spree::HasCustomFields
include Spree::Metadata
# presentation column, exposed publicly as `label` + translated via Mobility.
include Spree::PresentationTranslatable
diff --git a/spree/core/app/models/spree/order.rb b/spree/core/app/models/spree/order.rb
index 2d98d61da4..0a0ccb698e 100644
--- a/spree/core/app/models/spree/order.rb
+++ b/spree/core/app/models/spree/order.rb
@@ -39,7 +39,7 @@ module Spree
publishes_lifecycle_events
include Spree::MemoizedData
- include Spree::Metafields
+ include Spree::HasCustomFields
include Spree::Metadata
include Spree::Searchable
if defined?(Spree::Security::Orders)
@@ -972,13 +972,13 @@ module Spree
end
def to_csv(_store = nil)
- metafields_for_csv ||= Spree::MetafieldDefinition.for_resource_type('Spree::Order').order(:namespace, :key).map do |mf_def|
- metafields.find { |mf| mf.metafield_definition_id == mf_def.id }&.csv_value
+ custom_fields_for_csv ||= Spree::CustomFieldDefinition.for_resource_type('Spree::Order').order(:namespace, :key).map do |mf_def|
+ custom_fields.find { |mf| mf.custom_field_definition_id == mf_def.id }&.csv_value
end
csv_lines = []
line_items.each_with_index do |line_item, index|
- csv_lines << Spree::CSV::OrderLineItemPresenter.new(self, line_item, index, metafields_for_csv).call
+ csv_lines << Spree::CSV::OrderLineItemPresenter.new(self, line_item, index, custom_fields_for_csv).call
end
csv_lines
end
diff --git a/spree/core/app/models/spree/payment.rb b/spree/core/app/models/spree/payment.rb
index 2d4c2b30a6..70a72ae50a 100644
--- a/spree/core/app/models/spree/payment.rb
+++ b/spree/core/app/models/spree/payment.rb
@@ -6,7 +6,7 @@ module Spree
include Spree::Core::NumberGenerator.new(prefix: 'P', letters: true, length: 7)
include Spree::NumberIdentifier
- include Spree::Metafields
+ include Spree::HasCustomFields
include Spree::Metadata
if defined?(Spree::Security::Payments)
include Spree::Security::Payments
@@ -257,19 +257,19 @@ module Spree
end
def add_gateway_processing_error(error_message)
- if has_metafield?('gateway.processing_errors')
- errors = JSON.parse(get_metafield('gateway.processing_errors').value)
+ if has_custom_field?('gateway.processing_errors')
+ errors = JSON.parse(get_custom_field('gateway.processing_errors').value)
errors << { message: error_message }
- set_metafield('gateway.processing_errors', errors.to_json)
+ set_custom_field('gateway.processing_errors', errors.to_json)
else
- set_metafield('gateway.processing_errors', [{ message: error_message }].to_json)
+ set_custom_field('gateway.processing_errors', [{ message: error_message }].to_json)
end
end
def gateway_processing_error_messages
@gateway_processing_error_messages ||= begin
- errors = JSON.parse(get_metafield('gateway.processing_errors')&.value || '[]')
+ errors = JSON.parse(get_custom_field('gateway.processing_errors')&.value || '[]')
errors.map { |error| error['message'] }
rescue JSON::ParserError
[]
diff --git a/spree/core/app/models/spree/payment_method.rb b/spree/core/app/models/spree/payment_method.rb
index d564b7b7b6..10b7d5ad0c 100644
--- a/spree/core/app/models/spree/payment_method.rb
+++ b/spree/core/app/models/spree/payment_method.rb
@@ -6,7 +6,7 @@ module Spree
acts_as_list
include Spree::SingleStoreResource
- include Spree::Metafields
+ include Spree::HasCustomFields
include Spree::Metadata
include Spree::DisplayOn
if defined?(Spree::Security::PaymentMethods)
diff --git a/spree/core/app/models/spree/payment_session.rb b/spree/core/app/models/spree/payment_session.rb
index 9284400852..1525486ced 100644
--- a/spree/core/app/models/spree/payment_session.rb
+++ b/spree/core/app/models/spree/payment_session.rb
@@ -4,7 +4,7 @@ module Spree
acts_as_paranoid
- include Spree::Metafields
+ include Spree::HasCustomFields
self.event_prefix = 'payment_session'
diff --git a/spree/core/app/models/spree/payment_setup_session.rb b/spree/core/app/models/spree/payment_setup_session.rb
index 33ac8de864..0efa34d4b2 100644
--- a/spree/core/app/models/spree/payment_setup_session.rb
+++ b/spree/core/app/models/spree/payment_setup_session.rb
@@ -4,7 +4,7 @@ module Spree
acts_as_paranoid
- include Spree::Metafields
+ include Spree::HasCustomFields
self.event_prefix = 'payment_setup_session'
diff --git a/spree/core/app/models/spree/payment_source.rb b/spree/core/app/models/spree/payment_source.rb
index 4e468e5a9b..3b0499a28e 100644
--- a/spree/core/app/models/spree/payment_source.rb
+++ b/spree/core/app/models/spree/payment_source.rb
@@ -3,7 +3,7 @@ module Spree
class PaymentSource < Spree.base_class
has_prefix_id :ps
- include Spree::Metafields
+ include Spree::HasCustomFields
include Spree::Metadata
include Spree::PaymentSourceConcern
diff --git a/spree/core/app/models/spree/product.rb b/spree/core/app/models/spree/product.rb
index 42a78435b7..00a1bebb8c 100644
--- a/spree/core/app/models/spree/product.rb
+++ b/spree/core/app/models/spree/product.rb
@@ -25,8 +25,8 @@ module Spree
include Spree::TranslatableResource
include Spree::MemoizedData
include Spree::SanitizableRichText
- include Spree::Metafields
- include Spree::MetafieldFilterable
+ include Spree::HasCustomFields
+ include Spree::CustomFieldFilterable
include Spree::Metadata
include Spree::Searchable
include Spree::Product::Slugs
@@ -210,22 +210,22 @@ module Spree
product_ids = Spree::Variant.search_by_product_name_or_sku(query).pluck(:product_id)
- searchable_definitions = Spree::MetafieldDefinition.
+ searchable_definitions = Spree::CustomFieldDefinition.
for_resource_type('Spree::Product').
searchable
- # Only pay for the metafield scan when some definition opts into search;
- # the leading-wildcard LIKE over spree_metafields can't use an index.
- metafield_ids = if searchable_definitions.exists?
- joins(metafields: :metafield_definition).
+ # Only pay for the custom_field scan when some definition opts into search;
+ # the leading-wildcard LIKE over spree_custom_fields can't use an index.
+ custom_field_ids = if searchable_definitions.exists?
+ joins(custom_fields: :custom_field_definition).
merge(searchable_definitions).
- where(search_condition(Spree::Metafield, :value, query)).
+ where(search_condition(Spree::CustomField, :value, query)).
unscope(:order).distinct.pluck(:id)
else
[]
end
- where(id: (product_ids + metafield_ids).uniq.compact)
+ where(id: (product_ids + custom_field_ids).uniq.compact)
}
# Backward compatibility alias — remove in Spree 6.0
@@ -677,8 +677,8 @@ module Spree
else
[]
end
- metafields_for_csv ||= Spree::MetafieldDefinition.for_resource_type('Spree::Product').order(:namespace, :key).map do |mf_def|
- metafields.find { |mf| mf.metafield_definition_id == mf_def.id }&.csv_value
+ custom_fields_for_csv ||= Spree::CustomFieldDefinition.for_resource_type('Spree::Product').order(:namespace, :key).map do |mf_def|
+ custom_fields.find { |mf| mf.custom_field_definition_id == mf_def.id }&.csv_value
end
categories_for_csv ||= categories.reorder(depth: :desc).first(3).pluck(:pretty_name)
categories_for_csv.fill(nil, categories_for_csv.size...3)
@@ -691,7 +691,7 @@ module Spree
# Primary rows in the store's default currency
all_variants.each_with_index do |variant, index|
csv_lines << Spree::CSV::ProductVariantPresenter.new(self, variant, index, properties_for_csv, categories_for_csv, store,
- metafields_for_csv).call
+ custom_fields_for_csv).call
end
# Price-only rows for each additional currency
diff --git a/spree/core/app/models/spree/product_type.rb b/spree/core/app/models/spree/product_type.rb
index 000a8a98fe..2b742993b0 100644
--- a/spree/core/app/models/spree/product_type.rb
+++ b/spree/core/app/models/spree/product_type.rb
@@ -2,6 +2,7 @@ module Spree
class ProductType < Spree.base_class
has_prefix_id :pt
+ include Spree::HasCustomFields
include Spree::Metadata
include Spree::TranslatableResource
include Spree::SingleStoreResource
@@ -22,7 +23,7 @@ module Spree
has_many :product_type_custom_field_definitions, -> { ordered },
class_name: 'Spree::ProductTypeCustomFieldDefinition', dependent: :destroy, inverse_of: :product_type
has_many :custom_field_definitions, through: :product_type_custom_field_definitions,
- class_name: 'Spree::MetafieldDefinition'
+ class_name: 'Spree::CustomFieldDefinition'
# restrict, not nullify — removing a product's type (deletion included) would
# invalidate its type-driven data, so types in use cannot be deleted
@@ -46,7 +47,7 @@ module Spree
# @param rows [Array<Hash>, nil]
# @return [void]
def custom_field_definitions=(rows)
- return super if rows.blank? || rows.first.is_a?(Spree::MetafieldDefinition)
+ return super if rows.blank? || rows.first.is_a?(Spree::CustomFieldDefinition)
@pending_custom_field_definitions = Array(rows).map { |row| row.to_h.with_indifferent_access }
end
@@ -82,7 +83,7 @@ module Spree
@pending_custom_field_definitions = nil
resolved = rows.map do |row|
- [Spree::MetafieldDefinition.find_by_prefix_id(row[:id]), row]
+ [Spree::CustomFieldDefinition.find_by_prefix_id(row[:id]), row]
end
# Validate the whole payload before touching anything. This runs inside
diff --git a/spree/core/app/models/spree/product_type_custom_field_definition.rb b/spree/core/app/models/spree/product_type_custom_field_definition.rb
index 1d8324dfc1..88960cec8a 100644
--- a/spree/core/app/models/spree/product_type_custom_field_definition.rb
+++ b/spree/core/app/models/spree/product_type_custom_field_definition.rb
@@ -7,8 +7,8 @@ module Spree
class ProductTypeCustomFieldDefinition < Spree.base_class
belongs_to :product_type, class_name: 'Spree::ProductType'
# Association and column carry the 6.0 custom-field vocabulary; the class is
- # still named MetafieldDefinition until the rename wave lands.
- belongs_to :custom_field_definition, class_name: 'Spree::MetafieldDefinition'
+ # still named CustomFieldDefinition until the rename wave lands.
+ belongs_to :custom_field_definition, class_name: 'Spree::CustomFieldDefinition'
validates :product_type, :custom_field_definition, presence: true
validates :custom_field_definition_id, uniqueness: { scope: :product_type_id }
diff --git a/spree/core/app/models/spree/promotion.rb b/spree/core/app/models/spree/promotion.rb
index 3c1de02ca9..9e00e0a8b2 100644
--- a/spree/core/app/models/spree/promotion.rb
+++ b/spree/core/app/models/spree/promotion.rb
@@ -3,7 +3,7 @@ module Spree
has_prefix_id :promo # Spree-specific: promotion
include Spree::SingleStoreResource
- include Spree::Metafields
+ include Spree::HasCustomFields
include Spree::Metadata
if defined?(Spree::Security::Promotions)
include Spree::Security::Promotions
diff --git a/spree/core/app/models/spree/refund.rb b/spree/core/app/models/spree/refund.rb
index 6b5751ce0d..eb4af7eed8 100644
--- a/spree/core/app/models/spree/refund.rb
+++ b/spree/core/app/models/spree/refund.rb
@@ -2,7 +2,7 @@ module Spree
class Refund < Spree.base_class
has_prefix_id :re # Stripe: re_
- include Spree::Metafields
+ include Spree::HasCustomFields
include Spree::Metadata
if defined?(Spree::Security::Refunds)
include Spree::Security::Refunds
diff --git a/spree/core/app/models/spree/return.rb b/spree/core/app/models/spree/return.rb
index ec12376069..7bffc02c77 100644
--- a/spree/core/app/models/spree/return.rb
+++ b/spree/core/app/models/spree/return.rb
@@ -17,7 +17,7 @@ module Spree
include Spree::NumberIdentifier
include Spree::SingleStoreResource
include Spree::HasStatus
- include Spree::Metafields
+ include Spree::HasCustomFields
include Spree::Metadata
publishes_lifecycle_events
diff --git a/spree/core/app/models/spree/search_provider/base.rb b/spree/core/app/models/spree/search_provider/base.rb
index 6b7a10d96d..b8c188e689 100644
--- a/spree/core/app/models/spree/search_provider/base.rb
+++ b/spree/core/app/models/spree/search_provider/base.rb
@@ -13,9 +13,15 @@ module Spree
@store = store
end
- # @return [MetafieldSchema]
+ # @return [CustomFieldSchema]
+ def custom_field_schema
+ @custom_field_schema ||= CustomFieldSchema.new
+ end
+
+ # Deprecated 6.0 name, removed in 6.1.
def metafield_schema
- @metafield_schema ||= MetafieldSchema.new
+ Spree::Deprecation.warn('#metafield_schema is deprecated and will be removed in Spree 6.1. Use #custom_field_schema instead.')
+ custom_field_schema
end
# Search and paginate products. Does NOT compute filter facets — use #filters for that.
diff --git a/spree/core/app/models/spree/search_provider/database.rb b/spree/core/app/models/spree/search_provider/database.rb
index 94657dc42c..fffac3a8db 100644
--- a/spree/core/app/models/spree/search_provider/database.rb
+++ b/spree/core/app/models/spree/search_provider/database.rb
@@ -52,7 +52,7 @@ module Spree
end
filter_facets = build_facets(scope_with_options, category: category, sort_order: collection&.sort_order, option_value_ids: option_value_ids, scope_before_options: scope_before_options)
- filter_facets[:sort_options] = filter_facets[:sort_options] + metafield_sort_options
+ filter_facets[:sort_options] = filter_facets[:sort_options] + custom_field_sort_options
FiltersResult.new(
filters: filter_facets[:filters],
@@ -68,7 +68,7 @@ module Spree
scope = scope.search(query) if query.present?
filters = filters.to_unsafe_h if filters.respond_to?(:to_unsafe_h)
- scope, filters = scope.with_metafield_filters(filters, schema: metafield_schema)
+ scope, filters = scope.with_custom_field_filters(filters, schema: custom_field_schema)
ransack_filters = sanitize_filters(filters)
if ransack_filters.present?
@@ -115,8 +115,8 @@ module Spree
scope_method = CUSTOM_SORT_SCOPES[sort]
if scope_method
scope.reorder(nil).send(scope_method)
- elsif (parsed = metafield_schema.parse_sort(sort))
- apply_metafield_sort(scope, parsed)
+ elsif (parsed = custom_field_schema.parse_sort(sort))
+ apply_custom_field_sort(scope, parsed)
else
# Standard Ransack sort: 'name' → 'name asc', '-name' → 'name desc'
ransack_sort = sort.split(',').map { |field|
@@ -171,29 +171,29 @@ module Spree
# Project the ORDER BY expression into the SELECT list so PostgreSQL
# accepts it when DISTINCT is applied. Null-rank keeps products without
- # the metafield last for both ASC and DESC.
- def apply_metafield_sort(scope, parsed)
- definition = metafield_schema.entry_for(parsed[:attribute])
+ # the custom_field last for both ASC and DESC.
+ def apply_custom_field_sort(scope, parsed)
+ definition = custom_field_schema.entry_for(parsed[:attribute])
return scope unless definition
products = Spree::Product.arel_table
# Aliased so this join can't collide with the `filter_cf` correlated
# subquery when a cf_* filter and a cf_* sort are combined.
- metafields = Spree::Metafield.arel_table.alias('sort_cf')
+ custom_fields = Spree::CustomField.arel_table.alias('sort_cf')
- sort_expr = Spree::Product.metafield_value_expression(metafields[:value], definition.field_type)
- # NULL-rank so products missing the metafield sort last (Meilisearch parity).
+ sort_expr = Spree::Product.custom_field_value_expression(custom_fields[:value], definition.field_type)
+ # NULL-rank so products missing the custom_field sort last (Meilisearch parity).
# Projected as cf_sort_missing because PostgreSQL rejects (alias IS NULL) in ORDER BY.
null_rank = sort_expr.eq(nil)
direction = parsed[:direction] == 'desc' ? :desc : :asc
join = products.
- outer_join(metafields).
+ outer_join(custom_fields).
on(
- metafields[:resource_type].eq('Spree::Product').
- and(metafields[:resource_id].eq(products[:id])).
- and(metafields[:metafield_definition_id].eq(definition.id))
+ custom_fields[:resource_type].eq('Spree::Product').
+ and(custom_fields[:resource_id].eq(products[:id])).
+ and(custom_fields[:custom_field_definition_id].eq(definition.id))
).
join_sources
@@ -209,8 +209,8 @@ module Spree
%w[price -price best_selling name -name -available_on available_on].map { |id| { id: id, label: nil } }
end
- def metafield_sort_options
- metafield_schema.sort_options
+ def custom_field_sort_options
+ custom_field_schema.sort_options
end
end
end
diff --git a/spree/core/app/models/spree/search_provider/meilisearch.rb b/spree/core/app/models/spree/search_provider/meilisearch.rb
index 6e6407a864..625e02f79f 100644
--- a/spree/core/app/models/spree/search_provider/meilisearch.rb
+++ b/spree/core/app/models/spree/search_provider/meilisearch.rb
@@ -6,7 +6,7 @@ module Spree
PREFIXED_ID_PATTERN = /\A[a-z]+_[A-Za-z0-9]+\z/
ALLOWED_STATUSES = %w[active draft archived paused].freeze
BUILT_IN_FILTERABLE_ATTRIBUTES = %w[product_id status in_stock preorder store_ids channel_ids locale currency available_on discontinue_on price category_ids collection_ids grouping_id tags option_value_ids].freeze
- METAFIELD_RANGE_OPERATORS = { 'gt' => '>', 'gteq' => '>=', 'lt' => '<', 'lteq' => '<=' }.freeze
+ CUSTOM_FIELD_RANGE_OPERATORS = { 'gt' => '>', 'gteq' => '>=', 'lt' => '<', 'lteq' => '<=' }.freeze
def self.indexing_required?
true
@@ -59,7 +59,7 @@ module Spree
unless ms_result
return FiltersResult.new(
filters: [],
- sort_options: built_in_and_metafield_sort_options,
+ sort_options: built_in_and_custom_field_sort_options,
default_sort: default_sort,
total_count: 0
)
@@ -67,7 +67,7 @@ module Spree
FiltersResult.new(
filters: build_facet_response(facet_distribution),
- sort_options: built_in_and_metafield_sort_options,
+ sort_options: built_in_and_custom_field_sort_options,
default_sort: default_sort,
total_count: ms_result['totalHits'] || 0
)
@@ -103,7 +103,7 @@ module Spree
def reindex(scope = nil)
full_reindex = scope.nil?
scope ||= store.products
- @metafield_schema = MetafieldSchema.new
+ @custom_field_schema = CustomFieldSchema.new
ensure_index_settings!
# On a full reindex, clear first so stale docs (e.g. membership docs for
@@ -288,15 +288,15 @@ module Spree
end
def searchable_attributes
- %w[name description sku option_values category_names tags] + metafield_schema.searchable_attribute_keys
+ %w[name description sku option_values category_names tags] + custom_field_schema.searchable_attribute_keys
end
def filterable_attributes
- BUILT_IN_FILTERABLE_ATTRIBUTES + metafield_schema.filterable_attribute_keys
+ BUILT_IN_FILTERABLE_ATTRIBUTES + custom_field_schema.filterable_attribute_keys
end
def sortable_attributes
- %w[name price created_at available_on units_sold_count position] + metafield_schema.sortable_attribute_keys
+ %w[name price created_at available_on units_sold_count position] + custom_field_schema.sortable_attribute_keys
end
# Facets stay built-in only — cf_* distributions aren't consumed by
@@ -315,7 +315,7 @@ module Spree
# Sourced from Spree::Collection::SORT_ORDERS (matching FiltersAggregator) so
# both providers advertise identical options — including 'manual'.
def available_sort_options
- Spree::Collection::SORT_ORDERS.map { |sort_order| to_api_sort(sort_order) } + metafield_schema.sort_ids
+ Spree::Collection::SORT_ORDERS.map { |sort_order| to_api_sort(sort_order) } + custom_field_schema.sort_ids
end
# Converts internal sort format ('price asc') to API format ('price', '-price').
@@ -326,9 +326,9 @@ module Spree
direction == 'desc' ? "-#{field}" : field
end
- def built_in_and_metafield_sort_options
+ def built_in_and_custom_field_sort_options
Spree::Collection::SORT_ORDERS.map { |sort_order| { id: to_api_sort(sort_order), label: nil } } +
- metafield_schema.sort_options
+ custom_field_schema.sort_options
end
# Build Meilisearch filter conditions from API params.
@@ -408,7 +408,7 @@ module Spree
# Handled by grouped option conditions in search_and_filter — skip here
nil
else
- metafield_filter_condition(key, value)
+ custom_field_filter_condition(key, value)
end
end
@@ -416,8 +416,8 @@ module Spree
# EXISTS — but no string contains/starts/ends (CONTAINS is still
# experimental), so those predicates are ignored here. The Database
# provider supports the full predicate set.
- def metafield_filter_condition(key, value)
- parsed = metafield_schema.parse_filter(key)
+ def custom_field_filter_condition(key, value)
+ parsed = custom_field_schema.parse_filter(key)
return nil unless parsed
attribute = parsed[:definition].filter_key
@@ -430,17 +430,17 @@ module Spree
"#{attribute} NOT EXISTS"
when 'eq', 'not_eq'
operator = parsed[:predicate] == 'eq' ? '=' : '!='
- formatted = format_metafield_filter_value(value, numeric)
+ formatted = format_custom_field_filter_value(value, numeric)
formatted && "#{attribute} #{operator} #{formatted}"
- when *METAFIELD_RANGE_OPERATORS.keys
+ when *CUSTOM_FIELD_RANGE_OPERATORS.keys
return nil unless numeric
- formatted = format_metafield_filter_value(value, numeric)
- formatted && "#{attribute} #{METAFIELD_RANGE_OPERATORS[parsed[:predicate]]} #{formatted}"
+ formatted = format_custom_field_filter_value(value, numeric)
+ formatted && "#{attribute} #{CUSTOM_FIELD_RANGE_OPERATORS[parsed[:predicate]]} #{formatted}"
end
end
- def format_metafield_filter_value(value, numeric)
+ def format_custom_field_filter_value(value, numeric)
if numeric
Float(value.to_s, exception: false)&.to_s
else
@@ -500,7 +500,7 @@ module Spree
when 'available_on' then ['available_on:asc']
when 'best_selling' then ['units_sold_count:desc']
else
- parsed = metafield_schema.parse_sort(sort)
+ parsed = custom_field_schema.parse_sort(sort)
parsed && ["#{parsed[:attribute]}:#{parsed[:direction]}"]
end
end
diff --git a/spree/core/app/models/spree/stock_item.rb b/spree/core/app/models/spree/stock_item.rb
index 1c76bfb59e..5e38e7914e 100644
--- a/spree/core/app/models/spree/stock_item.rb
+++ b/spree/core/app/models/spree/stock_item.rb
@@ -4,7 +4,7 @@ module Spree
acts_as_paranoid
- include Spree::Metafields
+ include Spree::HasCustomFields
include Spree::Metadata
publishes_lifecycle_events
diff --git a/spree/core/app/models/spree/stock_transfer.rb b/spree/core/app/models/spree/stock_transfer.rb
index 05fd3fc1d3..e537ab5eec 100644
--- a/spree/core/app/models/spree/stock_transfer.rb
+++ b/spree/core/app/models/spree/stock_transfer.rb
@@ -4,7 +4,7 @@ module Spree
include Spree::Core::NumberGenerator.new(prefix: 'T')
include Spree::NumberIdentifier
- include Spree::Metafields
+ include Spree::HasCustomFields
include Spree::Metadata
publishes_lifecycle_events
diff --git a/spree/core/app/models/spree/store.rb b/spree/core/app/models/spree/store.rb
index 7d54655e7e..db2804a188 100644
--- a/spree/core/app/models/spree/store.rb
+++ b/spree/core/app/models/spree/store.rb
@@ -8,7 +8,7 @@ module Spree
include FriendlyId
include Spree::TranslatableResource
- include Spree::Metafields
+ include Spree::HasCustomFields
include Spree::Metadata
include Spree::Stores::Setup
include Spree::Stores::Markets
diff --git a/spree/core/app/models/spree/store_credit.rb b/spree/core/app/models/spree/store_credit.rb
index bcddf952f0..d082708d90 100644
--- a/spree/core/app/models/spree/store_credit.rb
+++ b/spree/core/app/models/spree/store_credit.rb
@@ -3,7 +3,7 @@ module Spree
has_prefix_id :credit
include Spree::SingleStoreResource
- include Spree::Metafields
+ include Spree::HasCustomFields
include Spree::Metadata
publishes_lifecycle_events
diff --git a/spree/core/app/models/spree/tax_rate.rb b/spree/core/app/models/spree/tax_rate.rb
index 3a8cb95400..2964ec62d3 100644
--- a/spree/core/app/models/spree/tax_rate.rb
+++ b/spree/core/app/models/spree/tax_rate.rb
@@ -7,7 +7,7 @@ module Spree
acts_as_paranoid
- include Spree::Metafields
+ include Spree::HasCustomFields
include Spree::Metadata
with_options inverse_of: :tax_rates do
diff --git a/spree/core/app/models/spree/variant.rb b/spree/core/app/models/spree/variant.rb
index 66b3910064..2d292e2626 100644
--- a/spree/core/app/models/spree/variant.rb
+++ b/spree/core/app/models/spree/variant.rb
@@ -6,7 +6,7 @@ module Spree
acts_as_list scope: :product
include Spree::MemoizedData
- include Spree::Metafields
+ include Spree::HasCustomFields
include Spree::Metadata
include Spree::Searchable
diff --git a/spree/core/app/presenters/spree/csv/custom_fields_helper.rb b/spree/core/app/presenters/spree/csv/custom_fields_helper.rb
new file mode 100644
index 0000000000..970f24faa2
--- /dev/null
+++ b/spree/core/app/presenters/spree/csv/custom_fields_helper.rb
@@ -0,0 +1,17 @@
+module Spree
+ module CSV
+ module CustomFieldsHelper
+ private
+
+ def custom_field_definitions_for_csv(resource)
+ Spree::CustomFieldDefinition.for_resource_type(resource.class.to_s).order(:namespace, :key)
+ end
+
+ def custom_fields_for_csv(resource)
+ Spree::CustomFieldDefinition.for_resource_type(resource.class.to_s).order(:namespace, :key).map do |mf_def|
+ resource.custom_fields.find { |mf| mf.custom_field_definition_id == mf_def.id }&.csv_value
+ end
+ end
+ end
+ end
+end
diff --git a/spree/core/app/presenters/spree/csv/customer_presenter.rb b/spree/core/app/presenters/spree/csv/customer_presenter.rb
index ff7900443d..1e8383e134 100644
--- a/spree/core/app/presenters/spree/csv/customer_presenter.rb
+++ b/spree/core/app/presenters/spree/csv/customer_presenter.rb
@@ -1,7 +1,7 @@
module Spree
module CSV
class CustomerPresenter
- include Spree::CSV::MetafieldsHelper
+ include Spree::CSV::CustomFieldsHelper
HEADERS = [
'First Name',
@@ -50,7 +50,7 @@ module Spree
customer.tag_list
]
- csv += metafields_for_csv(customer)
+ csv += custom_fields_for_csv(customer)
csv
end
diff --git a/spree/core/app/presenters/spree/csv/gift_card_presenter.rb b/spree/core/app/presenters/spree/csv/gift_card_presenter.rb
index 2617f97c9c..49cc0b3dbc 100644
--- a/spree/core/app/presenters/spree/csv/gift_card_presenter.rb
+++ b/spree/core/app/presenters/spree/csv/gift_card_presenter.rb
@@ -1,7 +1,7 @@
module Spree
module CSV
class GiftCardPresenter
- include Spree::CSV::MetafieldsHelper
+ include Spree::CSV::CustomFieldsHelper
HEADERS = [
'Code',
@@ -40,7 +40,7 @@ module Spree
gift_card.updated_at&.strftime('%Y-%m-%d %H:%M:%S')
]
- csv += metafields_for_csv(gift_card)
+ csv += custom_fields_for_csv(gift_card)
csv
end
diff --git a/spree/core/app/presenters/spree/csv/metafields_helper.rb b/spree/core/app/presenters/spree/csv/metafields_helper.rb
deleted file mode 100644
index 550f3d516a..0000000000
--- a/spree/core/app/presenters/spree/csv/metafields_helper.rb
+++ /dev/null
@@ -1,17 +0,0 @@
-module Spree
- module CSV
- module MetafieldsHelper
- private
-
- def metafield_definitions_for_csv(resource)
- Spree::MetafieldDefinition.for_resource_type(resource.class.to_s).order(:namespace, :key)
- end
-
- def metafields_for_csv(resource)
- Spree::MetafieldDefinition.for_resource_type(resource.class.to_s).order(:namespace, :key).map do |mf_def|
- resource.metafields.find { |mf| mf.metafield_definition_id == mf_def.id }&.csv_value
- end
- end
- end
- end
-end
diff --git a/spree/core/app/presenters/spree/csv/newsletter_subscriber_presenter.rb b/spree/core/app/presenters/spree/csv/newsletter_subscriber_presenter.rb
index 65dec2a2f5..56b754ac34 100644
--- a/spree/core/app/presenters/spree/csv/newsletter_subscriber_presenter.rb
+++ b/spree/core/app/presenters/spree/csv/newsletter_subscriber_presenter.rb
@@ -1,7 +1,7 @@
module Spree
module CSV
class NewsletterSubscriberPresenter
- include Spree::CSV::MetafieldsHelper
+ include Spree::CSV::CustomFieldsHelper
HEADERS = [
'Email',
@@ -30,7 +30,7 @@ module Spree
newsletter_subscriber.updated_at
]
- csv += metafields_for_csv(newsletter_subscriber)
+ csv += custom_fields_for_csv(newsletter_subscriber)
csv
end
diff --git a/spree/core/app/presenters/spree/csv/order_line_item_presenter.rb b/spree/core/app/presenters/spree/csv/order_line_item_presenter.rb
index 2cf4c4cd2c..04db28f855 100644
--- a/spree/core/app/presenters/spree/csv/order_line_item_presenter.rb
+++ b/spree/core/app/presenters/spree/csv/order_line_item_presenter.rb
@@ -59,14 +59,14 @@ module Spree
'Notes'
].freeze
- def initialize(order, line_item, index, metafields = [])
+ def initialize(order, line_item, index, custom_fields = [])
@order = order
@line_item = line_item
@index = index
- @metafields = metafields
+ @custom_fields = custom_fields
end
- attr_accessor :order, :line_item, :index, :metafields
+ attr_accessor :order, :line_item, :index, :custom_fields
def call
csv = [
@@ -128,7 +128,7 @@ module Spree
]
if index.zero?
- csv += metafields
+ csv += custom_fields
end
csv
diff --git a/spree/core/app/presenters/spree/csv/product_variant_presenter.rb b/spree/core/app/presenters/spree/csv/product_variant_presenter.rb
index af0bb706c6..25ba8d42f1 100644
--- a/spree/core/app/presenters/spree/csv/product_variant_presenter.rb
+++ b/spree/core/app/presenters/spree/csv/product_variant_presenter.rb
@@ -46,7 +46,7 @@ module Spree
'category3',
].freeze
- def initialize(product, variant, index = 0, properties = [], categories = [], store = nil, metafields = [], currency = nil)
+ def initialize(product, variant, index = 0, properties = [], categories = [], store = nil, custom_fields = [], currency = nil)
@product = product
@variant = variant
@index = index
@@ -55,10 +55,10 @@ module Spree
@store = store || product.store
@currency = currency || @store.default_currency
@price_only = @currency != @store.default_currency
- @metafields = metafields
+ @custom_fields = custom_fields
end
- attr_accessor :product, :variant, :index, :properties, :categories, :store, :currency, :price_only, :metafields
+ attr_accessor :product, :variant, :index, :properties, :categories, :store, :currency, :price_only, :custom_fields
##
# Generates an array representing a CSV row of product variant data.
@@ -119,7 +119,7 @@ module Spree
if index.zero?
csv += categories
csv += properties
- csv += metafields
+ csv += custom_fields
end
csv
diff --git a/spree/core/app/presenters/spree/data_feeds/google_presenter.rb b/spree/core/app/presenters/spree/data_feeds/google_presenter.rb
index 67bf3fa2db..ead6052ddd 100644
--- a/spree/core/app/presenters/spree/data_feeds/google_presenter.rb
+++ b/spree/core/app/presenters/spree/data_feeds/google_presenter.rb
@@ -4,7 +4,7 @@ module Spree
module DataFeeds
class GooglePresenter < BasePresenter
# Optional Google Merchant Center product attributes sourced from
- # metafields. See https://support.google.com/merchants/answer/7052112
+ # custom_fields. See https://support.google.com/merchants/answer/7052112
OPTIONAL_ATTRIBUTES = %w[
brand gtin mpn identifier_exists condition adult multipack is_bundle
age_group color gender material pattern size size_type size_system
@@ -42,7 +42,7 @@ module Spree
end
def build_items(xml)
- products.includes(:primary_media, public_metafields: :metafield_definition, variants: [:primary_media, option_values: :option_type]).find_each do |product|
+ products.includes(:primary_media, storefront_custom_fields: :custom_field_definition, variants: [:primary_media, option_values: :option_type]).find_each do |product|
product.variants.active(feed_currency).each do |variant|
build_item(xml, product, variant)
end
@@ -80,11 +80,11 @@ module Spree
end
def build_optional_attributes(xml, product)
- product.public_metafields.each do |metafield|
- key = metafield.metafield_definition.key.parameterize.underscore
+ product.storefront_custom_fields.each do |custom_field|
+ key = custom_field.custom_field_definition.key.parameterize.underscore
next unless OPTIONAL_ATTRIBUTES.include?(key)
- append_g_element(xml, key, metafield.value)
+ append_g_element(xml, key, custom_field.value)
end
end
diff --git a/spree/core/app/presenters/spree/search_provider/product_presenter.rb b/spree/core/app/presenters/spree/search_provider/product_presenter.rb
index 1e58af0a23..847602af8c 100644
--- a/spree/core/app/presenters/spree/search_provider/product_presenter.rb
+++ b/spree/core/app/presenters/spree/search_provider/product_presenter.rb
@@ -84,21 +84,21 @@ module Spree
available_on: product.available_on&.iso8601,
created_at: product.created_at&.iso8601,
updated_at: product.updated_at&.iso8601
- }.merge(metafield_document_attributes)
+ }.merge(custom_field_document_attributes)
end
- # Flat cf_* hash for searchable ∪ sortable metafields (Meilisearch docs).
- def metafield_document_attributes
- @metafield_document_attributes ||= product.metafields.filter_map do |metafield|
- definition = metafield.metafield_definition
+ # Flat cf_* hash for searchable ∪ sortable custom_fields (Meilisearch docs).
+ def custom_field_document_attributes
+ @custom_field_document_attributes ||= product.custom_fields.filter_map do |custom_field|
+ definition = custom_field.custom_field_definition
next unless definition&.searchable? || definition&.sortable?
- [definition.filter_key, metafield_index_value(metafield, definition.field_type)]
+ [definition.filter_key, custom_field_index_value(custom_field, definition.field_type)]
end.to_h
end
- def metafield_index_value(metafield, field_type)
- serialized = metafield.serialize_value
+ def custom_field_index_value(custom_field, field_type)
+ serialized = custom_field.serialize_value
case field_type
when 'number'
serialized.to_f
diff --git a/spree/core/app/services/spree/imports/row_processors/product_variant.rb b/spree/core/app/services/spree/imports/row_processors/product_variant.rb
index d69746e219..116f7a2123 100644
--- a/spree/core/app/services/spree/imports/row_processors/product_variant.rb
+++ b/spree/core/app/services/spree/imports/row_processors/product_variant.rb
@@ -90,7 +90,7 @@ module Spree
handle_tags(product) if attributes['tags'].present?
if has_product_attributes?
- handle_metafields(product)
+ handle_custom_fields(product)
handle_categories(product)
end
@@ -264,52 +264,52 @@ module Spree
%w[name status description category1 category2 category3].any? { |key| attributes[key].present? }
end
- def handle_metafields(product)
- return unless product.class.included_modules.include?(Spree::Metafields)
+ def handle_custom_fields(product)
+ return unless product.class.included_modules.include?(Spree::HasCustomFields)
- metafield_attributes = attributes.select { |key, _value| key.to_s.start_with?('metafield.') }
- return if metafield_attributes.empty?
+ custom_field_attributes = attributes.select { |key, _value| key.to_s.start_with?('custom_field.') }
+ return if custom_field_attributes.empty?
- # Build nested attributes for metafields
+ # Build nested attributes for custom_fields
nested_attrs = []
- metafield_attributes.each do |attribute_key, value|
- # Extract namespace.key from "metafield.namespace.key"
- full_key = attribute_key.to_s.sub(/^metafield\./, '')
+ custom_field_attributes.each do |attribute_key, value|
+ # Extract namespace.key from "custom_field.namespace.key"
+ full_key = attribute_key.to_s.sub(/^custom_field\./, '')
namespace, key = product.extract_namespace_and_key(full_key)
- # Find or initialize metafield definition
- metafield_definition = cached_lookup(:metafield_definition, namespace, key, product.class.name) do
- Spree::MetafieldDefinition.find_by(
+ # Find or initialize custom_field definition
+ custom_field_definition = cached_lookup(:custom_field_definition, namespace, key, product.class.name) do
+ Spree::CustomFieldDefinition.find_by(
namespace: namespace,
key: key,
resource_type: product.class.name
)
end
- next unless metafield_definition
+ next unless custom_field_definition
- # Find existing metafield if product is persisted
- existing_metafield = product.persisted? ? product.metafields.find_by(metafield_definition: metafield_definition) : nil
+ # Find existing custom_field if product is persisted
+ existing_custom_field = product.persisted? ? product.custom_fields.find_by(custom_field_definition: custom_field_definition) : nil
- # Skip blank values for new metafields
- next if value.blank? && existing_metafield.nil?
+ # Skip blank values for new custom_fields
+ next if value.blank? && existing_custom_field.nil?
- # For existing metafields with blank values, we'll mark them for destruction
- # For new metafields, we skip them (handled above)
- # For existing or new metafields with values, we create/update them
- metafield_attrs = {
- metafield_definition_id: metafield_definition.id,
+ # For existing custom_fields with blank values, we'll mark them for destruction
+ # For new custom_fields, we skip them (handled above)
+ # For existing or new custom_fields with values, we create/update them
+ custom_field_attrs = {
+ custom_field_definition_id: custom_field_definition.id,
value: value.to_s.strip,
- type: metafield_definition.metafield_type
+ type: custom_field_definition.field_type_class_name
}
- metafield_attrs[:id] = existing_metafield.id if existing_metafield
+ custom_field_attrs[:id] = existing_custom_field.id if existing_custom_field
- nested_attrs << metafield_attrs
+ nested_attrs << custom_field_attrs
end
- product.update(metafields_attributes: nested_attrs) unless nested_attrs.empty?
+ product.update!(custom_fields_attributes: nested_attrs) unless nested_attrs.empty?
end
def handle_tags(product)
diff --git a/spree/core/app/services/spree/sample_data/loader.rb b/spree/core/app/services/spree/sample_data/loader.rb
index 64fda94605..828198095d 100644
--- a/spree/core/app/services/spree/sample_data/loader.rb
+++ b/spree/core/app/services/spree/sample_data/loader.rb
@@ -20,8 +20,8 @@ module Spree
puts 'Loading sample channels...'
load_ruby_file('channels')
- puts 'Loading sample metafield definitions...'
- load_ruby_file('metafield_definitions')
+ puts 'Loading sample custom_field definitions...'
+ load_ruby_file('custom_field_definitions')
puts 'Loading sample options...'
load_ruby_file('options')
diff --git a/spree/core/app/services/spree/search_provider/metafield_schema.rb b/spree/core/app/services/spree/search_provider/custom_field_schema.rb
similarity index 94%
rename from spree/core/app/services/spree/search_provider/metafield_schema.rb
rename to spree/core/app/services/spree/search_provider/custom_field_schema.rb
index a54906a652..886493a042 100644
--- a/spree/core/app/services/spree/search_provider/metafield_schema.rb
+++ b/spree/core/app/services/spree/search_provider/custom_field_schema.rb
@@ -2,8 +2,8 @@
module Spree
module SearchProvider
- # Product metafield definitions that participate in search/sort.
- class MetafieldSchema
+ # Product custom_field definitions that participate in search/sort.
+ class CustomFieldSchema
# Ransack-style predicates accepted per field type. Mirrors the operator
# sets the admin dashboard's filter panel offers for string/number columns
# (see packages/dashboard-core/src/components/table-toolbar.tsx).
@@ -15,7 +15,7 @@ module Spree
ORDERED_FILTER_PREDICATES = (TEXT_FILTER_PREDICATES | NUMBER_FILTER_PREDICATES).
sort_by { |predicate| -predicate.length }.freeze
- # @return [Hash{String => Spree::MetafieldDefinition}]
+ # @return [Hash{String => Spree::CustomFieldDefinition}]
def entries
@entries ||= product_definitions.index_by(&:filter_key)
end
@@ -35,7 +35,7 @@ module Spree
end
# @param attribute_key [String]
- # @return [Spree::MetafieldDefinition, nil]
+ # @return [Spree::CustomFieldDefinition, nil]
def entry_for(attribute_key)
entries[attribute_key.to_s]
end
@@ -126,7 +126,7 @@ module Spree
private
def product_definitions
- scope = Spree::MetafieldDefinition.for_resource_type('Spree::Product')
+ scope = Spree::CustomFieldDefinition.for_resource_type('Spree::Product')
scope.where(searchable: true).or(scope.where(sortable: true))
end
diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.yml
index 98e1e4535f..6edcbb64c7 100644
--- a/spree/core/config/locales/en.yml
+++ b/spree/core/config/locales/en.yml
@@ -47,6 +47,10 @@ en:
number: Number
verification_value: Verification Value
year: Year
+ spree/custom_field_definition:
+ namespace: Namespace
+ searchable: Searchable
+ sortable: Sortable
spree/customer_group:
description: Description
name: Name
@@ -67,10 +71,6 @@ en:
spree/line_item:
price: Price
quantity: Quantity
- spree/metafield_definition:
- namespace: Namespace
- searchable: Searchable
- sortable: Sortable
spree/option_type:
filterable: Filterable
kind: Kind
@@ -775,6 +775,8 @@ en:
currency_not_supported_by_store: is not supported by this store
current: Current
current_password: Current password
+ custom_field_definitions: Custom Field Definitions
+ custom_fields: Custom Fields
customer: Customer
customer_group: Customer Group
customer_groups: Customer Groups
@@ -1077,8 +1079,6 @@ en:
meta_keywords: Meta Keywords
meta_title: Meta Title
metadata: Metadata
- metafield_definitions: Metafield Definitions
- metafields: Metafields
min: Min
min_quantity: Min Quantity
minimal_amount: Minimal Amount
diff --git a/spree/core/db/migrate/20260809000001_rename_metafields_to_custom_fields.rb b/spree/core/db/migrate/20260809000001_rename_metafields_to_custom_fields.rb
new file mode 100644
index 0000000000..2fc60d3a3b
--- /dev/null
+++ b/spree/core/db/migrate/20260809000001_rename_metafields_to_custom_fields.rb
@@ -0,0 +1,126 @@
+class RenameMetafieldsToCustomFields < ActiveRecord::Migration[7.2]
+ # STI class names and the `metafield_type` column both store the Ruby class
+ # name. A renamed class cannot load its own legacy rows, so the substitution
+ # runs here rather than in the upgrade manifest — after this migration the
+ # models are unusable until the strings match.
+ TYPE_RENAMES = {
+ 'Spree::Metafields::ShortText' => 'Spree::CustomFields::ShortText',
+ 'Spree::Metafields::LongText' => 'Spree::CustomFields::LongText',
+ 'Spree::Metafields::RichText' => 'Spree::CustomFields::RichText',
+ 'Spree::Metafields::Number' => 'Spree::CustomFields::Number',
+ 'Spree::Metafields::Boolean' => 'Spree::CustomFields::Boolean',
+ 'Spree::Metafields::Json' => 'Spree::CustomFields::Json'
+ }.freeze
+
+ def up
+ rename_table :spree_metafield_definitions, :spree_custom_field_definitions
+ rename_table :spree_metafields, :spree_custom_fields
+
+ rename_column :spree_custom_fields, :metafield_definition_id, :custom_field_definition_id
+ rename_column :spree_custom_field_definitions, :metafield_type, :field_type
+ rename_column :spree_custom_field_definitions, :name, :label
+
+ rename_index :spree_custom_fields, 'index_metafields_on_resource_and_definition',
+ 'index_custom_fields_on_resource_and_definition'
+
+ TYPE_RENAMES.each do |from, to|
+ execute_type_rename(:spree_custom_fields, :type, from, to)
+ execute_type_rename(:spree_custom_field_definitions, :field_type, from, to)
+ end
+
+ # Rich-text values move out of Action Text and into the shared `value`
+ # column (docs/plans/6.0-rich-text-descriptions.md). Action Text keys rows
+ # by the owner's STI base class, so they are found under the pre-rename
+ # class name. The source rows are left in place as the rollback path; the
+ # table is dropped in 6.1.
+ copy_action_text_bodies_into_values
+
+ # display_on (both/front_end/back_end) collapses to a boolean. Only
+ # back_end meant "hide from the storefront"; front_end-only was never a
+ # supported value on definitions.
+ add_column :spree_custom_field_definitions, :storefront_visible, :boolean, default: true, null: false
+ execute(<<~SQL.squish)
+ UPDATE spree_custom_field_definitions
+ SET storefront_visible = #{quoted_false}
+ WHERE display_on = 'back_end'
+ SQL
+ remove_column :spree_custom_field_definitions, :display_on
+ end
+
+ def down
+ add_column :spree_custom_field_definitions, :display_on, :string, default: 'both', null: false
+ execute(<<~SQL.squish)
+ UPDATE spree_custom_field_definitions
+ SET display_on = 'back_end'
+ WHERE storefront_visible = #{quoted_false}
+ SQL
+ add_index :spree_custom_field_definitions, :display_on
+ remove_column :spree_custom_field_definitions, :storefront_visible
+
+ # The Action Text rows were never deleted, so rolling back only needs to
+ # clear the copied column.
+ clear_rich_text_values
+
+ TYPE_RENAMES.each do |from, to|
+ execute_type_rename(:spree_custom_fields, :type, to, from)
+ execute_type_rename(:spree_custom_field_definitions, :field_type, to, from)
+ end
+
+ rename_index :spree_custom_fields, 'index_custom_fields_on_resource_and_definition',
+ 'index_metafields_on_resource_and_definition'
+
+ rename_column :spree_custom_field_definitions, :label, :name
+ rename_column :spree_custom_field_definitions, :field_type, :metafield_type
+ rename_column :spree_custom_fields, :custom_field_definition_id, :metafield_definition_id
+
+ rename_table :spree_custom_fields, :spree_metafields
+ rename_table :spree_custom_field_definitions, :spree_metafield_definitions
+ end
+
+ private
+
+ RICH_TEXT_TYPE = 'Spree::CustomFields::RichText'.freeze
+ # Action Text stores the owner's STI base class, so rows written before this
+ # migration are filed under the pre-rename name.
+ LEGACY_ACTION_TEXT_OWNER = 'Spree::Metafield'.freeze
+
+ # A correlated subquery rather than UPDATE ... FROM / UPDATE ... JOIN, which
+ # are spelled differently on PostgreSQL, MySQL and SQLite.
+ def copy_action_text_bodies_into_values
+ return unless connection.table_exists?(:action_text_rich_texts)
+
+ body = <<~SQL.squish
+ SELECT #{quote_column_name('body')} FROM #{quote_table_name('action_text_rich_texts')}
+ WHERE #{quote_table_name('action_text_rich_texts')}.#{quote_column_name('record_id')} = #{quote_table_name('spree_custom_fields')}.#{quote_column_name('id')}
+ AND #{quote_table_name('action_text_rich_texts')}.#{quote_column_name('record_type')} = #{quote(LEGACY_ACTION_TEXT_OWNER)}
+ AND #{quote_table_name('action_text_rich_texts')}.#{quote_column_name('name')} = #{quote('value')}
+ SQL
+
+ execute(<<~SQL.squish)
+ UPDATE #{quote_table_name('spree_custom_fields')}
+ SET #{quote_column_name('value')} = (#{body})
+ WHERE #{quote_column_name('type')} = #{quote(RICH_TEXT_TYPE)}
+ AND EXISTS (#{body})
+ SQL
+ end
+
+ def clear_rich_text_values
+ execute(<<~SQL.squish)
+ UPDATE #{quote_table_name('spree_custom_fields')}
+ SET #{quote_column_name('value')} = NULL
+ WHERE #{quote_column_name('type')} = #{quote(RICH_TEXT_TYPE)}
+ SQL
+ end
+
+ def execute_type_rename(table, column, from, to)
+ execute(<<~SQL.squish)
+ UPDATE #{quote_table_name(table)}
+ SET #{quote_column_name(column)} = #{quote(to)}
+ WHERE #{quote_column_name(column)} = #{quote(from)}
+ SQL
+ end
+
+ def quoted_false
+ connection.quoted_false
+ end
+end
diff --git a/spree/core/db/sample_data/metafield_definitions.rb b/spree/core/db/sample_data/custom_field_definitions.rb
similarity index 78%
rename from spree/core/db/sample_data/metafield_definitions.rb
rename to spree/core/db/sample_data/custom_field_definitions.rb
index aa6160c7a4..268a1db429 100644
--- a/spree/core/db/sample_data/metafield_definitions.rb
+++ b/spree/core/db/sample_data/custom_field_definitions.rb
@@ -1,5 +1,5 @@
%w[warranty capacity voltage wattage runtime room_coverage noise_level connectivity].each do |key|
- Spree::MetafieldDefinition.find_or_create_by!(
+ Spree::CustomFieldDefinition.find_or_create_by!(
namespace: 'custom',
key: key,
resource_type: 'Spree::Product'
diff --git a/spree/core/db/sample_data/product_types.rb b/spree/core/db/sample_data/product_types.rb
index c4a771fb4d..d0082305e5 100644
--- a/spree/core/db/sample_data/product_types.rb
+++ b/spree/core/db/sample_data/product_types.rb
@@ -14,7 +14,7 @@ store = Spree::Store.default
color_option_type = Spree::OptionType.find_by(name: 'color')
-definitions = Spree::MetafieldDefinition.where(
+definitions = Spree::CustomFieldDefinition.where(
namespace: 'custom',
resource_type: 'Spree::Product'
).index_by(&:key)
diff --git a/spree/core/db/sample_data/products.csv b/spree/core/db/sample_data/products.csv
index 1ae5794c6d..a5b1c6a9d8 100644
--- a/spree/core/db/sample_data/products.csv
+++ b/spree/core/db/sample_data/products.csv
@@ -1,4 +1,4 @@
-slug,sku,name,price,compare_at_price,currency,status,description,meta_title,meta_description,meta_keywords,tags,tax_category,product_type,category1,option1_name,option1_value,option2_name,option2_value,image1_src,width,height,depth,dimensions_unit,weight,weight_unit,available_on,discontinue_on,inventory_count,inventory_backorderable,track_inventory,metafield.custom.wattage,metafield.custom.voltage,metafield.custom.warranty,metafield.custom.capacity,metafield.custom.runtime,metafield.custom.room_coverage,metafield.custom.noise_level,metafield.custom.connectivity
+slug,sku,name,price,compare_at_price,currency,status,description,meta_title,meta_description,meta_keywords,tags,tax_category,product_type,category1,option1_name,option1_value,option2_name,option2_value,image1_src,width,height,depth,dimensions_unit,weight,weight_unit,available_on,discontinue_on,inventory_count,inventory_backorderable,track_inventory,custom_field.custom.wattage,custom_field.custom.voltage,custom_field.custom.warranty,custom_field.custom.capacity,custom_field.custom.runtime,custom_field.custom.room_coverage,custom_field.custom.noise_level,custom_field.custom.connectivity
automatic-espresso-machine,AUTOMATIC-ESPRESSO-MACHINE,Automatic Espresso Machine,0,0,USD,active,"Fully automatic bean-to-cup espresso machine with ceramic grinder, 15-bar pressure system, and intuitive touch display. Delivers barista-quality espresso, cappuccino, and latte at the touch of a button.",Automatic Espresso Machine | Spree Commerce Demo,Shop the Automatic Espresso Machine on the Spree Commerce demo store. Bean-to-cup coffee with 15-bar pressure & ceramic grinder. Spree ecommerce in action.,"automatic espresso machine, bean-to-cup coffee machine, home espresso machine, spree commerce, spree demo store, ecommerce platform demo","coffee, espresso, kitchen, coffee machines, bean-to-cup, automatic",Default,Kitchen Appliance,Kitchen -> Coffee Machines,,,,,https://raw.githubusercontent.com/spree/spree/main/docs/images/demo-images/automatic-espresso-machine.webp,,,,in,,lb,,,,FALSE,,1400W,220-240V,2 Years,,,,,
automatic-espresso-machine,AUTOMATIC-ESPRESSO-MACHINE-MATTE-BLACK,,879.99,0,USD,,,,,,,,,,Color,Matte Black,,,https://raw.githubusercontent.com/spree/spree/main/docs/images/demo-images/automatic-espresso-machine-matte-black.webp,13.8,15.7,11.8,in,19.8,lb,,,5000,FALSE,TRUE,,,,,,,,
automatic-espresso-machine,AUTOMATIC-ESPRESSO-MACHINE-SILVER,,879.99,0,USD,,,,,,,,,,Color,Silver,,,https://raw.githubusercontent.com/spree/spree/main/docs/images/demo-images/automatic-espresso-machine-silver.webp,13.8,15.7,11.8,in,19.8,lb,,,5000,FALSE,TRUE,,,,,,,,
diff --git a/spree/core/lib/generators/spree/api_resource/api_resource_generator.rb b/spree/core/lib/generators/spree/api_resource/api_resource_generator.rb
index d5c9eedb31..7d495ca6c9 100644
--- a/spree/core/lib/generators/spree/api_resource/api_resource_generator.rb
+++ b/spree/core/lib/generators/spree/api_resource/api_resource_generator.rb
@@ -10,7 +10,7 @@ module Spree
#
# Inherits from Spree::ModelGenerator (model + migration with Spree
# conventions: prefixed IDs, spree_-prefixed tables, null: false, optional
- # acts_as_paranoid + Spree::Metafields). Adds on top:
+ # acts_as_paranoid + Spree::HasCustomFields). Adds on top:
#
# - Store + Admin controllers (managed — overwrite on re-run)
# - Store + Admin serializers (managed — overwrite on re-run)
diff --git a/spree/core/lib/generators/spree/model/model_generator.rb b/spree/core/lib/generators/spree/model/model_generator.rb
index b12198e411..f00e11de71 100644
--- a/spree/core/lib/generators/spree/model/model_generator.rb
+++ b/spree/core/lib/generators/spree/model/model_generator.rb
@@ -20,10 +20,10 @@ module Spree
default: false,
desc: 'Enable acts_as_paranoid soft-delete (adds deleted_at column + index)'
- class_option :metafields,
+ class_option :custom_fields,
type: :boolean,
default: false,
- desc: 'Include Spree::Metafields and Spree::Metadata concerns'
+ desc: 'Include Spree::HasCustomFields and Spree::Metadata concerns'
desc 'Creates a new Spree model with prefixed IDs and Spree.base_class parent'
@@ -40,8 +40,8 @@ module Spree
options[:paranoid]
end
- def metafields?
- options[:metafields]
+ def custom_fields?
+ options[:custom_fields]
end
def class_path
diff --git a/spree/core/lib/generators/spree/model/templates/model.rb.tt b/spree/core/lib/generators/spree/model/templates/model.rb.tt
index 2a832f0b56..877c1c7680 100644
--- a/spree/core/lib/generators/spree/model/templates/model.rb.tt
+++ b/spree/core/lib/generators/spree/model/templates/model.rb.tt
@@ -1,7 +1,7 @@
module Spree
class <%= class_name.demodulize %> < <%= parent_class_name %>
-<% if metafields? -%>
- include Spree::Metafields
+<% if custom_fields? -%>
+ include Spree::HasCustomFields
include Spree::Metadata
<% end -%>
diff --git a/spree/core/lib/spree/core.rb b/spree/core/lib/spree/core.rb
index 147915affc..1ad7ee370b 100644
--- a/spree/core/lib/spree/core.rb
+++ b/spree/core/lib/spree/core.rb
@@ -434,8 +434,13 @@ module Spree
Rails.application.config.spree.translatable_resources = value
end
+ def self.custom_fields
+ Rails.application.config.spree.custom_fields
+ end
+
def self.metafields
- Rails.application.config.spree.metafields
+ Spree::Deprecation.warn('Spree.metafields is deprecated and will be removed in Spree 6.1. Use Spree.custom_fields instead.') if defined?(Spree::Deprecation)
+ custom_fields
end
def self.integrations
diff --git a/spree/core/lib/spree/core/engine.rb b/spree/core/lib/spree/core/engine.rb
index 5a75ff89c0..e13c8e3fd3 100644
--- a/spree/core/lib/spree/core/engine.rb
+++ b/spree/core/lib/spree/core/engine.rb
@@ -34,7 +34,7 @@ module Spree
:reports,
:translatable_resources,
:taggable_types,
- :metafields,
+ :custom_fields,
:analytics_events,
:analytics_event_handlers,
:integrations,
@@ -46,7 +46,7 @@ module Spree
PricingEnvironment = Struct.new(:rules)
OrderRoutingEnvironment = Struct.new(:strategies, :rules)
SpreeValidators = Struct.new(:addresses)
- MetafieldsEnvironment = Struct.new(:types, :enabled_resources)
+ CustomFieldsEnvironment = Struct.new(:types, :enabled_resources)
isolate_namespace Spree
engine_name 'spree'
@@ -120,10 +120,10 @@ module Spree
app.config.spree.delivery_method_rules = []
end
- initializer 'spree.register.metafields' do |app|
- app.config.spree.metafields = MetafieldsEnvironment.new
- app.config.spree.metafields.types = []
- app.config.spree.metafields.enabled_resources = []
+ initializer 'spree.register.custom_fields' do |app|
+ app.config.spree.custom_fields = CustomFieldsEnvironment.new
+ app.config.spree.custom_fields.types = []
+ app.config.spree.custom_fields.enabled_resources = []
end
# We need to define promotions rules here so extensions and existing apps
@@ -334,16 +334,16 @@ module Spree
Spree.customer_class.to_s
]
- Rails.application.config.spree.metafields.types = [
- Spree::Metafields::ShortText,
- Spree::Metafields::LongText,
- Spree::Metafields::RichText,
- Spree::Metafields::Number,
- Spree::Metafields::Boolean,
- Spree::Metafields::Json
+ Rails.application.config.spree.custom_fields.types = [
+ Spree::CustomFields::ShortText,
+ Spree::CustomFields::LongText,
+ Spree::CustomFields::RichText,
+ Spree::CustomFields::Number,
+ Spree::CustomFields::Boolean,
+ Spree::CustomFields::Json
]
- Rails.application.config.spree.metafields.enabled_resources = [
+ Rails.application.config.spree.custom_fields.enabled_resources = [
Spree::Address,
Spree::Asset,
Spree::Claim,
diff --git a/spree/core/lib/spree/core/permission_configuration.rb b/spree/core/lib/spree/core/permission_configuration.rb
index 5e8500f97f..7edcabe3fe 100644
--- a/spree/core/lib/spree/core/permission_configuration.rb
+++ b/spree/core/lib/spree/core/permission_configuration.rb
@@ -231,7 +231,7 @@ module Spree
def register_default_resources
register_resource(:orders, group: :orders, subjects: -> {
[Spree::Order, Spree::LineItem, Spree::TaxLine, Spree::Discount, Spree::Fee,
- Spree::Return, Spree::Exchange, Spree::Claim, Spree::Metafield]
+ Spree::Return, Spree::Exchange, Spree::Claim, Spree::CustomField]
})
register_resource(:payments, group: :orders, subjects: -> { [Spree::Payment] })
register_resource(:fulfillments, group: :orders, subjects: -> { [Spree::Fulfillment] })
@@ -244,7 +244,7 @@ module Spree
register_resource(:products, group: :catalog, subjects: -> {
[Spree::Product, Spree::ProductType, Spree::Variant, Spree::OptionType,
Spree::OptionValue, Spree::Price, Spree::PriceList, Spree::PriceRule,
- Spree::Asset, Spree::ProductPublication, Spree::Metafield]
+ Spree::Asset, Spree::ProductPublication, Spree::CustomField]
})
register_resource(:categories, group: :catalog, subjects: -> {
[Spree::Category, Spree::ProductCategory]
@@ -259,12 +259,12 @@ module Spree
register_resource(:promotions, group: :marketing, subjects: -> {
[Spree::Promotion, Spree::PromotionRule, Spree::PromotionAction,
- Spree::PromotionCategory, Spree::CouponCode, Spree::Metafield]
+ Spree::PromotionCategory, Spree::CouponCode, Spree::CustomField]
})
register_resource(:customers, group: :customers, subjects: -> {
[Spree.customer_class, Spree::Address, Spree::CreditCard, Spree::CustomerGroup,
- Spree::Metafield]
+ Spree::CustomField]
})
register_resource(:settings, group: :settings, subjects: -> {
@@ -273,7 +273,7 @@ module Spree
Spree::StockLocation, Spree::ShippingCategory, Spree::Zone, Spree::ZoneMember,
Spree::Market, Spree::TaxCategory, Spree::TaxRate, Spree::AllowedOrigin,
Spree::RefundReason, Spree::ReturnReason, Spree::ClaimReason, Spree::Channel,
- Spree::OrderRoutingRule, Spree::MetafieldDefinition, Spree::Policy,
+ Spree::OrderRoutingRule, Spree::CustomFieldDefinition, Spree::Policy,
Spree::StoreCreditCategory]
})
register_resource(:webhooks, group: :settings, subjects: -> {
diff --git a/spree/core/lib/spree/permitted_attributes.rb b/spree/core/lib/spree/permitted_attributes.rb
index b74d987bd3..7159962e35 100644
--- a/spree/core/lib/spree/permitted_attributes.rb
+++ b/spree/core/lib/spree/permitted_attributes.rb
@@ -27,8 +27,8 @@ module Spree
:market_attributes,
:menu_attributes,
:menu_item_attributes,
- :metafield_attributes,
- :metafield_definition_attributes,
+ :custom_field_attributes,
+ :custom_field_definition_attributes,
:option_type_attributes,
:option_value_attributes,
:page_attributes,
@@ -140,10 +140,10 @@ module Spree
@@menu_item_attributes = [:name, :subtitle, :destination, :new_window, :item_type,
:linked_resource_type, :linked_resource_id, :code, :menu_id]
- @@metafield_attributes = [:id, :value, :type, :metafield_definition_id, :_destroy]
+ @@custom_field_attributes = [:id, :value, :type, :custom_field_definition_id, :_destroy]
- @@metafield_definition_attributes = [
- :key, :name, :namespace, :metafield_type, :resource_type, :display_on,
+ @@custom_field_definition_attributes = [
+ :key, :label, :namespace, :field_type, :resource_type, :storefront_visible,
:searchable, :sortable
]
diff --git a/spree/core/lib/spree/testing_support/factories/metafield_definition_factory.rb b/spree/core/lib/spree/testing_support/factories/custom_field_definition_factory.rb
similarity index 52%
rename from spree/core/lib/spree/testing_support/factories/metafield_definition_factory.rb
rename to spree/core/lib/spree/testing_support/factories/custom_field_definition_factory.rb
index 7b0aede110..2195371f89 100644
--- a/spree/core/lib/spree/testing_support/factories/metafield_definition_factory.rb
+++ b/spree/core/lib/spree/testing_support/factories/custom_field_definition_factory.rb
@@ -1,56 +1,52 @@
FactoryBot.define do
- factory :metafield_definition, aliases: [:custom_field_definition], class: 'Spree::MetafieldDefinition' do
+ factory :custom_field_definition, aliases: [:metafield_definition], class: 'Spree::CustomFieldDefinition' do
namespace { 'custom' }
sequence(:key) { |n| "custom_field_#{n}" }
- name { 'Custom Field' }
- metafield_type { 'Spree::Metafields::ShortText' }
+ label { 'Custom Field' }
+ field_type { 'Spree::CustomFields::ShortText' }
resource_type { 'Spree::Product' }
- display_on { 'both' }
+ storefront_visible { true }
searchable { false }
sortable { false }
- trait :front_end_only do
- display_on { 'front_end' }
- end
-
- trait :back_end_only do
- display_on { 'back_end' }
+ trait :admin_only do
+ storefront_visible { false }
end
trait :short_text_field do
- metafield_type { 'Spree::Metafields::ShortText' }
+ field_type { 'Spree::CustomFields::ShortText' }
key { 'title' }
- name { 'Title' }
+ label { 'Title' }
end
trait :long_text_field do
- metafield_type { 'Spree::Metafields::LongText' }
+ field_type { 'Spree::CustomFields::LongText' }
key { 'description' }
- name { 'Description' }
+ label { 'Description' }
end
trait :rich_text_field do
- metafield_type { 'Spree::Metafields::RichText' }
+ field_type { 'Spree::CustomFields::RichText' }
key { 'content' }
- name { 'Content' }
+ label { 'Content' }
end
trait :number_field do
- metafield_type { 'Spree::Metafields::Number' }
+ field_type { 'Spree::CustomFields::Number' }
key { 'priority' }
- name { 'Priority' }
+ label { 'Priority' }
end
trait :boolean_field do
- metafield_type { 'Spree::Metafields::Boolean' }
+ field_type { 'Spree::CustomFields::Boolean' }
key { 'featured' }
- name { 'Featured' }
+ label { 'Featured' }
end
trait :json_field do
- metafield_type { 'Spree::Metafields::Json' }
+ field_type { 'Spree::CustomFields::Json' }
key { 'metadata' }
- name { 'Metadata' }
+ label { 'Metadata' }
end
trait :searchable do
@@ -64,19 +60,19 @@ FactoryBot.define do
trait :for_variant do
resource_type { 'Spree::Variant' }
key { 'variant_custom' }
- name { 'Variant Custom Field' }
+ label { 'Variant Custom Field' }
end
trait :for_order do
resource_type { 'Spree::Order' }
key { 'order_notes' }
- name { 'Order Notes' }
+ label { 'Order Notes' }
end
trait :for_user do
resource_type { Spree.customer_class.name }
key { 'user_preference' }
- name { 'User Preference' }
+ label { 'User Preference' }
end
end
end
diff --git a/spree/core/lib/spree/testing_support/factories/custom_field_factory.rb b/spree/core/lib/spree/testing_support/factories/custom_field_factory.rb
new file mode 100644
index 0000000000..2fd72d6a3a
--- /dev/null
+++ b/spree/core/lib/spree/testing_support/factories/custom_field_factory.rb
@@ -0,0 +1,64 @@
+FactoryBot.define do
+ factory :custom_field, aliases: [:metafield], class: 'Spree::CustomField' do
+ value { 'test_value' }
+ type { 'Spree::CustomFields::ShortText' }
+
+ association :resource, factory: :product
+ association :custom_field_definition
+
+ trait :admin_only do
+ association :custom_field_definition, :admin_only
+ end
+
+ trait :short_text do
+ type { 'Spree::CustomFields::ShortText' }
+ association :custom_field_definition, :short_text_field
+ value { 'Short text value' }
+ end
+
+ trait :long_text do
+ type { 'Spree::CustomFields::LongText' }
+ association :custom_field_definition, :long_text_field
+ value { 'This is a longer text value with more detailed information.' }
+ end
+
+ trait :number do
+ type { 'Spree::CustomFields::Number' }
+ association :custom_field_definition, :number_field
+ value { 42 }
+ end
+
+ trait :rich_text do
+ type { 'Spree::CustomFields::RichText' }
+ association :custom_field_definition, :rich_text_field
+ value { '<p>Rich text with <strong>formatting</strong></p>' }
+ end
+
+ trait :boolean do
+ type { 'Spree::CustomFields::Boolean' }
+ association :custom_field_definition, :boolean_field
+ value { true }
+ end
+
+ trait :json do
+ type { 'Spree::CustomFields::Json' }
+ association :custom_field_definition, :json_field
+ value { '{"key": "value"}' }
+ end
+
+ trait :for_variant do
+ association :resource, factory: :variant
+ association :custom_field_definition, :for_variant
+ end
+
+ trait :for_order do
+ association :resource, factory: :order
+ association :custom_field_definition, :for_order
+ end
+
+ trait :for_user do
+ association :resource, factory: :user
+ association :custom_field_definition, :for_user
+ end
+ end
+end
diff --git a/spree/core/lib/spree/testing_support/factories/metafield_factory.rb b/spree/core/lib/spree/testing_support/factories/metafield_factory.rb
deleted file mode 100644
index f53dd7e2ef..0000000000
--- a/spree/core/lib/spree/testing_support/factories/metafield_factory.rb
+++ /dev/null
@@ -1,68 +0,0 @@
-FactoryBot.define do
- factory :metafield, class: 'Spree::Metafield' do
- value { 'test_value' }
- type { 'Spree::Metafields::ShortText' }
-
- association :resource, factory: :product
- association :metafield_definition
-
- trait :front_end_only do
- association :metafield_definition, :front_end_only
- end
-
- trait :back_end_only do
- association :metafield_definition, :back_end_only
- end
-
- trait :short_text do
- type { 'Spree::Metafields::ShortText' }
- association :metafield_definition, :short_text_field
- value { 'Short text value' }
- end
-
- trait :long_text do
- type { 'Spree::Metafields::LongText' }
- association :metafield_definition, :long_text_field
- value { 'This is a longer text value with more detailed information.' }
- end
-
- trait :number do
- type { 'Spree::Metafields::Number' }
- association :metafield_definition, :number_field
- value { 42 }
- end
-
- trait :rich_text do
- type { 'Spree::Metafields::RichText' }
- association :metafield_definition, :rich_text_field
- value { '<p>Rich text with <strong>formatting</strong></p>' }
- end
-
- trait :boolean do
- type { 'Spree::Metafields::Boolean' }
- association :metafield_definition, :boolean_field
- value { true }
- end
-
- trait :json do
- type { 'Spree::Metafields::Json' }
- association :metafield_definition, :json_field
- value { '{"key": "value"}' }
- end
-
- trait :for_variant do
- association :resource, factory: :variant
- association :metafield_definition, :for_variant
- end
-
- trait :for_order do
- association :resource, factory: :order
- association :metafield_definition, :for_order
- end
-
- trait :for_user do
- association :resource, factory: :user
- association :metafield_definition, :for_user
- end
- end
-end
diff --git a/spree/core/lib/spree/upgrades/5_6_to_6_0/manifest.yml b/spree/core/lib/spree/upgrades/5_6_to_6_0/manifest.yml
index 0b6cb97d5e..d94679267f 100644
--- a/spree/core/lib/spree/upgrades/5_6_to_6_0/manifest.yml
+++ b/spree/core/lib/spree/upgrades/5_6_to_6_0/manifest.yml
@@ -62,7 +62,7 @@ steps:
taxonomy roots left childless, and nulls taxonomy_id on the survivors
(categories are store-owned in 6.0). Finally backfills the renamed
class-name strings ('Spree::Taxon*' -> 'Spree::Category*') across the
- metafield, attachment, ActionText, friendly_id slug and promotion-rule
+ custom-field, attachment, ActionText, friendly_id slug and promotion-rule
columns.
Idempotent. Multi-tenant installs run the per-tenant override shipped by
diff --git a/spree/core/spec/db/migrate/rename_metafields_to_custom_fields_spec.rb b/spree/core/spec/db/migrate/rename_metafields_to_custom_fields_spec.rb
new file mode 100644
index 0000000000..615fc6d127
--- /dev/null
+++ b/spree/core/spec/db/migrate/rename_metafields_to_custom_fields_spec.rb
@@ -0,0 +1,51 @@
+require 'spec_helper'
+
+# The rename migration rewrites stored class-name strings and moves rich-text
+# bodies out of Action Text. All of it is data no model can reach once the
+# classes are renamed, so it is covered here rather than through a model.
+RSpec.describe 'RenameMetafieldsToCustomFields migration' do
+ let(:migration) do
+ require Spree::Core::Engine.root.join('db', 'migrate', '20260809000001_rename_metafields_to_custom_fields.rb')
+ RenameMetafieldsToCustomFields.new
+ end
+
+ let(:connection) { ActiveRecord::Base.connection }
+
+ describe 'rich-text values' do
+ let(:product) { create(:product) }
+ let(:definition) do
+ create(:custom_field_definition, field_type: 'Spree::CustomFields::RichText', namespace: 'custom', key: 'notes')
+ end
+
+ # Rich text used to live in Action Text, which keys rows by the owner's STI
+ # *base* class — so pre-upgrade bodies sit under 'Spree::Metafield'. They
+ # have to be copied into the shared `value` column or the content silently
+ # disappears from the admin.
+ it 'copies bodies stored under the legacy owner class into the value column' do
+ custom_field = Spree::CustomFields::RichText.create!(
+ resource: product, custom_field_definition: definition, value: 'placeholder'
+ )
+ connection.insert(<<~SQL.squish)
+ INSERT INTO #{ActionText::RichText.table_name} (name, body, record_type, record_id, created_at, updated_at)
+ VALUES ('value', '<p>legacy body</p>', 'Spree::Metafield', #{custom_field.id}, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
+ SQL
+ connection.update(
+ "UPDATE #{Spree::CustomField.table_name} SET value = NULL WHERE id = #{custom_field.id}"
+ )
+
+ migration.send(:copy_action_text_bodies_into_values)
+
+ expect(custom_field.reload.value).to eq('<p>legacy body</p>')
+ end
+
+ it 'leaves rich-text values that were never in Action Text alone' do
+ custom_field = Spree::CustomFields::RichText.create!(
+ resource: product, custom_field_definition: definition, value: '<p>already migrated</p>'
+ )
+
+ migration.send(:copy_action_text_bodies_into_values)
+
+ expect(custom_field.reload.value).to eq('<p>already migrated</p>')
+ end
+ end
+end
diff --git a/spree/core/spec/fixtures/files/products_import.csv b/spree/core/spec/fixtures/files/products_import.csv
index 1c2cb9be66..6aa7e7c2b3 100644
--- a/spree/core/spec/fixtures/files/products_import.csv
+++ b/spree/core/spec/fixtures/files/products_import.csv
@@ -1,4 +1,4 @@
-slug,sku,name,status,vendor_name,brand_name,description,meta_title,meta_description,meta_keywords,tags,labels,price,compare_at_price,currency,width,height,depth,dimensions_unit,weight,weight_unit,available_on,discontinue_on,track_inventory,inventory_count,inventory_backorderable,tax_category,digital,image1_src,image2_src,image3_src,option1_name,option1_value,option2_name,option2_value,option3_name,option3_value,category1,category2,category3,metafield.properties.fit,metafield.properties.manufacturer,metafield.properties.material,metafield.custom.brand,metafield.custom.material
+slug,sku,name,status,vendor_name,brand_name,description,meta_title,meta_description,meta_keywords,tags,labels,price,compare_at_price,currency,width,height,depth,dimensions_unit,weight,weight_unit,available_on,discontinue_on,track_inventory,inventory_count,inventory_backorderable,tax_category,digital,image1_src,image2_src,image3_src,option1_name,option1_value,option2_name,option2_value,option3_name,option3_value,category1,category2,category3,custom_field.properties.fit,custom_field.properties.manufacturer,custom_field.properties.material,custom_field.custom.brand,custom_field.custom.material
denim-shirt,"",Denim Shirt,draft,,,Adipisci sapiente velit nihil ullam. Placeat cumque ipsa cupiditate velit magni sapiente mollitia dolorum. Veritatis esse illo eos perferendis. Perspiciatis vel iusto odio eveniet quam officia quidem. Fugiat a ipsum tempore optio accusantium autem in fugit.,,,,"","",0.0,0.0,USD,,,,,0.0,lb,2025-10-09 14:35:53,,true,100,true,Default,false,,,,,,,,,,Men -> Shirts,Women,Sportswear,Lose,Wannabe,90% Cotton 10% Elastan,,
denim-shirt,DENIM-SHIRT-XS-BLUE,,,,,,,,,,,62.99,0.0,USD,,,,,0.0,lb,2025-10-09 14:35:53,,true,100,true,Clothing,false,,,,Color,Blue,Size,XS,,,,,
denim-shirt,DENIM-SHIRT-S-BLUE,,,,,,,,,,,62.99,0.0,USD,,,,,0.0,lb,2025-10-09 14:35:53,,true,100,true,Clothing,false,,,,Color,Blue,Size,S,,,,,
diff --git a/spree/core/spec/lib/generators/spree/model/model_generator_spec.rb b/spree/core/spec/lib/generators/spree/model/model_generator_spec.rb
index 8727e847f4..3484724dd5 100644
--- a/spree/core/spec/lib/generators/spree/model/model_generator_spec.rb
+++ b/spree/core/spec/lib/generators/spree/model/model_generator_spec.rb
@@ -60,10 +60,10 @@ RSpec.describe Spree::ModelGenerator, type: :generator do
expect(result[:model]).to include('acts_as_paranoid')
end
- it 'includes Metafields concerns when --metafields is set' do
- result = run_generator(['Brand', 'name:string', '--metafields'])
+ it 'includes CustomFields concerns when --custom_fields is set' do
+ result = run_generator(['Brand', 'name:string', '--custom_fields'])
- expect(result[:model]).to include('include Spree::Metafields')
+ expect(result[:model]).to include('include Spree::HasCustomFields')
expect(result[:model]).to include('include Spree::Metadata')
end
@@ -117,7 +117,7 @@ RSpec.describe Spree::ModelGenerator, type: :generator do
end
it 'omits class_name and emits polymorphic: true for polymorphic references' do
- result = run_generator(['Metafield', 'resource:references{polymorphic}'])
+ result = run_generator(['CustomField', 'resource:references{polymorphic}'])
expect(result[:model]).to include('belongs_to :resource, polymorphic: true')
expect(result[:model]).not_to include('class_name:')
@@ -146,7 +146,7 @@ RSpec.describe Spree::ModelGenerator, type: :generator do
end
it 'preserves polymorphic: true on polymorphic references' do
- result = run_generator(['Metafield', 'resource:references{polymorphic}'])
+ result = run_generator(['CustomField', 'resource:references{polymorphic}'])
expect(result[:migration]).to include('polymorphic: true')
end
diff --git a/spree/core/spec/lib/spree/core_environment_spec.rb b/spree/core/spec/lib/spree/core_environment_spec.rb
index 5def77168b..8143de079d 100644
--- a/spree/core/spec/lib/spree/core_environment_spec.rb
+++ b/spree/core/spec/lib/spree/core_environment_spec.rb
@@ -68,14 +68,14 @@ RSpec.describe 'Spree environment accessors' do
expect(Spree.translatable_resources).to be_an(Array)
end
- it 'provides access to metafields.types' do
- expect(Spree.metafields.types).to eq(Rails.application.config.spree.metafields.types)
- expect(Spree.metafields.types).to be_an(Array)
+ it 'provides access to custom_fields.types' do
+ expect(Spree.custom_fields.types).to eq(Rails.application.config.spree.custom_fields.types)
+ expect(Spree.custom_fields.types).to be_an(Array)
end
- it 'provides access to metafields.enabled_resources' do
- expect(Spree.metafields.enabled_resources).to eq(Rails.application.config.spree.metafields.enabled_resources)
- expect(Spree.metafields.enabled_resources).to be_an(Array)
+ it 'provides access to custom_fields.enabled_resources' do
+ expect(Spree.custom_fields.enabled_resources).to eq(Rails.application.config.spree.custom_fields.enabled_resources)
+ expect(Spree.custom_fields.enabled_resources).to be_an(Array)
end
it 'provides access to analytics.events' do
diff --git a/spree/core/spec/lib/tasks/categories_and_collections_spec.rb b/spree/core/spec/lib/tasks/categories_and_collections_spec.rb
index 5a24bef344..bd0eed8a44 100644
--- a/spree/core/spec/lib/tasks/categories_and_collections_spec.rb
+++ b/spree/core/spec/lib/tasks/categories_and_collections_spec.rb
@@ -80,8 +80,8 @@ describe 'spree:migrate_taxons_to_categories_and_collections' do
end
describe 'backfilling renamed class-name strings' do
- let!(:metafield) do
- create(:metafield).tap { |m| m.update_column(:resource_type, 'Spree::Taxon') }
+ let!(:custom_field) do
+ create(:custom_field).tap { |m| m.update_column(:resource_type, 'Spree::Taxon') }
end
let!(:promotion_rule) do
create(:promotion_rule_taxon).tap { |r| r.update_column(:type, 'Spree::Promotion::Rules::Taxon') }
@@ -90,7 +90,7 @@ describe 'spree:migrate_taxons_to_categories_and_collections' do
it 'rewrites Spree::Taxon* strings to Spree::Category*' do
subject.invoke
- expect(metafield.reload.resource_type).to eq('Spree::Category')
+ expect(custom_field.reload.resource_type).to eq('Spree::Category')
expect(Spree::PromotionRule.where(id: promotion_rule.id).pick(:type)).to eq('Spree::Promotion::Rules::Category')
end
end
diff --git a/spree/core/spec/lib/tasks/six_zero_data_migrations_spec.rb b/spree/core/spec/lib/tasks/six_zero_data_migrations_spec.rb
index d30aef53b8..a01a163184 100644
--- a/spree/core/spec/lib/tasks/six_zero_data_migrations_spec.rb
+++ b/spree/core/spec/lib/tasks/six_zero_data_migrations_spec.rb
@@ -56,7 +56,7 @@ describe '6.0 data migration tasks' do
Spree::Calculator::Shipping::DigitalDelivery.create!(calculable: digital_method)
# A 5.x row as it arrives post-migration: storefront_visible at the
# column default, display_on still holding the real value.
- digital_method.update_columns(fulfillment_type: nil, fulfillment_provider: nil, storefront_visible: true, display_on: 'back_end')
+ digital_method.update_columns(fulfillment_type: nil, fulfillment_provider: nil, storefront_visible: true, storefront_visible: false)
run_task('spree:migrate_shipping_to_delivery')
@@ -70,7 +70,7 @@ describe '6.0 data migration tasks' do
# re-run cannot undo a visibility change an admin made in the meantime.
it 'does not revert a later admin visibility change on re-run' do
method = create(:shipping_method)
- method.update_columns(storefront_visible: true, display_on: 'back_end')
+ method.update_columns(storefront_visible: true, storefront_visible: false)
run_task('spree:migrate_shipping_to_delivery')
expect(method.reload.read_attribute(:storefront_visible)).to be(false)
diff --git a/spree/core/spec/models/concerns/spree/metafield_filterable_spec.rb b/spree/core/spec/models/concerns/spree/custom_field_filterable_spec.rb
similarity index 71%
rename from spree/core/spec/models/concerns/spree/metafield_filterable_spec.rb
rename to spree/core/spec/models/concerns/spree/custom_field_filterable_spec.rb
index a9cfd885b2..e354a044f3 100644
--- a/spree/core/spec/models/concerns/spree/metafield_filterable_spec.rb
+++ b/spree/core/spec/models/concerns/spree/custom_field_filterable_spec.rb
@@ -2,7 +2,7 @@
require 'spec_helper'
-RSpec.describe Spree::MetafieldFilterable do
+RSpec.describe Spree::CustomFieldFilterable do
let(:store) { @default_store }
let!(:product_1) { create(:product, name: 'Blue Shirt') }
@@ -10,28 +10,28 @@ RSpec.describe Spree::MetafieldFilterable do
let!(:product_3) { create(:product, name: 'Blue Jacket') }
let!(:material) do
- create(:metafield_definition, :short_text_field, :searchable, namespace: 'custom', key: 'material')
+ create(:custom_field_definition, :short_text_field, :searchable, namespace: 'custom', key: 'material')
end
let!(:weight) do
- create(:metafield_definition, :number_field, :sortable, namespace: 'custom', key: 'weight')
+ create(:custom_field_definition, :number_field, :sortable, namespace: 'custom', key: 'weight')
end
before do
- product_1.set_metafield(material, 'Wool-Blend')
- product_2.set_metafield(material, 'cotton')
- product_1.set_metafield(weight, '10')
- product_2.set_metafield(weight, '2')
- product_3.set_metafield(weight, '3.5')
+ product_1.set_custom_field(material, 'Wool-Blend')
+ product_2.set_custom_field(material, 'cotton')
+ product_1.set_custom_field(weight, '10')
+ product_2.set_custom_field(weight, '2')
+ product_3.set_custom_field(weight, '3.5')
end
def filter(filters)
- scope, remaining = Spree::Product.with_metafield_filters(filters)
+ scope, remaining = Spree::Product.with_custom_field_filters(filters)
[scope.to_a, remaining]
end
- describe '.with_metafield_filters' do
+ describe '.with_custom_field_filters' do
it 'returns the untouched scope and filters when no cf_* keys are present' do
- scope, remaining = Spree::Product.with_metafield_filters({'name_cont' => 'Blue'})
+ scope, remaining = Spree::Product.with_custom_field_filters({'name_cont' => 'Blue'})
expect(scope.to_a).to match_array([product_1, product_2, product_3])
expect(remaining).to eq('name_cont' => 'Blue')
@@ -70,7 +70,7 @@ RSpec.describe Spree::MetafieldFilterable do
expect(filter({'cf_custom_material_blank' => '1'}).first).to contain_exactly(product_3)
end
- it 'composes multiple metafield predicates' do
+ it 'composes multiple custom_field predicates' do
products, = filter({'cf_custom_material_present' => '1', 'cf_custom_weight_gteq' => '5'})
expect(products).to contain_exactly(product_1)
@@ -82,42 +82,42 @@ RSpec.describe Spree::MetafieldFilterable do
end
it 'leaves keys whose predicate the field type does not support for Ransack' do
- _, remaining = Spree::Product.with_metafield_filters({'cf_custom_weight_cont' => 'abc'})
+ _, remaining = Spree::Product.with_custom_field_filters({'cf_custom_weight_cont' => 'abc'})
expect(remaining).to eq('cf_custom_weight_cont' => 'abc')
end
# The schema hits the DB, so a filter hash with no cf_* keys must not pay for it.
it 'does not build a schema when no cf_* key is present' do
- expect(Spree::SearchProvider::MetafieldSchema).not_to receive(:new)
+ expect(Spree::SearchProvider::CustomFieldSchema).not_to receive(:new)
- Spree::Product.with_metafield_filters({'name_cont' => 'Blue'})
+ Spree::Product.with_custom_field_filters({'name_cont' => 'Blue'})
end
end
- describe '.metafield_value_expression' do
+ describe '.custom_field_value_expression' do
let(:connection) { Spree::Product.connection }
# Identifier quoting differs per adapter (backticks on MySQL, double
# quotes elsewhere), so build the expected column reference from the
# connection rather than hardcoding either form.
let(:quoted_column) do
- "#{connection.quote_table_name(Spree::Metafield.table_name)}.#{connection.quote_column_name('value')}"
+ "#{connection.quote_table_name(Spree::CustomField.table_name)}.#{connection.quote_column_name('value')}"
end
def to_sql(node)
connection.visitor.compile(node, Arel::Collectors::SQLString.new)
end
- it 'casts numeric metafields for the current adapter' do
- expression = Spree::Product.metafield_value_expression(Spree::Metafield.arel_table[:value], 'number')
+ it 'casts numeric custom_fields for the current adapter' do
+ expression = Spree::Product.custom_field_value_expression(Spree::CustomField.arel_table[:value], 'number')
# PostgreSQL renders `CAST(x AS numeric)`, MySQL `CAST(x AS DECIMAL(30, 10))`,
# SQLite `CAST(x AS REAL)` — all wrap the column in a cast.
expect(to_sql(expression)).to match(/\ACAST\(#{Regexp.escape(quoted_column)} AS .+\)\z/)
end
- it 'leaves text metafields uncast' do
- expression = Spree::Product.metafield_value_expression(Spree::Metafield.arel_table[:value], 'short_text')
+ it 'leaves text custom_fields uncast' do
+ expression = Spree::Product.custom_field_value_expression(Spree::CustomField.arel_table[:value], 'short_text')
expect(to_sql(expression)).to eq(quoted_column)
end
diff --git a/spree/core/spec/models/concerns/spree/has_custom_fields_spec.rb b/spree/core/spec/models/concerns/spree/has_custom_fields_spec.rb
new file mode 100644
index 0000000000..886d83d84e
--- /dev/null
+++ b/spree/core/spec/models/concerns/spree/has_custom_fields_spec.rb
@@ -0,0 +1,348 @@
+require 'spec_helper'
+
+RSpec.describe Spree::HasCustomFields, type: :concern do
+ let(:product) { create(:product) }
+
+ describe 'associations' do
+ it 'has many custom_fields' do
+ expect(product).to respond_to(:custom_fields)
+ end
+
+ it 'has many storefront_custom_fields' do
+ expect(product).to respond_to(:storefront_custom_fields)
+ end
+ end
+
+ describe '.with_custom_field_key' do
+ let!(:definition) { create(:custom_field_definition, namespace: 'custom', key: 'foo', resource_type: 'Spree::Product') }
+ let!(:custom_field) { create(:custom_field, resource: product, custom_field_definition: definition) }
+
+ it 'returns products with the given custom_field key' do
+ expect(Spree::Product.with_custom_field_key('custom.foo')).to include(product)
+ end
+
+ it 'does not return products without the given custom_field key' do
+ other_product = create(:product)
+ expect(Spree::Product.with_custom_field_key('custom.foo')).not_to include(other_product)
+ end
+ end
+
+ describe '.with_custom_field_key_value' do
+ let!(:definition) { create(:custom_field_definition, namespace: 'custom', key: 'bar', resource_type: 'Spree::Product') }
+ let!(:custom_field) { create(:custom_field, resource: product, custom_field_definition: definition, value: 'baz') }
+
+ it 'returns products with the given custom_field key and value' do
+ expect(Spree::Product.with_custom_field_key_value('custom.bar', 'baz')).to include(product)
+ end
+
+ it 'does not return products with the key but different value' do
+ expect(Spree::Product.with_custom_field_key_value('custom.bar', 'other')).not_to include(product)
+ end
+ end
+
+ describe '#set_custom_field and #get_custom_field' do
+ it 'creates and retrieves a custom_field by key_with_namespace' do
+ expect {
+ product.set_custom_field('custom.foo', 'bar')
+ }.to change { product.custom_fields.count }.by(1)
+
+ custom_field = product.get_custom_field('custom.foo')
+ expect(custom_field).to be_present
+ expect(custom_field.value).to eq('bar')
+ expect(custom_field.custom_field_definition.namespace).to eq('custom')
+ expect(custom_field.custom_field_definition.key).to eq('foo')
+ end
+
+ it 'updates the value if the custom_field already exists' do
+ product.set_custom_field('custom.foo', 'bar')
+ expect {
+ product.set_custom_field('custom.foo', 'baz')
+ }.not_to change { product.custom_fields.count }
+ expect(product.get_custom_field('custom.foo').value).to eq('baz')
+ end
+
+ it 'accepts a CustomFieldDefinition instance' do
+ definition = create(:custom_field_definition, namespace: 'custom', key: 'bar', resource_type: 'Spree::Product')
+
+ product.set_custom_field(definition, 'value-from-instance')
+
+ expect(product.get_custom_field('custom.bar').value).to eq('value-from-instance')
+ end
+
+ it 'accepts a prefixed-id String' do
+ definition = create(:custom_field_definition, namespace: 'custom', key: 'pref', resource_type: 'Spree::Product')
+
+ product.set_custom_field(definition.prefixed_id, 'value-from-prefixed')
+
+ expect(product.get_custom_field('custom.pref').value).to eq('value-from-prefixed')
+ end
+
+ it 'accepts a raw integer id' do
+ definition = create(:custom_field_definition, namespace: 'custom', key: 'intid', resource_type: 'Spree::Product')
+
+ product.set_custom_field(definition.id, 'value-from-int')
+
+ expect(product.get_custom_field('custom.intid').value).to eq('value-from-int')
+ end
+
+ it 'destroys an existing custom_field when the value is nil' do
+ product.set_custom_field('custom.foo', 'bar')
+ expect {
+ product.set_custom_field('custom.foo', nil)
+ }.to change { product.custom_fields.count }.by(-1)
+ end
+
+ it 'destroys an existing custom_field when the value is an empty/whitespace string' do
+ product.set_custom_field('custom.foo', 'bar')
+ expect {
+ product.set_custom_field('custom.foo', ' ')
+ }.to change { product.custom_fields.count }.by(-1)
+ end
+
+ it 'preserves Boolean false (not blank)' do
+ definition = create(:custom_field_definition, namespace: 'custom', key: 'flag', resource_type: 'Spree::Product', field_type: 'Spree::CustomFields::Boolean')
+
+ product.set_custom_field(definition, false)
+
+ mf = product.get_custom_field('custom.flag')
+ expect(mf).to be_present
+ # Boolean custom_field serializes to a stringified value depending on adapter.
+ expect(mf.value).to be_in(['false', 'f', false])
+ end
+
+ it 'preserves Numeric 0 (not blank)' do
+ definition = create(:custom_field_definition, namespace: 'custom', key: 'count', resource_type: 'Spree::Product', field_type: 'Spree::CustomFields::Number')
+
+ product.set_custom_field(definition, 0)
+
+ mf = product.get_custom_field('custom.count')
+ expect(mf).to be_present
+ expect(mf.value.to_s).to eq('0')
+ end
+
+ it 'preserves an empty Array value (JSON custom_field)' do
+ definition = create(:custom_field_definition, namespace: 'custom', key: 'tags_json', resource_type: 'Spree::Product', field_type: 'Spree::CustomFields::Json')
+
+ product.set_custom_field(definition, '[]')
+
+ mf = product.get_custom_field('custom.tags_json')
+ expect(mf).to be_present
+ expect(mf.value).to eq('[]')
+ end
+
+ it 'preserves an empty Hash value (JSON custom_field)' do
+ definition = create(:custom_field_definition, namespace: 'custom', key: 'meta_json', resource_type: 'Spree::Product', field_type: 'Spree::CustomFields::Json')
+
+ product.set_custom_field(definition, '{}')
+
+ mf = product.get_custom_field('custom.meta_json')
+ expect(mf).to be_present
+ expect(mf.value).to eq('{}')
+ end
+
+ it 'raises ArgumentError on a prefixed-id-shaped string that decodes to no real definition' do
+ # Sqids decodes any alphanumeric string to *some* integer; the
+ # existence check ensures we don't silently address a phantom id.
+ expect {
+ product.set_custom_field('cfdef_garbage', 'x')
+ }.to raise_error(ArgumentError, /Unknown custom field definition id/)
+ end
+
+ it 'raises ArgumentError on a bare non-numeric string' do
+ expect {
+ product.set_custom_field('nope', 'x')
+ }.to raise_error(ArgumentError, /Invalid custom field definition reference/)
+ end
+
+ it 'raises ArgumentError on a non-supported type' do
+ expect {
+ product.set_custom_field(Object.new, 'x')
+ }.to raise_error(ArgumentError, /Invalid definition_or_key/)
+ end
+ end
+
+ describe '#has_custom_field?' do
+ let!(:definition) { create(:custom_field_definition, namespace: 'custom', key: 'foo', resource_type: 'Spree::Product') }
+
+ it 'returns true if custom_field exists for string key_with_namespace' do
+ product.set_custom_field('custom.foo', 'bar')
+ expect(product.has_custom_field?('custom.foo')).to be true
+ end
+
+ it 'returns false if custom_field does not exist for string key_with_namespace' do
+ expect(product.has_custom_field?('custom.foo')).to be false
+ end
+
+ it 'returns true if custom_field exists for CustomFieldDefinition' do
+ product.set_custom_field('custom.foo', 'bar')
+ expect(product.has_custom_field?(definition)).to be true
+ end
+
+ it 'returns false if custom_field does not exist for CustomFieldDefinition' do
+ expect(product.has_custom_field?(definition)).to be false
+ end
+
+ it 'raises ArgumentError for invalid key_with_namespace' do
+ expect {
+ product.has_custom_field?(123)
+ }.to raise_error(ArgumentError)
+ end
+ end
+
+ describe 'accepts_nested_attributes_for :custom_fields' do
+ let!(:definition) { create(:custom_field_definition, namespace: 'custom', key: 'foo', resource_type: 'Spree::Product') }
+
+ it 'creates custom_field via nested attributes' do
+ attrs = {
+ custom_fields_attributes: [
+ {
+ custom_field_definition_id: definition.id,
+ value: 'nested value',
+ type: definition.field_type_class_name
+ }
+ ]
+ }
+ expect {
+ product.update(attrs)
+ }.to change { product.custom_fields.count }.by(1)
+ expect(product.custom_fields.last.value).to eq('nested value')
+ end
+
+ it 'rejects custom_field if custom_field_definition_id is blank' do
+ attrs = {
+ custom_fields_attributes: [
+ {
+ custom_field_definition_id: nil,
+ value: 'should not be saved',
+ type: definition.field_type_class_name
+ }
+ ]
+ }
+ expect {
+ product.update(attrs)
+ }.not_to change { product.custom_fields.count }
+ end
+
+ it 'rejects custom_field if id and value are blank' do
+ attrs = {
+ custom_fields_attributes: [
+ {
+ custom_field_definition_id: definition.id,
+ value: '',
+ id: nil,
+ type: definition.field_type_class_name
+ }
+ ]
+ }
+ expect {
+ product.update(attrs)
+ }.not_to change { product.custom_fields.count }
+ end
+
+ context 'auto-destroy custom_fields with empty values' do
+ let!(:custom_field) do
+ create(:custom_field, resource: product, custom_field_definition: definition,
+ value: 'initial value', type: definition.field_type_class_name)
+ end
+
+ it 'destroys existing custom_field when value is set to empty string' do
+ attrs = {
+ custom_fields_attributes: [
+ {
+ id: custom_field.id,
+ custom_field_definition_id: definition.id,
+ value: '',
+ type: definition.field_type_class_name
+ }
+ ]
+ }
+ expect {
+ product.update(attrs)
+ }.to change { product.custom_fields.count }.by(-1)
+ end
+
+ it 'destroys existing custom_field when value is set to nil' do
+ attrs = {
+ custom_fields_attributes: [
+ {
+ id: custom_field.id,
+ custom_field_definition_id: definition.id,
+ value: nil,
+ type: definition.field_type_class_name
+ }
+ ]
+ }
+ expect {
+ product.update(attrs)
+ }.to change { product.custom_fields.count }.by(-1)
+ end
+
+ it 'updates existing custom_field when value is not empty' do
+ attrs = {
+ custom_fields_attributes: [
+ {
+ id: custom_field.id,
+ custom_field_definition_id: definition.id,
+ value: 'updated value',
+ type: definition.field_type_class_name
+ }
+ ]
+ }
+ expect {
+ product.update(attrs)
+ }.not_to change { product.custom_fields.count }
+ expect(custom_field.reload.value).to eq('updated value')
+ end
+
+ it 'handles multiple custom_fields correctly' do
+ other_definition = create(:custom_field_definition, namespace: 'custom', key: 'bar', resource_type: 'Spree::Product')
+ other_custom_field = create(:custom_field, resource: product, custom_field_definition: other_definition,
+ value: 'other value', type: other_definition.field_type_class_name)
+
+ attrs = {
+ custom_fields_attributes: [
+ {
+ id: custom_field.id,
+ custom_field_definition_id: definition.id,
+ value: '',
+ type: definition.field_type_class_name
+ },
+ {
+ id: other_custom_field.id,
+ custom_field_definition_id: other_definition.id,
+ value: 'updated other value',
+ type: other_definition.field_type_class_name
+ }
+ ]
+ }
+ expect {
+ product.update(attrs)
+ }.to change { product.custom_fields.count }.by(-1)
+ expect(product.custom_fields.pluck(:id)).not_to include(custom_field.id)
+ expect(other_custom_field.reload.value).to eq('updated other value')
+ end
+ end
+ end
+
+ describe '#metafields_attributes=' do
+ let(:definition) { create(:custom_field_definition, namespace: 'custom', key: 'legacy', resource_type: 'Spree::Product') }
+
+ # Legacy payloads name the foreign key `metafield_definition_id`, which the
+ # current writer would otherwise reject and silently drop.
+ it 'accepts the legacy definition key' do
+ expect {
+ product.metafields_attributes = [{ metafield_definition_id: definition.id, value: 'legacy value' }]
+ product.save!
+ }.to change { product.custom_fields.count }.by(1)
+
+ expect(product.get_custom_field('custom.legacy').value).to eq('legacy value')
+ end
+
+ it 'still accepts the current definition key' do
+ expect {
+ product.metafields_attributes = [{ custom_field_definition_id: definition.id, value: 'current value' }]
+ product.save!
+ }.to change { product.custom_fields.count }.by(1)
+ end
+ end
+end
diff --git a/spree/core/spec/models/concerns/spree/metafields_spec.rb b/spree/core/spec/models/concerns/spree/metafields_spec.rb
deleted file mode 100644
index 2ee2898027..0000000000
--- a/spree/core/spec/models/concerns/spree/metafields_spec.rb
+++ /dev/null
@@ -1,336 +0,0 @@
-require 'spec_helper'
-
-RSpec.describe Spree::Metafields, type: :concern do
- let(:product) { create(:product) }
-
- describe 'associations' do
- it 'has many metafields' do
- expect(product).to respond_to(:metafields)
- end
-
- it 'has many public_metafields' do
- expect(product).to respond_to(:public_metafields)
- end
-
- it 'has many private_metafields' do
- expect(product).to respond_to(:private_metafields)
- end
- end
-
- describe '.with_metafield_key' do
- let!(:definition) { create(:metafield_definition, namespace: 'custom', key: 'foo', resource_type: 'Spree::Product') }
- let!(:metafield) { create(:metafield, resource: product, metafield_definition: definition) }
-
- it 'returns products with the given metafield key' do
- expect(Spree::Product.with_metafield_key('custom.foo')).to include(product)
- end
-
- it 'does not return products without the given metafield key' do
- other_product = create(:product)
- expect(Spree::Product.with_metafield_key('custom.foo')).not_to include(other_product)
- end
- end
-
- describe '.with_metafield_key_value' do
- let!(:definition) { create(:metafield_definition, namespace: 'custom', key: 'bar', resource_type: 'Spree::Product') }
- let!(:metafield) { create(:metafield, resource: product, metafield_definition: definition, value: 'baz') }
-
- it 'returns products with the given metafield key and value' do
- expect(Spree::Product.with_metafield_key_value('custom.bar', 'baz')).to include(product)
- end
-
- it 'does not return products with the key but different value' do
- expect(Spree::Product.with_metafield_key_value('custom.bar', 'other')).not_to include(product)
- end
- end
-
- describe '#set_metafield and #get_metafield' do
- it 'creates and retrieves a metafield by key_with_namespace' do
- expect {
- product.set_metafield('custom.foo', 'bar')
- }.to change { product.metafields.count }.by(1)
-
- metafield = product.get_metafield('custom.foo')
- expect(metafield).to be_present
- expect(metafield.value).to eq('bar')
- expect(metafield.metafield_definition.namespace).to eq('custom')
- expect(metafield.metafield_definition.key).to eq('foo')
- end
-
- it 'updates the value if the metafield already exists' do
- product.set_metafield('custom.foo', 'bar')
- expect {
- product.set_metafield('custom.foo', 'baz')
- }.not_to change { product.metafields.count }
- expect(product.get_metafield('custom.foo').value).to eq('baz')
- end
-
- it 'accepts a MetafieldDefinition instance' do
- definition = create(:metafield_definition, namespace: 'custom', key: 'bar', resource_type: 'Spree::Product')
-
- product.set_metafield(definition, 'value-from-instance')
-
- expect(product.get_metafield('custom.bar').value).to eq('value-from-instance')
- end
-
- it 'accepts a prefixed-id String' do
- definition = create(:metafield_definition, namespace: 'custom', key: 'pref', resource_type: 'Spree::Product')
-
- product.set_metafield(definition.prefixed_id, 'value-from-prefixed')
-
- expect(product.get_metafield('custom.pref').value).to eq('value-from-prefixed')
- end
-
- it 'accepts a raw integer id' do
- definition = create(:metafield_definition, namespace: 'custom', key: 'intid', resource_type: 'Spree::Product')
-
- product.set_metafield(definition.id, 'value-from-int')
-
- expect(product.get_metafield('custom.intid').value).to eq('value-from-int')
- end
-
- it 'destroys an existing metafield when the value is nil' do
- product.set_metafield('custom.foo', 'bar')
- expect {
- product.set_metafield('custom.foo', nil)
- }.to change { product.metafields.count }.by(-1)
- end
-
- it 'destroys an existing metafield when the value is an empty/whitespace string' do
- product.set_metafield('custom.foo', 'bar')
- expect {
- product.set_metafield('custom.foo', ' ')
- }.to change { product.metafields.count }.by(-1)
- end
-
- it 'preserves Boolean false (not blank)' do
- definition = create(:metafield_definition, namespace: 'custom', key: 'flag', resource_type: 'Spree::Product', metafield_type: 'Spree::Metafields::Boolean')
-
- product.set_metafield(definition, false)
-
- mf = product.get_metafield('custom.flag')
- expect(mf).to be_present
- # Boolean metafield serializes to a stringified value depending on adapter.
- expect(mf.value).to be_in(['false', 'f', false])
- end
-
- it 'preserves Numeric 0 (not blank)' do
- definition = create(:metafield_definition, namespace: 'custom', key: 'count', resource_type: 'Spree::Product', metafield_type: 'Spree::Metafields::Number')
-
- product.set_metafield(definition, 0)
-
- mf = product.get_metafield('custom.count')
- expect(mf).to be_present
- expect(mf.value.to_s).to eq('0')
- end
-
- it 'preserves an empty Array value (JSON metafield)' do
- definition = create(:metafield_definition, namespace: 'custom', key: 'tags_json', resource_type: 'Spree::Product', metafield_type: 'Spree::Metafields::Json')
-
- product.set_metafield(definition, '[]')
-
- mf = product.get_metafield('custom.tags_json')
- expect(mf).to be_present
- expect(mf.value).to eq('[]')
- end
-
- it 'preserves an empty Hash value (JSON metafield)' do
- definition = create(:metafield_definition, namespace: 'custom', key: 'meta_json', resource_type: 'Spree::Product', metafield_type: 'Spree::Metafields::Json')
-
- product.set_metafield(definition, '{}')
-
- mf = product.get_metafield('custom.meta_json')
- expect(mf).to be_present
- expect(mf.value).to eq('{}')
- end
-
- it 'raises ArgumentError on a prefixed-id-shaped string that decodes to no real definition' do
- # Sqids decodes any alphanumeric string to *some* integer; the
- # existence check ensures we don't silently address a phantom id.
- expect {
- product.set_metafield('cfdef_garbage', 'x')
- }.to raise_error(ArgumentError, /Unknown metafield definition id/)
- end
-
- it 'raises ArgumentError on a bare non-numeric string' do
- expect {
- product.set_metafield('nope', 'x')
- }.to raise_error(ArgumentError, /Invalid metafield definition reference/)
- end
-
- it 'raises ArgumentError on a non-supported type' do
- expect {
- product.set_metafield(Object.new, 'x')
- }.to raise_error(ArgumentError, /Invalid definition_or_key/)
- end
- end
-
- describe '#has_metafield?' do
- let!(:definition) { create(:metafield_definition, namespace: 'custom', key: 'foo', resource_type: 'Spree::Product') }
-
- it 'returns true if metafield exists for string key_with_namespace' do
- product.set_metafield('custom.foo', 'bar')
- expect(product.has_metafield?('custom.foo')).to be true
- end
-
- it 'returns false if metafield does not exist for string key_with_namespace' do
- expect(product.has_metafield?('custom.foo')).to be false
- end
-
- it 'returns true if metafield exists for MetafieldDefinition' do
- product.set_metafield('custom.foo', 'bar')
- expect(product.has_metafield?(definition)).to be true
- end
-
- it 'returns false if metafield does not exist for MetafieldDefinition' do
- expect(product.has_metafield?(definition)).to be false
- end
-
- it 'raises ArgumentError for invalid key_with_namespace' do
- expect {
- product.has_metafield?(123)
- }.to raise_error(ArgumentError)
- end
- end
-
- describe 'accepts_nested_attributes_for :metafields' do
- let!(:definition) { create(:metafield_definition, namespace: 'custom', key: 'foo', resource_type: 'Spree::Product') }
-
- it 'creates metafield via nested attributes' do
- attrs = {
- metafields_attributes: [
- {
- metafield_definition_id: definition.id,
- value: 'nested value',
- type: definition.metafield_type
- }
- ]
- }
- expect {
- product.update(attrs)
- }.to change { product.metafields.count }.by(1)
- expect(product.metafields.last.value).to eq('nested value')
- end
-
- it 'rejects metafield if metafield_definition_id is blank' do
- attrs = {
- metafields_attributes: [
- {
- metafield_definition_id: nil,
- value: 'should not be saved',
- type: definition.metafield_type
- }
- ]
- }
- expect {
- product.update(attrs)
- }.not_to change { product.metafields.count }
- end
-
- it 'rejects metafield if id and value are blank' do
- attrs = {
- metafields_attributes: [
- {
- metafield_definition_id: definition.id,
- value: '',
- id: nil,
- type: definition.metafield_type
- }
- ]
- }
- expect {
- product.update(attrs)
- }.not_to change { product.metafields.count }
- end
-
- context 'auto-destroy metafields with empty values' do
- let!(:metafield) do
- product.metafields.create!(
- metafield_definition: definition,
- value: 'initial value',
- type: definition.metafield_type
- )
- end
-
- it 'destroys existing metafield when value is set to empty string' do
- attrs = {
- metafields_attributes: [
- {
- id: metafield.id,
- metafield_definition_id: definition.id,
- value: '',
- type: definition.metafield_type
- }
- ]
- }
- expect {
- product.update(attrs)
- }.to change { product.metafields.count }.by(-1)
- end
-
- it 'destroys existing metafield when value is set to nil' do
- attrs = {
- metafields_attributes: [
- {
- id: metafield.id,
- metafield_definition_id: definition.id,
- value: nil,
- type: definition.metafield_type
- }
- ]
- }
- expect {
- product.update(attrs)
- }.to change { product.metafields.count }.by(-1)
- end
-
- it 'updates existing metafield when value is not empty' do
- attrs = {
- metafields_attributes: [
- {
- id: metafield.id,
- metafield_definition_id: definition.id,
- value: 'updated value',
- type: definition.metafield_type
- }
- ]
- }
- expect {
- product.update(attrs)
- }.not_to change { product.metafields.count }
- expect(metafield.reload.value).to eq('updated value')
- end
-
- it 'handles multiple metafields correctly' do
- other_definition = create(:metafield_definition, namespace: 'custom', key: 'bar', resource_type: 'Spree::Product')
- other_metafield = product.metafields.create!(
- metafield_definition: other_definition,
- value: 'other value',
- type: other_definition.metafield_type
- )
-
- attrs = {
- metafields_attributes: [
- {
- id: metafield.id,
- metafield_definition_id: definition.id,
- value: '',
- type: definition.metafield_type
- },
- {
- id: other_metafield.id,
- metafield_definition_id: other_definition.id,
- value: 'updated other value',
- type: other_definition.metafield_type
- }
- ]
- }
- expect {
- product.update(attrs)
- }.to change { product.metafields.count }.by(-1)
- expect(product.metafields.pluck(:id)).not_to include(metafield.id)
- expect(other_metafield.reload.value).to eq('updated other value')
- end
- end
- end
-end
diff --git a/spree/core/spec/models/concerns/spree/purchase/payment_processing_spec.rb b/spree/core/spec/models/concerns/spree/purchase/payment_processing_spec.rb
index 6d842819c7..c74c96fc75 100644
--- a/spree/core/spec/models/concerns/spree/purchase/payment_processing_spec.rb
+++ b/spree/core/spec/models/concerns/spree/purchase/payment_processing_spec.rb
@@ -138,7 +138,7 @@ RSpec.shared_examples 'a payment processing host' do
it 'lists active front-end methods available for this record' do
available = create(:credit_card_payment_method, store: store)
inactive = create(:credit_card_payment_method, store: store, active: false)
- back_office_only = create(:credit_card_payment_method, store: store, display_on: 'back_end')
+ back_office_only = create(:credit_card_payment_method, store: store, storefront_visible: false)
expect(record.payment_methods).to include(available)
expect(record.payment_methods).not_to include(inactive)
diff --git a/spree/core/spec/models/spree/asset_spec.rb b/spree/core/spec/models/spree/asset_spec.rb
index 98247b430d..9a4cda1851 100644
--- a/spree/core/spec/models/spree/asset_spec.rb
+++ b/spree/core/spec/models/spree/asset_spec.rb
@@ -188,13 +188,13 @@ describe Spree::Asset, type: :model do
context 'external URL' do
before do
- create(:metafield_definition, namespace: 'external', key: 'url', resource_type: 'Spree::Asset')
+ create(:custom_field_definition, namespace: 'external', key: 'url', resource_type: 'Spree::Asset')
end
describe '.with_external_url' do
it 'returns assets with the given external URL' do
asset = create(:asset)
- asset.set_metafield('external.url', 'https://example.com/Example-Image-001.png')
+ asset.set_custom_field('external.url', 'https://example.com/Example-Image-001.png')
expect(described_class.with_external_url('https://example.com/Example-Image-001.png')).to include(asset)
end
@@ -206,7 +206,7 @@ describe Spree::Asset, type: :model do
describe '#external_url' do
it 'returns the external URL' do
asset = create(:asset)
- asset.set_metafield('external.url', 'https://example.com/Example-Image-001.png')
+ asset.set_custom_field('external.url', 'https://example.com/Example-Image-001.png')
expect(asset.external_url).to eq('https://example.com/Example-Image-001.png')
end
diff --git a/spree/core/spec/models/spree/concerns/display_on_spec.rb b/spree/core/spec/models/spree/concerns/display_on_spec.rb
index bc9c506992..3f722ad96c 100644
--- a/spree/core/spec/models/spree/concerns/display_on_spec.rb
+++ b/spree/core/spec/models/spree/concerns/display_on_spec.rb
@@ -3,7 +3,7 @@
require 'spec_helper'
RSpec.describe Spree::DisplayOn do
- # PaymentMethod and MetafieldDefinition are the remaining hosts and
+ # PaymentMethod and CustomFieldDefinition are the remaining hosts and
# include the concern identically. DeliveryMethod moved off it in 6.0 —
# it owns a real storefront_visible column.
let(:payment_method) { build(:check_payment_method) }
@@ -56,8 +56,8 @@ RSpec.describe Spree::DisplayOn do
end
describe 'scopes' do
- let!(:storefront_method) { create(:check_payment_method, display_on: 'both') }
- let!(:admin_only_method) { create(:check_payment_method, display_on: 'back_end') }
+ let!(:storefront_method) { create(:check_payment_method) }
+ let!(:admin_only_method) { create(:check_payment_method, storefront_visible: false) }
describe '.storefront_visible' do
it 'returns methods where display_on != back_end' do
diff --git a/spree/core/spec/models/spree/custom_field_definition_spec.rb b/spree/core/spec/models/spree/custom_field_definition_spec.rb
index 2b68ffe1a2..25d5775b4c 100644
--- a/spree/core/spec/models/spree/custom_field_definition_spec.rb
+++ b/spree/core/spec/models/spree/custom_field_definition_spec.rb
@@ -1,42 +1,199 @@
require 'spec_helper'
-RSpec.describe 'Spree::CustomFieldDefinition constant alias' do
- it 'aliases Spree::MetafieldDefinition' do
- expect(Spree::CustomFieldDefinition).to equal(Spree::MetafieldDefinition)
+RSpec.describe Spree::CustomFieldDefinition, type: :model do
+ let(:custom_field_definition) { build(:custom_field_definition) }
+
+ describe 'scopes' do
+ let!(:visible_definition) { create(:custom_field_definition, storefront_visible: true) }
+ let!(:admin_only_definition) { create(:custom_field_definition, :admin_only) }
+ let!(:product_definition) { create(:custom_field_definition, resource_type: 'Spree::Product') }
+ let!(:variant_definition) { create(:custom_field_definition, :for_variant) }
+ let!(:searchable_definition) { create(:custom_field_definition, :searchable, key: 'searchable_field') }
+ let!(:sortable_definition) { create(:custom_field_definition, :sortable, key: 'sortable_field') }
+
+ describe '.storefront_visible' do
+ it 'returns only definitions exposed to the storefront' do
+ expect(described_class.storefront_visible).to include(visible_definition)
+ expect(described_class.storefront_visible).not_to include(admin_only_definition)
+ end
+ end
+
+ describe '.admin_only' do
+ it 'returns only definitions hidden from the storefront' do
+ expect(described_class.admin_only).to include(admin_only_definition)
+ expect(described_class.admin_only).not_to include(visible_definition)
+ end
+ end
+
+ describe '.for_resource_type' do
+ it 'returns definitions for specific resource type' do
+ expect(described_class.for_resource_type('Spree::Product')).to include(product_definition)
+ expect(described_class.for_resource_type('Spree::Product')).not_to include(variant_definition)
+
+ expect(described_class.for_resource_type('Spree::Variant')).to include(variant_definition)
+ expect(described_class.for_resource_type('Spree::Variant')).not_to include(product_definition)
+ end
+ end
+
+ describe '.searchable' do
+ it 'returns only searchable definitions' do
+ expect(described_class.searchable).to include(searchable_definition)
+ expect(described_class.searchable).not_to include(product_definition)
+ end
+ end
+
+ describe '.sortable' do
+ it 'returns only sortable definitions' do
+ expect(described_class.sortable).to include(sortable_definition)
+ expect(described_class.sortable).not_to include(product_definition)
+ end
+ end
end
- it 'lets the alias serve as a model entry point' do
- defn = Spree::CustomFieldDefinition.new(
- namespace: 'specs',
- key: 'fabric',
- label: 'Fabric',
- field_type: 'Spree::Metafields::ShortText',
- resource_type: 'Spree::Product'
- )
- expect(defn).to be_valid
+ describe 'searchable / sortable validations' do
+ it 'allows searchable on short_text' do
+ definition = build(:custom_field_definition, :short_text_field, searchable: true)
+ expect(definition).to be_valid
+ end
+
+ it 'allows searchable on long_text' do
+ definition = build(:custom_field_definition, :long_text_field, searchable: true)
+ expect(definition).to be_valid
+ end
+
+ it 'rejects searchable on rich_text' do
+ definition = build(:custom_field_definition, :rich_text_field, searchable: true)
+ expect(definition).not_to be_valid
+ expect(definition.errors[:searchable].first).to include('short text', 'long text', 'number')
+ end
+
+ it 'rejects searchable on boolean' do
+ definition = build(:custom_field_definition, :boolean_field, searchable: true)
+ expect(definition).not_to be_valid
+ expect(definition.errors[:searchable]).to be_present
+ end
+
+ it 'allows sortable on short_text and number' do
+ expect(build(:custom_field_definition, :short_text_field, sortable: true)).to be_valid
+ expect(build(:custom_field_definition, :number_field, sortable: true)).to be_valid
+ end
+
+ it 'rejects sortable on long_text' do
+ definition = build(:custom_field_definition, :long_text_field, sortable: true)
+ expect(definition).not_to be_valid
+ expect(definition.errors[:sortable].first).to include('short text', 'number')
+ expect(definition.errors[:sortable].first).not_to include('long text')
+ end
+
+ it 'rejects changing field_type to a non-searchable class while searchable stays true' do
+ definition = create(:custom_field_definition, :short_text_field, searchable: true)
+ definition.field_type = 'boolean'
+ expect(definition).not_to be_valid
+ expect(definition.errors[:searchable]).to be_present
+ end
+
+ it 'rejects changing field_type to a non-sortable class while sortable stays true' do
+ definition = create(:custom_field_definition, :short_text_field, sortable: true)
+ definition.field_type = 'long_text'
+ expect(definition).not_to be_valid
+ expect(definition.errors[:sortable]).to be_present
+ end
end
- describe 'field_type input validation' do
- let(:base_attrs) do
- { namespace: 'specs', key: 'fabric', label: 'Fabric', resource_type: 'Spree::Product' }
+ describe 'field_type= with an extension-registered class' do
+ # Extensions register their own custom-field classes, which have no token
+ # in the built-in vocabulary — they are addressed by class name.
+ #
+ # The double is deliberately defined outside the Spree namespace: it stands
+ # in for a third-party extension's class, which is exactly the case that
+ # regressed. Namespacing it under Spree would not exercise it.
+ before do
+ stub_const('PluginExtension::CustomFields::Color', Class.new(Spree::CustomField))
+ allow(Spree.custom_fields).to receive(:types).
+ and_return(described_class.available_types + [PluginExtension::CustomFields::Color])
end
- it 'accepts the token form' do
- defn = Spree::CustomFieldDefinition.new(base_attrs.merge(field_type: 'short_text'))
- expect(defn).to be_valid
- expect(defn.field_type).to eq('short_text')
+ it 'accepts the registered class name' do
+ definition = build(:custom_field_definition, resource_type: 'Spree::Product')
+ definition.field_type = 'PluginExtension::CustomFields::Color'
+
+ expect(definition).to be_valid
+ expect(definition.field_type).to eq('PluginExtension::CustomFields::Color')
end
- it 'accepts the legacy class-name form' do
- defn = Spree::CustomFieldDefinition.new(base_attrs.merge(field_type: 'Spree::Metafields::ShortText'))
- expect(defn).to be_valid
- expect(defn.field_type).to eq('short_text')
+ it 'rejects a class name that is not registered' do
+ definition = build(:custom_field_definition, resource_type: 'Spree::Product')
+ definition.field_type = 'Unregistered::CustomFields::Color'
+
+ expect(definition).not_to be_valid
+ expect(definition.errors[:field_type]).to be_present
+ end
+ end
+
+ describe '.searchable_field_type_tokens / .sortable_field_type_tokens' do
+ it 'derives tokens from custom_field type class capabilities' do
+ expect(described_class.searchable_field_type_tokens).to match_array(%w[short_text long_text number])
+ expect(described_class.sortable_field_type_tokens).to match_array(%w[short_text number])
+ end
+ end
+
+ describe '#filter_key' do
+ it 'combines the namespace and key' do
+ custom_field_definition = build(:custom_field_definition, namespace: 'custom', key: 'material')
+
+ expect(custom_field_definition.filter_key).to eq('cf_custom_material')
end
+ end
+
+ describe 'filter_key uniqueness' do
+ # (a_b, c) and (a, b_c) both flatten to `cf_a_b_c`, which would make one
+ # definition unreachable via sort/filter params.
+ it 'rejects a definition whose filter_key collides across a different namespace split' do
+ create(:custom_field_definition, resource_type: 'Spree::Product', namespace: 'a_b', key: 'c')
+ colliding = build(:custom_field_definition, resource_type: 'Spree::Product', namespace: 'a', key: 'b_c')
+
+ expect(colliding).not_to be_valid
+ expect(colliding.errors[:key]).to be_present
+ end
+
+ it 'allows the same namespace/key split on a different resource type' do
+ create(:custom_field_definition, resource_type: 'Spree::Product', namespace: 'a_b', key: 'c')
+ other_resource = build(:custom_field_definition, resource_type: 'Spree::Variant', namespace: 'a', key: 'b_c')
+
+ expect(other_resource).to be_valid
+ end
+
+ it 'does not flag a persisted definition against itself' do
+ custom_field_definition = create(:custom_field_definition, namespace: 'custom', key: 'material')
+
+ custom_field_definition.label = 'Renamed'
+
+ expect(custom_field_definition).to be_valid
+ end
+ end
+
+ describe 'Ransack allowlist' do
+ it 'allows filtering by searchable and sortable' do
+ matching = create(:custom_field_definition, :short_text_field, :searchable, :sortable, key: 'ransack_match')
+ create(:custom_field_definition, :short_text_field, key: 'ransack_other')
+
+ result = described_class.ransack(searchable_eq: true, sortable_eq: true).result
+ expect(result).to include(matching)
+ expect(result.map(&:key)).not_to include('ransack_other')
+ end
+ end
+
+ describe '#csv_header_name' do
+ it 'returns the CSV header name with custom_field prefix' do
+ custom_field_definition = build(:custom_field_definition, namespace: 'custom', key: 'field1')
+ expect(custom_field_definition.csv_header_name).to eq('custom_field.custom.field1')
+ end
+ end
- it 'reports an error on `field_type` with the token vocabulary for typo input' do
- defn = Spree::CustomFieldDefinition.new(base_attrs.merge(field_type: 'shrt_text'))
- expect(defn).not_to be_valid
- expect(defn.errors[:field_type]).to include(a_string_matching(/short_text.*long_text/))
+ describe '#full_key' do
+ it 'returns the full key with namespace' do
+ custom_field_definition = build(:custom_field_definition, namespace: 'custom', key: 'field1')
+ expect(custom_field_definition.full_key).to eq('custom.field1')
end
end
end
diff --git a/spree/core/spec/models/spree/custom_field_spec.rb b/spree/core/spec/models/spree/custom_field_spec.rb
index 10a7961e4a..83f1340ad6 100644
--- a/spree/core/spec/models/spree/custom_field_spec.rb
+++ b/spree/core/spec/models/spree/custom_field_spec.rb
@@ -1,20 +1,140 @@
require 'spec_helper'
-RSpec.describe 'Spree::CustomField constant alias' do
- it 'aliases Spree::Metafield' do
- expect(Spree::CustomField).to equal(Spree::Metafield)
+RSpec.describe Spree::CustomField, type: :model do
+ context 'Callbacks' do
+ it 'sets the type from the custom_field definition' do
+ custom_field_definition = create(:custom_field_definition, field_type: 'Spree::CustomFields::ShortText')
+ custom_field = create(:custom_field, custom_field_definition: custom_field_definition, type: nil)
+ expect(custom_field.type).to eq('Spree::CustomFields::ShortText')
+ end
end
- it 'lets the alias serve as a model entry point' do
- product = create(:product)
- definition = create(:metafield_definition, :short_text_field)
-
- cf = Spree::CustomField.new(
- resource: product,
- custom_field_definition_id: definition.id,
- value: 'wool'
- )
- expect(cf.save).to be(true)
- expect(Spree::CustomField.find(cf.id).value).to eq('wool')
+ context 'Validations' do
+ it 'validates the type must match the custom_field definition' do
+ custom_field_definition = create(:custom_field_definition, field_type: 'Spree::CustomFields::ShortText')
+ custom_field = build(:custom_field, custom_field_definition: custom_field_definition, type: 'Spree::CustomFields::LongText')
+ expect(custom_field.valid?).to be false
+ end
+ end
+
+ context 'Scopes' do
+ describe '.with_key' do
+ it 'returns the custom_fields with the given key' do
+ custom_field_definition = create(:custom_field_definition, namespace: 'custom', key: 'foo')
+ custom_field = create(:custom_field, custom_field_definition: custom_field_definition)
+ other_definition = create(:custom_field_definition, namespace: 'custom', key: 'bar')
+ create(:custom_field, custom_field_definition: other_definition)
+ expect(described_class.with_key('custom', 'foo').ids).to contain_exactly(custom_field.id)
+ end
+ end
+ end
+
+ describe '#serialize_value' do
+ it 'returns the value' do
+ custom_field = build(:custom_field, value: 'Test Value')
+ expect(custom_field.serialize_value).to eq('Test Value')
+ end
+ end
+
+ describe '#csv_value' do
+ context 'for base CustomField' do
+ it 'returns the value as string' do
+ custom_field = build(:custom_field, value: 'Test Value')
+ expect(custom_field.csv_value).to eq('Test Value')
+ end
+ end
+
+ context 'for Boolean custom_field' do
+ let(:custom_field_definition) { create(:custom_field_definition, field_type: 'Spree::CustomFields::Boolean') }
+
+ it 'returns Yes for true values' do
+ custom_field = Spree::CustomFields::Boolean.new(custom_field_definition: custom_field_definition, value: 'true')
+ expect(custom_field.csv_value).to eq(Spree.t(:say_yes))
+ end
+
+ it 'returns No for false values' do
+ custom_field = Spree::CustomFields::Boolean.new(custom_field_definition: custom_field_definition, value: 'false')
+ expect(custom_field.csv_value).to eq(Spree.t(:say_no))
+ end
+ end
+
+ context 'for Number custom_field' do
+ let(:custom_field_definition) { create(:custom_field_definition, field_type: 'Spree::CustomFields::Number') }
+
+ it 'returns the number as string' do
+ custom_field = Spree::CustomFields::Number.new(custom_field_definition: custom_field_definition, value: '123.45')
+ expect(custom_field.csv_value).to eq('123.45')
+ end
+ end
+
+ context 'for Json custom_field' do
+ let(:custom_field_definition) { create(:custom_field_definition, field_type: 'Spree::CustomFields::Json') }
+
+ it 'returns the JSON string' do
+ custom_field = Spree::CustomFields::Json.new(custom_field_definition: custom_field_definition, value: '{"key": "value"}')
+ expect(custom_field.csv_value).to eq('{"key": "value"}')
+ end
+ end
+
+ context 'for ShortText custom_field' do
+ let(:custom_field_definition) { create(:custom_field_definition, field_type: 'Spree::CustomFields::ShortText') }
+
+ it 'returns the text value' do
+ custom_field = Spree::CustomFields::ShortText.new(custom_field_definition: custom_field_definition, value: 'Short text')
+ expect(custom_field.csv_value).to eq('Short text')
+ end
+ end
+
+ context 'for LongText custom_field' do
+ let(:custom_field_definition) { create(:custom_field_definition, field_type: 'Spree::CustomFields::LongText') }
+
+ it 'returns the text value' do
+ custom_field = Spree::CustomFields::LongText.new(custom_field_definition: custom_field_definition, value: 'Long text content')
+ expect(custom_field.csv_value).to eq('Long text content')
+ end
+ end
+
+ context 'for RichText custom_field' do
+ let(:custom_field_definition) { create(:custom_field_definition, field_type: 'Spree::CustomFields::RichText') }
+
+ it 'returns plain text without HTML tags' do
+ custom_field = Spree::CustomFields::RichText.new(custom_field_definition: custom_field_definition)
+ custom_field.value = '<p>Rich <strong>text</strong> content</p>'
+ expect(custom_field.csv_value).to eq('Rich text content')
+ end
+ end
+ end
+
+ describe 'resource type validation' do
+ let(:product) { create(:product) }
+
+ it 'rejects a definition belonging to another resource type' do
+ variant_definition = create(:custom_field_definition, :for_variant)
+ custom_field = build(:custom_field, resource: product, custom_field_definition: variant_definition)
+
+ expect(custom_field).not_to be_valid
+ expect(custom_field.errors[:resource_type]).to be_present
+ end
+
+ it 'accepts a definition naming an STI subclass of the resource' do
+ # Images store `Spree::Asset` in the polymorphic column, while the
+ # definition names the concrete `Spree::Image`.
+ image_definition = create(:custom_field_definition, resource_type: 'Spree::Image', key: 'sti_key')
+ custom_field = build(:custom_field, custom_field_definition: image_definition, value: 'x')
+ custom_field.resource_type = 'Spree::Asset'
+
+ custom_field.valid?
+ expect(custom_field.errors[:resource_type]).to be_empty
+ end
+ end
+
+ describe 'deprecated definition writer' do
+ it 'assigns through metafield_definition=' do
+ definition = create(:custom_field_definition)
+ custom_field = Spree::CustomField.new
+ custom_field.metafield_definition = definition
+
+ expect(custom_field.custom_field_definition).to eq(definition)
+ end
end
end
diff --git a/spree/core/spec/models/spree/metafields/boolean_spec.rb b/spree/core/spec/models/spree/custom_fields/boolean_spec.rb
similarity index 50%
rename from spree/core/spec/models/spree/metafields/boolean_spec.rb
rename to spree/core/spec/models/spree/custom_fields/boolean_spec.rb
index f1aab6cd91..6e5a2eaf7a 100644
--- a/spree/core/spec/models/spree/metafields/boolean_spec.rb
+++ b/spree/core/spec/models/spree/custom_fields/boolean_spec.rb
@@ -1,27 +1,27 @@
require 'spec_helper'
-describe Spree::Metafields::Boolean, type: :model do
- let(:metafield_definition) { create(:metafield_definition, :boolean_field) }
- let(:metafield) { described_class.new(metafield_definition: metafield_definition, value: 'true') }
+describe Spree::CustomFields::Boolean, type: :model do
+ let(:custom_field_definition) { create(:custom_field_definition, :boolean_field) }
+ let(:custom_field) { described_class.new(custom_field_definition: custom_field_definition, value: 'true') }
describe 'normalizes' do
it 'normalizes the boolean value' do
- metafield.value = '0'
- expect(metafield.value).to eq('false')
- metafield.value = '1'
- expect(metafield.value).to eq('true')
+ custom_field.value = '0'
+ expect(custom_field.value).to eq('false')
+ custom_field.value = '1'
+ expect(custom_field.value).to eq('true')
end
end
describe '#serialize_value' do
it 'returns the boolean value' do
- expect(metafield.serialize_value).to eq(true)
+ expect(custom_field.serialize_value).to eq(true)
end
end
describe '#csv_value' do
it 'returns the boolean value' do
- expect(metafield.csv_value).to eq('Yes')
+ expect(custom_field.csv_value).to eq('Yes')
end
end
diff --git a/spree/core/spec/models/spree/custom_fields/json_spec.rb b/spree/core/spec/models/spree/custom_fields/json_spec.rb
new file mode 100644
index 0000000000..e3d3a5a0f6
--- /dev/null
+++ b/spree/core/spec/models/spree/custom_fields/json_spec.rb
@@ -0,0 +1,62 @@
+require 'spec_helper'
+
+describe Spree::CustomFields::Json, type: :model do
+ let(:product) { create(:product) }
+ let(:custom_field_definition) { create(:custom_field_definition, field_type: 'Spree::CustomFields::Json') }
+ let(:custom_field) { described_class.new(custom_field_definition: custom_field_definition, value: '{"key": "value"}', resource: product) }
+
+ describe 'Validations' do
+ it 'returns false if the value is not valid JSON' do
+ custom_field.value = 'not valid json'
+ expect(custom_field.valid?).to be false
+ expect(custom_field.errors[:value]).to include(/must be valid JSON/)
+ end
+
+ it 'returns true for valid JSON object' do
+ custom_field.value = '{"key": "value", "nested": {"foo": "bar"}}'
+ expect(custom_field.valid?).to be true
+ end
+
+ it 'returns true for valid JSON array' do
+ custom_field.value = '[1, 2, 3, "test"]'
+ expect(custom_field.valid?).to be true
+ end
+
+ it 'returns true for valid JSON string' do
+ custom_field.value = '"simple string"'
+ expect(custom_field.valid?).to be true
+ end
+
+ it 'returns true for valid JSON number' do
+ custom_field.value = '123'
+ expect(custom_field.valid?).to be true
+ end
+
+ it 'returns true for valid JSON boolean' do
+ custom_field.value = 'true'
+ expect(custom_field.valid?).to be true
+ end
+
+ it 'returns true for valid JSON null' do
+ custom_field.value = 'null'
+ expect(custom_field.valid?).to be true
+ end
+ end
+
+ describe '#serialize_value' do
+ it 'returns parsed JSON object' do
+ custom_field.value = '{"key": "value", "number": 42}'
+ expect(custom_field.serialize_value).to eq({ 'key' => 'value', 'number' => 42 })
+ end
+
+ it 'returns parsed JSON array' do
+ custom_field.value = '[1, 2, 3]'
+ expect(custom_field.serialize_value).to eq([1, 2, 3])
+ end
+
+ it 'returns original value if parsing fails' do
+ allow(JSON).to receive(:parse).and_raise(JSON::ParserError)
+ expect(custom_field.serialize_value).to eq('{"key": "value"}')
+ end
+ end
+end
diff --git a/spree/core/spec/models/spree/metafields/long_text_spec.rb b/spree/core/spec/models/spree/custom_fields/long_text_spec.rb
similarity index 82%
rename from spree/core/spec/models/spree/metafields/long_text_spec.rb
rename to spree/core/spec/models/spree/custom_fields/long_text_spec.rb
index 9b438e05fe..3bd5719801 100644
--- a/spree/core/spec/models/spree/metafields/long_text_spec.rb
+++ b/spree/core/spec/models/spree/custom_fields/long_text_spec.rb
@@ -2,7 +2,7 @@
require 'spec_helper'
-describe Spree::Metafields::LongText, type: :model do
+describe Spree::CustomFields::LongText, type: :model do
describe '.searchable? / .sortable?' do
it 'is searchable but not sortable' do
expect(described_class.searchable?).to eq(true)
diff --git a/spree/core/spec/models/spree/custom_fields/number_spec.rb b/spree/core/spec/models/spree/custom_fields/number_spec.rb
new file mode 100644
index 0000000000..87d1dafd90
--- /dev/null
+++ b/spree/core/spec/models/spree/custom_fields/number_spec.rb
@@ -0,0 +1,36 @@
+require 'spec_helper'
+
+describe Spree::CustomFields::Number, type: :model do
+ let(:product) { create(:product) }
+ let(:custom_field_definition) { create(:custom_field_definition, :number_field) }
+ let(:custom_field) { described_class.new(custom_field_definition: custom_field_definition, value: '123', resource: product) }
+
+ describe 'Validations' do
+ it 'returns false if the value is not a number' do
+ custom_field.value = 'not a number'
+ expect(custom_field.valid?).to be false
+ end
+ end
+
+ describe '#serialize_value' do
+ it 'returns the number' do
+ expect(custom_field.valid?).to be true
+ expect(custom_field.serialize_value).to be_kind_of(BigDecimal)
+ expect(custom_field.serialize_value).to eq(123)
+ end
+ end
+
+ describe '#csv_value' do
+ it 'returns the number as a string' do
+ expect(custom_field.csv_value).to be_kind_of(String)
+ expect(custom_field.csv_value).to eq('123.0')
+ end
+ end
+
+ describe '.searchable? / .sortable?' do
+ it 'is searchable and sortable' do
+ expect(described_class.searchable?).to eq(true)
+ expect(described_class.sortable?).to eq(true)
+ end
+ end
+end
diff --git a/spree/core/spec/models/spree/custom_fields/rich_text_spec.rb b/spree/core/spec/models/spree/custom_fields/rich_text_spec.rb
new file mode 100644
index 0000000000..fa8b616ac0
--- /dev/null
+++ b/spree/core/spec/models/spree/custom_fields/rich_text_spec.rb
@@ -0,0 +1,43 @@
+require 'spec_helper'
+
+describe Spree::CustomFields::RichText, type: :model do
+ let(:custom_field_definition) { create(:custom_field_definition, :rich_text_field) }
+ let(:product) { create(:product) }
+ let(:custom_field) do
+ described_class.new(resource: product, custom_field_definition: custom_field_definition,
+ value: '<p>Rich text with <strong>formatting</strong></p>')
+ end
+
+ describe '#value' do
+ it 'stores HTML in the shared value column' do
+ expect(custom_field.value).to eq('<p>Rich text with <strong>formatting</strong></p>')
+ end
+ end
+
+ describe '#serialize_value' do
+ it 'returns the stored HTML' do
+ expect(custom_field.serialize_value).to eq('<p>Rich text with <strong>formatting</strong></p>')
+ end
+ end
+
+ describe '#csv_value' do
+ it 'strips the markup' do
+ expect(custom_field.csv_value).to eq('Rich text with formatting')
+ end
+
+ it 'returns an empty string when there is no value' do
+ custom_field.value = nil
+ expect(custom_field.csv_value).to eq('')
+ end
+ end
+
+ describe 'sanitization' do
+ it 'strips dangerous markup on save' do
+ custom_field.value = '<p>ok</p><script>alert(1)</script>'
+ custom_field.save!
+
+ expect(custom_field.reload.value).to include('<p>ok</p>')
+ expect(custom_field.value).not_to include('<script>')
+ end
+ end
+end
diff --git a/spree/core/spec/models/spree/metafields/short_text_spec.rb b/spree/core/spec/models/spree/custom_fields/short_text_spec.rb
similarity index 81%
rename from spree/core/spec/models/spree/metafields/short_text_spec.rb
rename to spree/core/spec/models/spree/custom_fields/short_text_spec.rb
index fd32e84ffa..addb106b5a 100644
--- a/spree/core/spec/models/spree/metafields/short_text_spec.rb
+++ b/spree/core/spec/models/spree/custom_fields/short_text_spec.rb
@@ -2,7 +2,7 @@
require 'spec_helper'
-describe Spree::Metafields::ShortText, type: :model do
+describe Spree::CustomFields::ShortText, type: :model do
describe '.searchable? / .sortable?' do
it 'is searchable and sortable' do
expect(described_class.searchable?).to eq(true)
diff --git a/spree/core/spec/models/spree/delivery_method_spec.rb b/spree/core/spec/models/spree/delivery_method_spec.rb
index fac483313b..27bd249ccd 100644
--- a/spree/core/spec/models/spree/delivery_method_spec.rb
+++ b/spree/core/spec/models/spree/delivery_method_spec.rb
@@ -210,7 +210,7 @@ describe Spree::DeliveryMethod, type: :model do
expect(visible_delivery_method.display_on).to eq('both')
expect(admin_only_delivery_method.display_on).to eq('back_end')
- method = build(:delivery_method, display_on: 'back_end')
+ method = build(:delivery_method, storefront_visible: false)
expect(method.storefront_visible).to be false
# front_end-only had no real workflow and folds into visible.
diff --git a/spree/core/spec/models/spree/export_spec.rb b/spree/core/spec/models/spree/export_spec.rb
index d55cdda285..40bf2fd6e8 100644
--- a/spree/core/spec/models/spree/export_spec.rb
+++ b/spree/core/spec/models/spree/export_spec.rb
@@ -120,12 +120,12 @@ RSpec.describe Spree::Export, :job, type: :model do
# Ransack alone has no such attribute.
context 'with a custom field filter' do
let!(:definition) do
- create(:metafield_definition, :short_text_field, :searchable, namespace: 'custom', key: 'material')
+ create(:custom_field_definition, :short_text_field, :searchable, namespace: 'custom', key: 'material')
end
let(:target) { matching_products.first }
let(:search_params) { { cf_custom_material_i_cont: 'wool' }.to_json }
- before { target.set_metafield(definition, 'Wool-Blend') }
+ before { target.set_custom_field(definition, 'Wool-Blend') }
it 'applies the custom field predicate' do
expect(export.records_to_export).to contain_exactly(target)
diff --git a/spree/core/spec/models/spree/exports/customers_spec.rb b/spree/core/spec/models/spree/exports/customers_spec.rb
index 5d1e05894f..e24b8f95ca 100644
--- a/spree/core/spec/models/spree/exports/customers_spec.rb
+++ b/spree/core/spec/models/spree/exports/customers_spec.rb
@@ -5,7 +5,7 @@ RSpec.describe Spree::Exports::Customers, type: :model do
let(:export) { described_class.new(store: store) }
describe '#csv_headers' do
- context 'when no metafields exist' do
+ context 'when no custom_fields exist' do
it 'returns customer headers' do
expected_headers = [
'First Name',
@@ -30,15 +30,15 @@ RSpec.describe Spree::Exports::Customers, type: :model do
end
end
- context 'when metafields exist' do
- let!(:metafield_definition) do
- create(:metafield_definition,
+ context 'when custom_fields exist' do
+ let!(:custom_field_definition) do
+ create(:custom_field_definition,
resource_type: export.model_class.to_s,
namespace: 'custom',
key: 'loyalty_points')
end
- it 'includes metafield headers' do
+ it 'includes custom_field headers' do
expected_headers = [
'First Name',
'Last Name',
@@ -57,7 +57,7 @@ RSpec.describe Spree::Exports::Customers, type: :model do
'Total Spent',
'Total Orders',
'Tags',
- 'metafield.custom.loyalty_points'
+ 'custom_field.custom.loyalty_points'
]
expect(export.csv_headers).to eq(expected_headers)
end
diff --git a/spree/core/spec/models/spree/exports/gift_cards_spec.rb b/spree/core/spec/models/spree/exports/gift_cards_spec.rb
index 19e427248b..3ea8d93593 100644
--- a/spree/core/spec/models/spree/exports/gift_cards_spec.rb
+++ b/spree/core/spec/models/spree/exports/gift_cards_spec.rb
@@ -29,7 +29,7 @@ RSpec.describe Spree::Exports::GiftCards, type: :model do
end
describe '#csv_headers' do
- context 'when no metafields exist' do
+ context 'when no custom_fields exist' do
it 'returns gift card headers' do
expected_headers = [
'Code',
@@ -49,15 +49,15 @@ RSpec.describe Spree::Exports::GiftCards, type: :model do
end
end
- context 'when metafields exist' do
- let!(:metafield_definition) do
- create(:metafield_definition,
+ context 'when custom_fields exist' do
+ let!(:custom_field_definition) do
+ create(:custom_field_definition,
resource_type: 'Spree::GiftCard',
namespace: 'custom',
key: 'purchase_location')
end
- it 'includes metafield headers' do
+ it 'includes custom_field headers' do
expected_headers = [
'Code',
'Amount',
@@ -71,7 +71,7 @@ RSpec.describe Spree::Exports::GiftCards, type: :model do
'Customer Last Name',
'Created At',
'Updated At',
- 'metafield.custom.purchase_location'
+ 'custom_field.custom.purchase_location'
]
expect(export.csv_headers).to eq(expected_headers)
end
diff --git a/spree/core/spec/models/spree/exports/newsletter_subscribers_spec.rb b/spree/core/spec/models/spree/exports/newsletter_subscribers_spec.rb
index ac6cd3004f..24db322b77 100644
--- a/spree/core/spec/models/spree/exports/newsletter_subscribers_spec.rb
+++ b/spree/core/spec/models/spree/exports/newsletter_subscribers_spec.rb
@@ -5,7 +5,7 @@ RSpec.describe Spree::Exports::NewsletterSubscribers, type: :model do
let(:export) { described_class.new(store: store) }
describe '#csv_headers' do
- context 'when no metafields exist' do
+ context 'when no custom_fields exist' do
it 'returns newsletter subscriber headers' do
expected_headers = [
'Email',
@@ -20,15 +20,15 @@ RSpec.describe Spree::Exports::NewsletterSubscribers, type: :model do
end
end
- context 'when metafields exist' do
- let!(:metafield_definition) do
- create(:metafield_definition,
+ context 'when custom_fields exist' do
+ let!(:custom_field_definition) do
+ create(:custom_field_definition,
resource_type: 'Spree::NewsletterSubscriber',
namespace: 'custom',
key: 'subscription_source')
end
- it 'includes metafield headers' do
+ it 'includes custom_field headers' do
expected_headers = [
'Email',
'Customer Name',
@@ -37,7 +37,7 @@ RSpec.describe Spree::Exports::NewsletterSubscribers, type: :model do
'Verified At',
'Created At',
'Updated At',
- 'metafield.custom.subscription_source'
+ 'custom_field.custom.subscription_source'
]
expect(export.csv_headers).to eq(expected_headers)
end
diff --git a/spree/core/spec/models/spree/exports/orders_spec.rb b/spree/core/spec/models/spree/exports/orders_spec.rb
index c98dd4b620..1acc114fbb 100644
--- a/spree/core/spec/models/spree/exports/orders_spec.rb
+++ b/spree/core/spec/models/spree/exports/orders_spec.rb
@@ -5,7 +5,7 @@ RSpec.describe Spree::Exports::Orders, type: :model do
let(:export) { described_class.new(store: store) }
describe '#csv_headers' do
- context 'when no metafields exist' do
+ context 'when no custom_fields exist' do
it 'returns order line item headers' do
expected_headers = [
'Number',
@@ -68,15 +68,15 @@ RSpec.describe Spree::Exports::Orders, type: :model do
end
end
- context 'when metafields exist' do
- let!(:metafield_definition) do
- create(:metafield_definition,
+ context 'when custom_fields exist' do
+ let!(:custom_field_definition) do
+ create(:custom_field_definition,
resource_type: 'Spree::Order',
namespace: 'custom',
key: 'gift_message')
end
- it 'includes metafield headers' do
+ it 'includes custom_field headers' do
expected_headers = [
'Number',
'Email',
@@ -133,7 +133,7 @@ RSpec.describe Spree::Exports::Orders, type: :model do
'Cancelled at',
'Cancelled by',
'Notes',
- 'metafield.custom.gift_message'
+ 'custom_field.custom.gift_message'
]
expect(export.csv_headers).to eq(expected_headers)
end
diff --git a/spree/core/spec/models/spree/exports/products_spec.rb b/spree/core/spec/models/spree/exports/products_spec.rb
index 0e174c6234..af0605ce64 100644
--- a/spree/core/spec/models/spree/exports/products_spec.rb
+++ b/spree/core/spec/models/spree/exports/products_spec.rb
@@ -26,7 +26,7 @@ RSpec.describe Spree::Exports::Products, type: :model do
end
describe '#csv_headers' do
- context 'when no metafields' do
+ context 'when no custom_fields' do
it 'returns product variant headers without properties' do
expected_headers = [
'product_id',
@@ -74,10 +74,10 @@ RSpec.describe Spree::Exports::Products, type: :model do
end
end
- context 'when metafields exist' do
- let!(:metafield_definition) { create(:metafield_definition, resource_type: 'Spree::Product', namespace: 'custom', key: 'field1') }
+ context 'when custom_fields exist' do
+ let!(:custom_field_definition) { create(:custom_field_definition, resource_type: 'Spree::Product', namespace: 'custom', key: 'field1') }
- it 'includes metafield headers' do
+ it 'includes custom_field headers' do
expected_headers = [
'product_id',
'sku',
@@ -119,7 +119,7 @@ RSpec.describe Spree::Exports::Products, type: :model do
'category1',
'category2',
'category3',
- 'metafield.custom.field1'
+ 'custom_field.custom.field1'
]
expect(export.csv_headers).to eq(expected_headers)
end
diff --git a/spree/core/spec/models/spree/import_mapping_spec.rb b/spree/core/spec/models/spree/import_mapping_spec.rb
index 31b335ac73..f10d2a48bd 100644
--- a/spree/core/spec/models/spree/import_mapping_spec.rb
+++ b/spree/core/spec/models/spree/import_mapping_spec.rb
@@ -159,21 +159,21 @@ RSpec.describe Spree::ImportMapping, type: :model do
end
end
- context 'when schema_field is a metafield' do
- let!(:metafield_definition) do
- create(:metafield_definition,
+ context 'when schema_field is a custom_field' do
+ let!(:custom_field_definition) do
+ create(:custom_field_definition,
namespace: 'properties',
key: 'manufacturer',
- name: 'Manufacturer',
+ label: 'Manufacturer',
resource_type: 'Spree::Product')
end
let(:mapping) do
create(:import_mapping,
import: import,
- schema_field: 'metafield.properties.manufacturer')
+ schema_field: 'custom_field.properties.manufacturer')
end
- it 'returns the metafield definition name' do
+ it 'returns the custom_field definition name' do
expect(mapping.schema_field_label).to eq('Manufacturer')
end
end
diff --git a/spree/core/spec/models/spree/import_spec.rb b/spree/core/spec/models/spree/import_spec.rb
index 3838dca39c..d2d294b873 100644
--- a/spree/core/spec/models/spree/import_spec.rb
+++ b/spree/core/spec/models/spree/import_spec.rb
@@ -183,11 +183,11 @@ RSpec.describe Spree::Import, :job, type: :model do
'category1',
'category2',
'category3',
- 'metafield.properties.fit',
- 'metafield.properties.manufacturer',
- 'metafield.properties.material',
- 'metafield.custom.brand',
- 'metafield.custom.material'
+ 'custom_field.properties.fit',
+ 'custom_field.properties.manufacturer',
+ 'custom_field.properties.material',
+ 'custom_field.custom.brand',
+ 'custom_field.custom.material'
])
end
@@ -203,19 +203,19 @@ RSpec.describe Spree::Import, :job, type: :model do
end
describe '#schema_fields' do
- context 'when model supports metafields' do
- let!(:metafield_definition1) do
- create(:metafield_definition,
+ context 'when model supports custom_fields' do
+ let!(:custom_field_definition1) do
+ create(:custom_field_definition,
namespace: 'properties',
key: 'manufacturer',
- name: 'Manufacturer',
+ label: 'Manufacturer',
resource_type: 'Spree::Product')
end
- let!(:metafield_definition2) do
- create(:metafield_definition,
+ let!(:custom_field_definition2) do
+ create(:custom_field_definition,
namespace: 'custom',
key: 'brand',
- name: 'Brand',
+ label: 'Brand',
resource_type: 'Spree::Product')
end
@@ -224,7 +224,7 @@ RSpec.describe Spree::Import, :job, type: :model do
end
it 'returns base fields from schema' do
- base_fields = import.schema_fields.select { |f| !f[:name].start_with?('metafield.') }
+ base_fields = import.schema_fields.select { |f| !f[:name].start_with?('custom_field.') }
expect(base_fields).to include(
{ name: 'slug', label: 'Slug', required: true },
{ name: 'sku', label: 'SKU', required: true },
@@ -232,34 +232,34 @@ RSpec.describe Spree::Import, :job, type: :model do
)
end
- it 'includes metafield fields' do
- metafield_fields = import.schema_fields.select { |f| f[:name].start_with?('metafield.') }
- expect(metafield_fields).to include(
- { name: 'metafield.properties.manufacturer', label: 'Manufacturer' },
- { name: 'metafield.custom.brand', label: 'Brand' }
+ it 'includes custom_field fields' do
+ custom_field_fields = import.schema_fields.select { |f| f[:name].start_with?('custom_field.') }
+ expect(custom_field_fields).to include(
+ { name: 'custom_field.properties.manufacturer', label: 'Manufacturer' },
+ { name: 'custom_field.custom.brand', label: 'Brand' }
)
end
- it 'combines base fields and metafield fields' do
+ it 'combines base fields and custom_field fields' do
all_fields = import.schema_fields
base_field_count = Spree::ImportSchemas::Products::FIELDS.count
- metafield_count = 2
+ custom_field_count = 2
- expect(all_fields.count).to eq(base_field_count + metafield_count)
+ expect(all_fields.count).to eq(base_field_count + custom_field_count)
end
- it 'has correct structure for metafield fields' do
- metafield_field = import.schema_fields.find { |f| f[:name] == 'metafield.properties.manufacturer' }
- expect(metafield_field).to eq(
- { name: 'metafield.properties.manufacturer', label: 'Manufacturer' }
+ it 'has correct structure for custom_field fields' do
+ custom_field_field = import.schema_fields.find { |f| f[:name] == 'custom_field.properties.manufacturer' }
+ expect(custom_field_field).to eq(
+ { name: 'custom_field.properties.manufacturer', label: 'Manufacturer' }
)
end
end
- context 'when model does not support metafields' do
+ context 'when model does not support custom_fields' do
before do
import.type = 'Spree::Imports::Products'
- # Mock model_class to return a class that doesn't include Metafields
+ # Mock model_class to return a class that doesn't include CustomFields
allow(import).to receive(:model_class).and_return(double('ModelClass', included_modules: []))
end
@@ -268,17 +268,17 @@ RSpec.describe Spree::Import, :job, type: :model do
expect(fields).to eq(Spree::ImportSchemas::Products::FIELDS)
end
- it 'does not include any metafield fields' do
- metafield_fields = import.schema_fields.select { |f| f[:name].start_with?('metafield.') }
- expect(metafield_fields).to be_empty
+ it 'does not include any custom_field fields' do
+ custom_field_fields = import.schema_fields.select { |f| f[:name].start_with?('custom_field.') }
+ expect(custom_field_fields).to be_empty
end
end
- context 'when model supports metafields but has no metafield definitions' do
+ context 'when model supports custom_fields but has no custom_field definitions' do
before do
import.type = 'Spree::Imports::Products'
- # Ensure no metafield definitions exist
- Spree::MetafieldDefinition.where(resource_type: 'Spree::Product').delete_all
+ # Ensure no custom_field definitions exist
+ Spree::CustomFieldDefinition.where(resource_type: 'Spree::Product').delete_all
end
it 'returns only base fields' do
@@ -311,7 +311,7 @@ RSpec.describe Spree::Import, :job, type: :model do
end
it 'returns columns that are not mapped' do
- expect(import.unmapped_file_columns).to include('vendor_name', 'brand_name', 'labels', 'metafield.properties.fit', 'metafield.properties.manufacturer', 'metafield.properties.material')
+ expect(import.unmapped_file_columns).to include('vendor_name', 'brand_name', 'labels', 'custom_field.properties.fit', 'custom_field.properties.manufacturer', 'custom_field.properties.material')
expect(import.unmapped_file_columns).not_to include('slug')
end
end
diff --git a/spree/core/spec/models/spree/metafield_definition_spec.rb b/spree/core/spec/models/spree/metafield_definition_spec.rb
deleted file mode 100644
index 21de008f55..0000000000
--- a/spree/core/spec/models/spree/metafield_definition_spec.rb
+++ /dev/null
@@ -1,178 +0,0 @@
-require 'spec_helper'
-
-RSpec.describe Spree::MetafieldDefinition, type: :model do
- let(:metafield_definition) { build(:metafield_definition) }
-
- describe 'scopes' do
- let!(:both_definition) { create(:metafield_definition, display_on: 'both') }
- let!(:front_end_definition) { create(:metafield_definition, :front_end_only) }
- let!(:back_end_definition) { create(:metafield_definition, :back_end_only) }
- let!(:product_definition) { create(:metafield_definition, resource_type: 'Spree::Product') }
- let!(:variant_definition) { create(:metafield_definition, :for_variant) }
- let!(:searchable_definition) { create(:metafield_definition, :searchable, key: 'searchable_field') }
- let!(:sortable_definition) { create(:metafield_definition, :sortable, key: 'sortable_field') }
-
- describe '.available' do
- it 'returns only both definitions (from DisplayOn concern)' do
- expect(described_class.available).to include(both_definition)
- expect(described_class.available).not_to include(front_end_definition)
- expect(described_class.available).not_to include(back_end_definition)
- end
- end
-
- describe '.available_on_front_end' do
- it 'returns public definitions (front_end and both)' do
- expect(described_class.available_on_front_end).to include(front_end_definition, both_definition)
- expect(described_class.available_on_front_end).not_to include(back_end_definition)
- end
- end
-
- describe '.available_on_back_end' do
- it 'returns admin definitions (back_end and both)' do
- expect(described_class.available_on_back_end).to include(back_end_definition, both_definition)
- expect(described_class.available_on_back_end).not_to include(front_end_definition)
- end
- end
-
- describe '.for_resource_type' do
- it 'returns definitions for specific resource type' do
- expect(described_class.for_resource_type('Spree::Product')).to include(product_definition)
- expect(described_class.for_resource_type('Spree::Product')).not_to include(variant_definition)
-
- expect(described_class.for_resource_type('Spree::Variant')).to include(variant_definition)
- expect(described_class.for_resource_type('Spree::Variant')).not_to include(product_definition)
- end
- end
-
- describe '.searchable' do
- it 'returns only searchable definitions' do
- expect(described_class.searchable).to include(searchable_definition)
- expect(described_class.searchable).not_to include(product_definition)
- end
- end
-
- describe '.sortable' do
- it 'returns only sortable definitions' do
- expect(described_class.sortable).to include(sortable_definition)
- expect(described_class.sortable).not_to include(product_definition)
- end
- end
- end
-
- describe 'searchable / sortable validations' do
- it 'allows searchable on short_text' do
- definition = build(:metafield_definition, :short_text_field, searchable: true)
- expect(definition).to be_valid
- end
-
- it 'allows searchable on long_text' do
- definition = build(:metafield_definition, :long_text_field, searchable: true)
- expect(definition).to be_valid
- end
-
- it 'rejects searchable on rich_text' do
- definition = build(:metafield_definition, :rich_text_field, searchable: true)
- expect(definition).not_to be_valid
- expect(definition.errors[:searchable].first).to include('short text', 'long text', 'number')
- end
-
- it 'rejects searchable on boolean' do
- definition = build(:metafield_definition, :boolean_field, searchable: true)
- expect(definition).not_to be_valid
- expect(definition.errors[:searchable]).to be_present
- end
-
- it 'allows sortable on short_text and number' do
- expect(build(:metafield_definition, :short_text_field, sortable: true)).to be_valid
- expect(build(:metafield_definition, :number_field, sortable: true)).to be_valid
- end
-
- it 'rejects sortable on long_text' do
- definition = build(:metafield_definition, :long_text_field, sortable: true)
- expect(definition).not_to be_valid
- expect(definition.errors[:sortable].first).to include('short text', 'number')
- expect(definition.errors[:sortable].first).not_to include('long text')
- end
-
- it 'rejects changing metafield_type to a non-searchable class while searchable stays true' do
- definition = create(:metafield_definition, :short_text_field, searchable: true)
- definition.field_type = 'boolean'
- expect(definition).not_to be_valid
- expect(definition.errors[:searchable]).to be_present
- end
-
- it 'rejects changing metafield_type to a non-sortable class while sortable stays true' do
- definition = create(:metafield_definition, :short_text_field, sortable: true)
- definition.field_type = 'long_text'
- expect(definition).not_to be_valid
- expect(definition.errors[:sortable]).to be_present
- end
- end
-
- describe '.searchable_field_type_tokens / .sortable_field_type_tokens' do
- it 'derives tokens from metafield type class capabilities' do
- expect(described_class.searchable_field_type_tokens).to match_array(%w[short_text long_text number])
- expect(described_class.sortable_field_type_tokens).to match_array(%w[short_text number])
- end
- end
-
- describe '#filter_key' do
- it 'combines the namespace and key' do
- metafield_definition = build(:metafield_definition, namespace: 'custom', key: 'material')
-
- expect(metafield_definition.filter_key).to eq('cf_custom_material')
- end
- end
-
- describe 'filter_key uniqueness' do
- # (a_b, c) and (a, b_c) both flatten to `cf_a_b_c`, which would make one
- # definition unreachable via sort/filter params.
- it 'rejects a definition whose filter_key collides across a different namespace split' do
- create(:metafield_definition, resource_type: 'Spree::Product', namespace: 'a_b', key: 'c')
- colliding = build(:metafield_definition, resource_type: 'Spree::Product', namespace: 'a', key: 'b_c')
-
- expect(colliding).not_to be_valid
- expect(colliding.errors[:key]).to be_present
- end
-
- it 'allows the same namespace/key split on a different resource type' do
- create(:metafield_definition, resource_type: 'Spree::Product', namespace: 'a_b', key: 'c')
- other_resource = build(:metafield_definition, resource_type: 'Spree::Variant', namespace: 'a', key: 'b_c')
-
- expect(other_resource).to be_valid
- end
-
- it 'does not flag a persisted definition against itself' do
- metafield_definition = create(:metafield_definition, namespace: 'custom', key: 'material')
-
- metafield_definition.name = 'Renamed'
-
- expect(metafield_definition).to be_valid
- end
- end
-
- describe 'Ransack allowlist' do
- it 'allows filtering by searchable and sortable' do
- matching = create(:metafield_definition, :short_text_field, :searchable, :sortable, key: 'ransack_match')
- create(:metafield_definition, :short_text_field, key: 'ransack_other')
-
- result = described_class.ransack(searchable_eq: true, sortable_eq: true).result
- expect(result).to include(matching)
- expect(result.map(&:key)).not_to include('ransack_other')
- end
- end
-
- describe '#csv_header_name' do
- it 'returns the CSV header name with metafield prefix' do
- metafield_definition = build(:metafield_definition, namespace: 'custom', key: 'field1')
- expect(metafield_definition.csv_header_name).to eq('metafield.custom.field1')
- end
- end
-
- describe '#full_key' do
- it 'returns the full key with namespace' do
- metafield_definition = build(:metafield_definition, namespace: 'custom', key: 'field1')
- expect(metafield_definition.full_key).to eq('custom.field1')
- end
- end
-end
diff --git a/spree/core/spec/models/spree/metafield_spec.rb b/spree/core/spec/models/spree/metafield_spec.rb
deleted file mode 100644
index e184f99005..0000000000
--- a/spree/core/spec/models/spree/metafield_spec.rb
+++ /dev/null
@@ -1,107 +0,0 @@
-require 'spec_helper'
-
-RSpec.describe Spree::Metafield, type: :model do
- context 'Callbacks' do
- it 'sets the type from the metafield definition' do
- metafield_definition = create(:metafield_definition, metafield_type: 'Spree::Metafields::ShortText')
- metafield = create(:metafield, metafield_definition: metafield_definition, type: nil)
- expect(metafield.type).to eq('Spree::Metafields::ShortText')
- end
- end
-
- context 'Validations' do
- it 'validates the type must match the metafield definition' do
- metafield_definition = create(:metafield_definition, metafield_type: 'Spree::Metafields::ShortText')
- metafield = build(:metafield, metafield_definition: metafield_definition, type: 'Spree::Metafields::LongText')
- expect(metafield.valid?).to be false
- end
- end
-
- context 'Scopes' do
- describe '.with_key' do
- it 'returns the metafields with the given key' do
- metafield_definition = create(:metafield_definition, namespace: 'custom', key: 'foo')
- metafield = create(:metafield, metafield_definition: metafield_definition)
- other_definition = create(:metafield_definition, namespace: 'custom', key: 'bar')
- create(:metafield, metafield_definition: other_definition)
- expect(described_class.with_key('custom', 'foo').ids).to contain_exactly(metafield.id)
- end
- end
- end
-
- describe '#serialize_value' do
- it 'returns the value' do
- metafield = build(:metafield, value: 'Test Value')
- expect(metafield.serialize_value).to eq('Test Value')
- end
- end
-
- describe '#csv_value' do
- context 'for base Metafield' do
- it 'returns the value as string' do
- metafield = build(:metafield, value: 'Test Value')
- expect(metafield.csv_value).to eq('Test Value')
- end
- end
-
- context 'for Boolean metafield' do
- let(:metafield_definition) { create(:metafield_definition, metafield_type: 'Spree::Metafields::Boolean') }
-
- it 'returns Yes for true values' do
- metafield = Spree::Metafields::Boolean.new(metafield_definition: metafield_definition, value: 'true')
- expect(metafield.csv_value).to eq(Spree.t(:say_yes))
- end
-
- it 'returns No for false values' do
- metafield = Spree::Metafields::Boolean.new(metafield_definition: metafield_definition, value: 'false')
- expect(metafield.csv_value).to eq(Spree.t(:say_no))
- end
- end
-
- context 'for Number metafield' do
- let(:metafield_definition) { create(:metafield_definition, metafield_type: 'Spree::Metafields::Number') }
-
- it 'returns the number as string' do
- metafield = Spree::Metafields::Number.new(metafield_definition: metafield_definition, value: '123.45')
- expect(metafield.csv_value).to eq('123.45')
- end
- end
-
- context 'for Json metafield' do
- let(:metafield_definition) { create(:metafield_definition, metafield_type: 'Spree::Metafields::Json') }
-
- it 'returns the JSON string' do
- metafield = Spree::Metafields::Json.new(metafield_definition: metafield_definition, value: '{"key": "value"}')
- expect(metafield.csv_value).to eq('{"key": "value"}')
- end
- end
-
- context 'for ShortText metafield' do
- let(:metafield_definition) { create(:metafield_definition, metafield_type: 'Spree::Metafields::ShortText') }
-
- it 'returns the text value' do
- metafield = Spree::Metafields::ShortText.new(metafield_definition: metafield_definition, value: 'Short text')
- expect(metafield.csv_value).to eq('Short text')
- end
- end
-
- context 'for LongText metafield' do
- let(:metafield_definition) { create(:metafield_definition, metafield_type: 'Spree::Metafields::LongText') }
-
- it 'returns the text value' do
- metafield = Spree::Metafields::LongText.new(metafield_definition: metafield_definition, value: 'Long text content')
- expect(metafield.csv_value).to eq('Long text content')
- end
- end
-
- context 'for RichText metafield' do
- let(:metafield_definition) { create(:metafield_definition, metafield_type: 'Spree::Metafields::RichText') }
-
- it 'returns plain text without HTML tags' do
- metafield = Spree::Metafields::RichText.new(metafield_definition: metafield_definition)
- metafield.value = '<p>Rich <strong>text</strong> content</p>'
- expect(metafield.csv_value).to eq('Rich text content')
- end
- end
- end
-end
diff --git a/spree/core/spec/models/spree/metafields/json_spec.rb b/spree/core/spec/models/spree/metafields/json_spec.rb
deleted file mode 100644
index 1368fccad1..0000000000
--- a/spree/core/spec/models/spree/metafields/json_spec.rb
+++ /dev/null
@@ -1,62 +0,0 @@
-require 'spec_helper'
-
-describe Spree::Metafields::Json, type: :model do
- let(:product) { create(:product) }
- let(:metafield_definition) { create(:metafield_definition, metafield_type: 'Spree::Metafields::Json') }
- let(:metafield) { described_class.new(metafield_definition: metafield_definition, value: '{"key": "value"}', resource: product) }
-
- describe 'Validations' do
- it 'returns false if the value is not valid JSON' do
- metafield.value = 'not valid json'
- expect(metafield.valid?).to be false
- expect(metafield.errors[:value]).to include(/must be valid JSON/)
- end
-
- it 'returns true for valid JSON object' do
- metafield.value = '{"key": "value", "nested": {"foo": "bar"}}'
- expect(metafield.valid?).to be true
- end
-
- it 'returns true for valid JSON array' do
- metafield.value = '[1, 2, 3, "test"]'
- expect(metafield.valid?).to be true
- end
-
- it 'returns true for valid JSON string' do
- metafield.value = '"simple string"'
- expect(metafield.valid?).to be true
- end
-
- it 'returns true for valid JSON number' do
- metafield.value = '123'
- expect(metafield.valid?).to be true
- end
-
- it 'returns true for valid JSON boolean' do
- metafield.value = 'true'
- expect(metafield.valid?).to be true
- end
-
- it 'returns true for valid JSON null' do
- metafield.value = 'null'
- expect(metafield.valid?).to be true
- end
- end
-
- describe '#serialize_value' do
- it 'returns parsed JSON object' do
- metafield.value = '{"key": "value", "number": 42}'
- expect(metafield.serialize_value).to eq({ 'key' => 'value', 'number' => 42 })
- end
-
- it 'returns parsed JSON array' do
- metafield.value = '[1, 2, 3]'
- expect(metafield.serialize_value).to eq([1, 2, 3])
- end
-
- it 'returns original value if parsing fails' do
- allow(JSON).to receive(:parse).and_raise(JSON::ParserError)
- expect(metafield.serialize_value).to eq('{"key": "value"}')
- end
- end
-end
diff --git a/spree/core/spec/models/spree/metafields/number_spec.rb b/spree/core/spec/models/spree/metafields/number_spec.rb
deleted file mode 100644
index 5de0bcea5e..0000000000
--- a/spree/core/spec/models/spree/metafields/number_spec.rb
+++ /dev/null
@@ -1,36 +0,0 @@
-require 'spec_helper'
-
-describe Spree::Metafields::Number, type: :model do
- let(:product) { create(:product) }
- let(:metafield_definition) { create(:metafield_definition, :number_field) }
- let(:metafield) { described_class.new(metafield_definition: metafield_definition, value: '123', resource: product) }
-
- describe 'Validations' do
- it 'returns false if the value is not a number' do
- metafield.value = 'not a number'
- expect(metafield.valid?).to be false
- end
- end
-
- describe '#serialize_value' do
- it 'returns the number' do
- expect(metafield.valid?).to be true
- expect(metafield.serialize_value).to be_kind_of(BigDecimal)
- expect(metafield.serialize_value).to eq(123)
- end
- end
-
- describe '#csv_value' do
- it 'returns the number as a string' do
- expect(metafield.csv_value).to be_kind_of(String)
- expect(metafield.csv_value).to eq('123.0')
- end
- end
-
- describe '.searchable? / .sortable?' do
- it 'is searchable and sortable' do
- expect(described_class.searchable?).to eq(true)
- expect(described_class.sortable?).to eq(true)
- end
- end
-end
diff --git a/spree/core/spec/models/spree/metafields/rich_text_spec.rb b/spree/core/spec/models/spree/metafields/rich_text_spec.rb
deleted file mode 100644
index cd02cc400e..0000000000
--- a/spree/core/spec/models/spree/metafields/rich_text_spec.rb
+++ /dev/null
@@ -1,18 +0,0 @@
-require 'spec_helper'
-
-describe Spree::Metafields::RichText, type: :model do
- let(:metafield_definition) { create(:metafield_definition, :rich_text_field) }
- let(:metafield) { described_class.new(metafield_definition: metafield_definition, value: '<p>Rich text with <strong>formatting</strong></p>') }
-
- describe '#value' do
- it 'returns the rich text body' do
- expect(metafield.value).to be_kind_of(ActionText::RichText)
- end
- end
-
- describe '#serialize_value' do
- it 'returns the rich text body' do
- expect(metafield.serialize_value).to eq(metafield.value.body.to_s)
- end
- end
-end
diff --git a/spree/core/spec/models/spree/order_spec.rb b/spree/core/spec/models/spree/order_spec.rb
index 1895abf994..0488a54c04 100644
--- a/spree/core/spec/models/spree/order_spec.rb
+++ b/spree/core/spec/models/spree/order_spec.rb
@@ -485,22 +485,22 @@ describe Spree::Order, type: :model do
let(:order_from_different_store) { create(:order, user: user, store: store_2) }
it 'includes frontend payment methods' do
- payment_method = store.payment_methods.create!(name: 'Fake', active: true, display_on: 'front_end')
+ payment_method = store.payment_methods.create!(name: 'Fake', active: true, storefront_visible: true)
expect(order.collect_frontend_payment_methods).to include(payment_method)
end
it "includes 'both' payment methods" do
- payment_method = store.payment_methods.create!(name: 'Fake', active: true, display_on: 'both')
+ payment_method = store.payment_methods.create!(name: 'Fake', active: true)
expect(order.collect_frontend_payment_methods).to include(payment_method)
end
it 'does not include backend payment method' do
- store.payment_methods.create!(name: 'Fake', active: true, display_on: 'back_end')
+ store.payment_methods.create!(name: 'Fake', active: true, storefront_visible: false)
expect(order.collect_frontend_payment_methods.count).to eq(0)
end
it 'does not include inactive payment methods' do
- store.payment_methods.create!(name: 'Fake', active: false, display_on: 'front_end')
+ store.payment_methods.create!(name: 'Fake', active: false, storefront_visible: true)
expect(order.collect_frontend_payment_methods.count).to eq(0)
end
@@ -511,7 +511,7 @@ describe Spree::Order, type: :model do
end
it 'does not include a payment method from different stores' do
- payment_method = store_2.payment_methods.create!(name: 'Fake', active: true, display_on: 'both')
+ payment_method = store_2.payment_methods.create!(name: 'Fake', active: true)
expect(order.collect_frontend_payment_methods).not_to include(payment_method)
expect(order_from_different_store.collect_frontend_payment_methods).to include(payment_method)
@@ -1355,9 +1355,9 @@ describe Spree::Order, type: :model do
describe '#collect_backend_payment_methods' do
let!(:order) { create(:order_with_line_items, line_items_count: 2) }
- let!(:credit_card_payment_method) { create(:simple_credit_card_payment_method, display_on: 'both') }
- let!(:store_credit_payment_method) { create(:store_credit_payment_method, display_on: 'both') }
- let!(:inactive_payment_method) { create(:simple_credit_card_payment_method, display_on: 'both', active: false) }
+ let!(:credit_card_payment_method) { create(:simple_credit_card_payment_method) }
+ let!(:store_credit_payment_method) { create(:store_credit_payment_method) }
+ let!(:inactive_payment_method) { create(:simple_credit_card_payment_method, active: false) }
it { expect(order.collect_backend_payment_methods).to include(credit_card_payment_method) }
it { expect(order.collect_backend_payment_methods).not_to include(store_credit_payment_method) }
diff --git a/spree/core/spec/models/spree/payment_method/store_credit_spec.rb b/spree/core/spec/models/spree/payment_method/store_credit_spec.rb
index 0a1be02aaa..4deeafaa95 100644
--- a/spree/core/spec/models/spree/payment_method/store_credit_spec.rb
+++ b/spree/core/spec/models/spree/payment_method/store_credit_spec.rb
@@ -291,7 +291,7 @@ describe Spree::PaymentMethod::StoreCredit do
end
describe '#available_for_order?' do
- let!(:store_credit_payment_method) { create(:store_credit_payment_method, display_on: 'both') }
+ let!(:store_credit_payment_method) { create(:store_credit_payment_method) }
context 'when user have store credits' do
let(:store) { @default_store }
diff --git a/spree/core/spec/models/spree/payment_spec.rb b/spree/core/spec/models/spree/payment_spec.rb
index f440cc3874..19ad778759 100644
--- a/spree/core/spec/models/spree/payment_spec.rb
+++ b/spree/core/spec/models/spree/payment_spec.rb
@@ -1247,18 +1247,18 @@ describe Spree::Payment, type: :model do
it 'adds a gateway processing error' do
subject
- expect(payment.get_metafield('gateway.processing_errors').value).to eq([{ message: 'Insufficient balance on payment' }].to_json)
+ expect(payment.get_custom_field('gateway.processing_errors').value).to eq([{ message: 'Insufficient balance on payment' }].to_json)
end
- context 'when the metafield already exists' do
+ context 'when the custom_field already exists' do
before do
- payment.set_metafield('gateway.processing_errors', [{ message: 'Gateway processing error' }].to_json)
+ payment.set_custom_field('gateway.processing_errors', [{ message: 'Gateway processing error' }].to_json)
end
it 'adds a gateway processing error' do
subject
- expect(payment.get_metafield('gateway.processing_errors').value).to eq(
+ expect(payment.get_custom_field('gateway.processing_errors').value).to eq(
[
{ message: 'Gateway processing error' },
{ message: 'Insufficient balance on payment' }
diff --git a/spree/core/spec/models/spree/product_spec.rb b/spree/core/spec/models/spree/product_spec.rb
index 9ef3324796..37d4d20b90 100644
--- a/spree/core/spec/models/spree/product_spec.rb
+++ b/spree/core/spec/models/spree/product_spec.rb
@@ -510,7 +510,7 @@ describe Spree::Product, type: :model do
# reject the first of them — and enforcing later would break products whose
# type gained a required field after they were created.
describe 'required custom fields from the product type' do
- let(:definition) { create(:custom_field_definition, name: 'Material') }
+ let(:definition) { create(:custom_field_definition, label: 'Material') }
let(:product_type) { create(:product_type) }
before do
@@ -2366,16 +2366,16 @@ describe Spree::Product, type: :model do
let!(:matching) { create(:product, name: 'Unrelated Name', store: store) }
let!(:other) { create(:product, name: 'Other Product', store: store) }
let!(:definition) do
- create(:metafield_definition, :short_text_field, :searchable,
+ create(:custom_field_definition, :short_text_field, :searchable,
namespace: 'custom', key: 'pinyin_name')
end
before do
- matching.set_metafield(definition, 'hong-ku-zi')
- other.set_metafield(definition, 'something-else')
+ matching.set_custom_field(definition, 'hong-ku-zi')
+ other.set_custom_field(definition, 'something-else')
end
- it 'finds products by searchable metafield value via plain SQL' do
+ it 'finds products by searchable custom_field value via plain SQL' do
expect(described_class.search('hong-ku')).to include(matching)
expect(described_class.search('hong-ku')).not_to include(other)
end
diff --git a/spree/core/spec/models/spree/search_provider/database_spec.rb b/spree/core/spec/models/spree/search_provider/database_spec.rb
index 4d49766589..d88edd27c7 100644
--- a/spree/core/spec/models/spree/search_provider/database_spec.rb
+++ b/spree/core/spec/models/spree/search_provider/database_spec.rb
@@ -255,33 +255,33 @@ module Spree
end
end
- context 'with searchable metafields' do
+ context 'with searchable custom_fields' do
let!(:definition) do
- create(:metafield_definition, :short_text_field, :searchable,
+ create(:custom_field_definition, :short_text_field, :searchable,
namespace: 'custom', key: 'label')
end
before do
- product_2.set_metafield(definition, 'wool-blend')
+ product_2.set_custom_field(definition, 'wool-blend')
end
- it 'finds products by searchable metafield value' do
+ it 'finds products by searchable custom_field value' do
result = provider.search_and_filter(scope: scope, query: 'wool')
expect(result.products).to include(product_2)
expect(result.products).not_to include(product_1, product_3)
end
end
- context 'with sortable metafields' do
+ context 'with sortable custom_fields' do
let!(:definition) do
- create(:metafield_definition, :short_text_field, :sortable,
+ create(:custom_field_definition, :short_text_field, :sortable,
namespace: 'custom', key: 'label')
end
before do
- product_1.set_metafield(definition, 'charlie')
- product_2.set_metafield(definition, 'alpha')
- product_3.set_metafield(definition, 'bravo')
+ product_1.set_custom_field(definition, 'charlie')
+ product_2.set_custom_field(definition, 'alpha')
+ product_3.set_custom_field(definition, 'bravo')
end
it 'sorts ascending by cf_* attribute' do
@@ -303,9 +303,9 @@ module Spree
expect(result.products.map(&:id)).to eq([product_3.id, product_1.id])
end
- context 'with missing metafield values' do
+ context 'with missing custom_field values' do
before do
- product_2.metafields.destroy_all
+ product_2.custom_fields.destroy_all
end
it 'keeps missing values last when sorting ascending' do
@@ -320,22 +320,22 @@ module Spree
end
end
- context 'with metafield filters' do
+ context 'with custom_field filters' do
let!(:material) do
- create(:metafield_definition, :short_text_field, :searchable,
+ create(:custom_field_definition, :short_text_field, :searchable,
namespace: 'custom', key: 'material')
end
let!(:weight) do
- create(:metafield_definition, :number_field, :sortable,
+ create(:custom_field_definition, :number_field, :sortable,
namespace: 'custom', key: 'weight')
end
before do
- product_1.set_metafield(material, 'wool-blend')
- product_2.set_metafield(material, 'cotton')
- product_1.set_metafield(weight, '10')
- product_2.set_metafield(weight, '2')
- product_3.set_metafield(weight, '3.5')
+ product_1.set_custom_field(material, 'wool-blend')
+ product_2.set_custom_field(material, 'cotton')
+ product_1.set_custom_field(weight, '10')
+ product_2.set_custom_field(weight, '2')
+ product_3.set_custom_field(weight, '3.5')
end
it 'filters text values with cont' do
@@ -383,7 +383,7 @@ module Spree
expect(result.products).to contain_exactly(product_3)
end
- it 'combines metafield and ransack filters' do
+ it 'combines custom_field and ransack filters' do
result = provider.search_and_filter(
scope: scope,
filters: { 'name_cont' => 'Blue', 'cf_custom_weight_gteq' => '5' }
@@ -391,7 +391,7 @@ module Spree
expect(result.products).to contain_exactly(product_1)
end
- it 'combines metafield filters with metafield sort' do
+ it 'combines custom_field filters with custom_field sort' do
result = provider.search_and_filter(
scope: scope,
filters: { 'cf_custom_weight_gteq' => '3' },
@@ -421,16 +421,16 @@ module Spree
end
end
- context 'with sortable number metafields' do
+ context 'with sortable number custom_fields' do
let!(:definition) do
- create(:metafield_definition, :number_field, :sortable,
+ create(:custom_field_definition, :number_field, :sortable,
namespace: 'custom', key: 'weight')
end
before do
- product_1.set_metafield(definition, '10')
- product_2.set_metafield(definition, '2')
- product_3.set_metafield(definition, '3')
+ product_1.set_custom_field(definition, '10')
+ product_2.set_custom_field(definition, '2')
+ product_3.set_custom_field(definition, '3')
end
it 'sorts ascending numerically rather than lexicographically' do
@@ -460,18 +460,18 @@ module Spree
expect(ids).to include('price', '-price', 'best_selling')
end
- context 'with sortable metafield definitions' do
+ context 'with sortable custom_field definitions' do
let!(:definition) do
- create(:metafield_definition, :short_text_field, :sortable,
- namespace: 'custom', key: 'label', name: 'Material')
+ create(:custom_field_definition, :short_text_field, :sortable,
+ namespace: 'custom', key: 'label', label: 'Material')
end
- it 'includes metafield sort options' do
+ it 'includes custom_field sort options' do
ids = result.sort_options.map { |o| o[:id] }
expect(ids).to include('cf_custom_label', '-cf_custom_label')
end
- it 'includes human-readable labels for metafield sort options' do
+ it 'includes human-readable labels for custom_field sort options' do
by_id = result.sort_options.index_by { |o| o[:id] }
expect(by_id['cf_custom_label'][:label]).to eq("Material (#{Spree.t(:sort_a_to_z)})")
expect(by_id['-cf_custom_label'][:label]).to eq("Material (#{Spree.t(:sort_z_to_a)})")
diff --git a/spree/core/spec/models/spree/search_provider/meilisearch_spec.rb b/spree/core/spec/models/spree/search_provider/meilisearch_spec.rb
index a16f6baa83..76bd715650 100644
--- a/spree/core/spec/models/spree/search_provider/meilisearch_spec.rb
+++ b/spree/core/spec/models/spree/search_provider/meilisearch_spec.rb
@@ -506,9 +506,9 @@ module Spree
end
end
- describe 'metafield searchable / sortable settings' do
+ describe 'custom_field searchable / sortable settings' do
let!(:definition) do
- create(:metafield_definition, :short_text_field, :searchable, :sortable,
+ create(:custom_field_definition, :short_text_field, :searchable, :sortable,
namespace: 'custom', key: 'label')
end
@@ -528,17 +528,17 @@ module Spree
end
end
- describe 'metafield filter conditions' do
+ describe 'custom_field filter conditions' do
let!(:label) do
- create(:metafield_definition, :short_text_field, :searchable,
+ create(:custom_field_definition, :short_text_field, :searchable,
namespace: 'custom', key: 'label')
end
let!(:weight) do
- create(:metafield_definition, :number_field, :sortable,
+ create(:custom_field_definition, :number_field, :sortable,
namespace: 'custom', key: 'weight')
end
- it 'builds equality conditions for text metafields' do
+ it 'builds equality conditions for text custom_fields' do
expect(provider.send(:build_filter_condition, 'cf_custom_label_eq', 'wool')).to eq("cf_custom_label = 'wool'")
expect(provider.send(:build_filter_condition, 'cf_custom_label_not_eq', 'wool')).to eq("cf_custom_label != 'wool'")
end
@@ -547,7 +547,7 @@ module Spree
expect(provider.send(:build_filter_condition, 'cf_custom_label_eq', "o'brien\\x")).to eq("cf_custom_label = 'o\\'brien\\\\x'")
end
- it 'builds range conditions for number metafields' do
+ it 'builds range conditions for number custom_fields' do
expect(provider.send(:build_filter_condition, 'cf_custom_weight_gteq', '3.5')).to eq('cf_custom_weight >= 3.5')
expect(provider.send(:build_filter_condition, 'cf_custom_weight_lt', '10')).to eq('cf_custom_weight < 10.0')
end
@@ -569,7 +569,7 @@ module Spree
expect(provider.send(:build_filter_condition, 'cf_bogus_field_eq', 'x')).to be_nil
end
- it 'passes metafield conditions through to the Meilisearch query' do
+ it 'passes custom_field conditions through to the Meilisearch query' do
ms_response = { 'hits' => [], 'estimatedTotalHits' => 0, 'facetDistribution' => {} }
expect(mock_index).to receive(:search).with(anything, hash_including(
filter: include('cf_custom_weight >= 3.5')
diff --git a/spree/core/spec/models/spree/store_spec.rb b/spree/core/spec/models/spree/store_spec.rb
index 77665bd1ba..aa156eddf4 100644
--- a/spree/core/spec/models/spree/store_spec.rb
+++ b/spree/core/spec/models/spree/store_spec.rb
@@ -1027,8 +1027,8 @@ describe Spree::Store, type: :model, without_global_store: true do
context 'when the only non-store-credit methods are admin-only' do
before do
- create(:credit_card_payment_method, store: store, display_on: 'back_end')
- create(:check_payment_method, store: store, display_on: 'back_end')
+ create(:credit_card_payment_method, store: store, storefront_visible: false)
+ create(:check_payment_method, store: store, storefront_visible: false)
end
it 'stays pending' do
diff --git a/spree/core/spec/presenters/spree/csv/customer_presenter_spec.rb b/spree/core/spec/presenters/spree/csv/customer_presenter_spec.rb
index 8eb27b66b6..d52a075c1d 100644
--- a/spree/core/spec/presenters/spree/csv/customer_presenter_spec.rb
+++ b/spree/core/spec/presenters/spree/csv/customer_presenter_spec.rb
@@ -129,35 +129,33 @@ RSpec.describe Spree::CSV::CustomerPresenter do
end
end
- describe 'metafields' do
- let!(:metafield_definition) do
- create(:metafield_definition,
+ describe 'custom_fields' do
+ let!(:custom_field_definition) do
+ create(:custom_field_definition,
resource_type: customer.class.to_s,
namespace: 'custom',
key: 'loyalty_points')
end
- let!(:metafield) do
- customer.metafields.create!(
- metafield_definition: metafield_definition,
- value: '500'
- )
+ let!(:custom_field) do
+ create(:custom_field, resource: customer, custom_field_definition: custom_field_definition,
+ value: '500')
end
- it 'includes metafield values at the end of the array' do
+ it 'includes custom_field values at the end of the array' do
result = presenter.call
expect(result.last).to eq '500'
end
- context 'when customer has no metafield value' do
- let(:customer_without_metafield) do
+ context 'when customer has no custom_field value' do
+ let(:customer_without_custom_field) do
create(:user,
first_name: 'Jane',
last_name: 'Smith',
end
- let(:presenter) { described_class.new(customer_without_metafield) }
+ let(:presenter) { described_class.new(customer_without_custom_field) }
- it 'returns nil for metafield' do
+ it 'returns nil for custom_field' do
result = presenter.call
expect(result.last).to be_nil
end
diff --git a/spree/core/spec/presenters/spree/csv/gift_card_presenter_spec.rb b/spree/core/spec/presenters/spree/csv/gift_card_presenter_spec.rb
index 46434800f5..2ae379bea6 100644
--- a/spree/core/spec/presenters/spree/csv/gift_card_presenter_spec.rb
+++ b/spree/core/spec/presenters/spree/csv/gift_card_presenter_spec.rb
@@ -69,30 +69,28 @@ RSpec.describe Spree::CSV::GiftCardPresenter, type: :model do
end
end
- describe 'metafields' do
- let!(:metafield_definition) do
- create(:metafield_definition,
+ describe 'custom_fields' do
+ let!(:custom_field_definition) do
+ create(:custom_field_definition,
resource_type: 'Spree::GiftCard',
namespace: 'custom',
key: 'purchase_location')
end
- let!(:metafield) do
- gift_card.metafields.create!(
- metafield_definition: metafield_definition,
- value: 'Online Store'
- )
+ let!(:custom_field) do
+ create(:custom_field, resource: gift_card, custom_field_definition: custom_field_definition,
+ value: 'Online Store')
end
- it 'includes metafield values at the end of the array' do
+ it 'includes custom_field values at the end of the array' do
result = presenter.call
expect(result.last).to eq 'Online Store'
end
- context 'when gift card has no metafield value' do
- let(:gift_card_without_metafield) { create(:gift_card, store: store) }
- let(:presenter) { described_class.new(gift_card_without_metafield) }
+ context 'when gift card has no custom_field value' do
+ let(:gift_card_without_custom_field) { create(:gift_card, store: store) }
+ let(:presenter) { described_class.new(gift_card_without_custom_field) }
- it 'returns nil for metafield' do
+ it 'returns nil for custom_field' do
result = presenter.call
expect(result.last).to be_nil
end
diff --git a/spree/core/spec/presenters/spree/csv/newsletter_subscriber_presenter_spec.rb b/spree/core/spec/presenters/spree/csv/newsletter_subscriber_presenter_spec.rb
index b089311ae5..8c41288398 100644
--- a/spree/core/spec/presenters/spree/csv/newsletter_subscriber_presenter_spec.rb
+++ b/spree/core/spec/presenters/spree/csv/newsletter_subscriber_presenter_spec.rb
@@ -81,33 +81,31 @@ RSpec.describe Spree::CSV::NewsletterSubscriberPresenter do
end
end
- describe 'metafields' do
- let!(:metafield_definition) do
- create(:metafield_definition,
+ describe 'custom_fields' do
+ let!(:custom_field_definition) do
+ create(:custom_field_definition,
resource_type: 'Spree::NewsletterSubscriber',
namespace: 'custom',
key: 'subscription_source')
end
- let!(:metafield) do
- newsletter_subscriber.metafields.create!(
- metafield_definition: metafield_definition,
- value: 'Homepage Popup'
- )
+ let!(:custom_field) do
+ create(:custom_field, resource: newsletter_subscriber, custom_field_definition: custom_field_definition,
+ value: 'Homepage Popup')
end
- it 'includes metafield values at the end of the array' do
+ it 'includes custom_field values at the end of the array' do
result = presenter.call
expect(result.last).to eq 'Homepage Popup'
end
- context 'when subscriber has no metafield value' do
- let(:subscriber_without_metafield) do
+ context 'when subscriber has no custom_field value' do
+ let(:subscriber_without_custom_field) do
create(:newsletter_subscriber,
end
- let(:presenter) { described_class.new(subscriber_without_metafield) }
+ let(:presenter) { described_class.new(subscriber_without_custom_field) }
- it 'returns nil for metafield' do
+ it 'returns nil for custom_field' do
result = presenter.call
expect(result.last).to be_nil
end
diff --git a/spree/core/spec/presenters/spree/csv/order_line_items_presenter_spec.rb b/spree/core/spec/presenters/spree/csv/order_line_items_presenter_spec.rb
index f8b7a96668..ecbb15dff4 100644
--- a/spree/core/spec/presenters/spree/csv/order_line_items_presenter_spec.rb
+++ b/spree/core/spec/presenters/spree/csv/order_line_items_presenter_spec.rb
@@ -5,8 +5,8 @@ RSpec.describe Spree::CSV::OrderLineItemPresenter do
let(:order) { create(:completed_order_with_totals, store: store) }
let(:line_item) { order.line_items.first }
let(:index) { 0 }
- let(:metafields) { [] }
- let(:presenter) { described_class.new(order, line_item, index, metafields) }
+ let(:custom_fields) { [] }
+ let(:presenter) { described_class.new(order, line_item, index, custom_fields) }
describe '#call' do
subject { presenter.call }
@@ -79,12 +79,12 @@ RSpec.describe Spree::CSV::OrderLineItemPresenter do
end
end
- describe 'metafields' do
+ describe 'custom_fields' do
context 'when index is zero' do
- let(:metafields) { ['loyalty_tier', '100'] }
- let(:presenter) { described_class.new(order, line_item, 0, metafields) }
+ let(:custom_fields) { ['loyalty_tier', '100'] }
+ let(:presenter) { described_class.new(order, line_item, 0, custom_fields) }
- it 'includes metafields at the end of the array' do
+ it 'includes custom_fields at the end of the array' do
result = presenter.call
expect(result[-2]).to eq 'loyalty_tier'
expect(result[-1]).to eq '100'
@@ -92,10 +92,10 @@ RSpec.describe Spree::CSV::OrderLineItemPresenter do
end
context 'when index is not zero' do
- let(:metafields) { ['loyalty_tier', '100'] }
- let(:presenter) { described_class.new(order, line_item, 1, metafields) }
+ let(:custom_fields) { ['loyalty_tier', '100'] }
+ let(:presenter) { described_class.new(order, line_item, 1, custom_fields) }
- it 'does not include metafields' do
+ it 'does not include custom_fields' do
result = presenter.call
expect(result).not_to include('loyalty_tier')
expect(result).not_to include('100')
diff --git a/spree/core/spec/presenters/spree/csv/product_variant_presenter_spec.rb b/spree/core/spec/presenters/spree/csv/product_variant_presenter_spec.rb
index c08db703e6..7d3cd6db17 100644
--- a/spree/core/spec/presenters/spree/csv/product_variant_presenter_spec.rb
+++ b/spree/core/spec/presenters/spree/csv/product_variant_presenter_spec.rb
@@ -6,8 +6,8 @@ RSpec.describe Spree::CSV::ProductVariantPresenter do
let(:variant) { product.default_variant }
let(:properties) { [] }
let(:taxons) { [] }
- let(:metafields) { [] }
- let(:presenter) { described_class.new(product, variant, 0, properties, taxons, store, metafields) }
+ let(:custom_fields) { [] }
+ let(:presenter) { described_class.new(product, variant, 0, properties, taxons, store, custom_fields) }
let(:default_publication) { product.product_publications.find_by(channel: store.default_channel) }
let!(:variant_images) { create_list(:image, 3, viewable: variant) }
@@ -58,7 +58,7 @@ RSpec.describe Spree::CSV::ProductVariantPresenter do
end
context 'when index is not zero' do
- let(:presenter) { described_class.new(product, variant, 1, properties, taxons, store, metafields) }
+ let(:presenter) { described_class.new(product, variant, 1, properties, taxons, store, custom_fields) }
let!(:color_option) { create(:option_type, name: 'Color', presentation: 'Color', products: [product]) }
let!(:size_option) { create(:option_type, name: 'Size', presentation: 'Size', products: [product]) }
@@ -147,12 +147,12 @@ RSpec.describe Spree::CSV::ProductVariantPresenter do
end
end
- describe 'metafields' do
+ describe 'custom_fields' do
context 'when index is zero' do
- let(:metafields) { ['value1', 'value2'] }
- let(:presenter) { described_class.new(product, variant, 0, properties, taxons, store, metafields) }
+ let(:custom_fields) { ['value1', 'value2'] }
+ let(:presenter) { described_class.new(product, variant, 0, properties, taxons, store, custom_fields) }
- it 'includes metafields at the end of the array' do
+ it 'includes custom_fields at the end of the array' do
result = presenter.call
expect(result[-2]).to eq 'value1'
expect(result[-1]).to eq 'value2'
@@ -160,10 +160,10 @@ RSpec.describe Spree::CSV::ProductVariantPresenter do
end
context 'when index is not zero' do
- let(:metafields) { ['value1', 'value2'] }
- let(:presenter) { described_class.new(product, variant, 1, properties, taxons, store, metafields) }
+ let(:custom_fields) { ['value1', 'value2'] }
+ let(:presenter) { described_class.new(product, variant, 1, properties, taxons, store, custom_fields) }
- it 'does not include metafields' do
+ it 'does not include custom_fields' do
result = presenter.call
expect(result).not_to include('value1')
expect(result).not_to include('value2')
diff --git a/spree/core/spec/presenters/spree/data_feeds/google_presenter_spec.rb b/spree/core/spec/presenters/spree/data_feeds/google_presenter_spec.rb
index 7e6f7b9c86..03736127fa 100644
--- a/spree/core/spec/presenters/spree/data_feeds/google_presenter_spec.rb
+++ b/spree/core/spec/presenters/spree/data_feeds/google_presenter_spec.rb
@@ -119,47 +119,47 @@ RSpec.describe Spree::DataFeeds::GooglePresenter do
end
end
- context 'optional attributes from product metafields' do
+ context 'optional attributes from product custom_fields' do
let(:product) { create(:product) }
- let(:metafield_definition) { create(:metafield_definition, name: 'Brand', key: 'brand') }
- let!(:metafield) { create(:metafield, resource: product, metafield_definition: metafield_definition, value: 'Nike') }
+ let(:custom_field_definition) { create(:custom_field_definition, label: 'Brand', key: 'brand') }
+ let!(:custom_field) { create(:custom_field, resource: product, custom_field_definition: custom_field_definition, value: 'Nike') }
- it 'includes product metafields' do
- expect(xml).to include("<g:brand>#{product.metafields.first.value}</g:brand>")
+ it 'includes product custom_fields' do
+ expect(xml).to include("<g:brand>#{product.custom_fields.first.value}</g:brand>")
end
end
- context 'metafield with a key that is not a known Google attribute' do
+ context 'custom_field with a key that is not a known Google attribute' do
let(:product) { create(:product) }
- let(:metafield_definition) { create(:metafield_definition, name: 'Internal', key: 'internal_note') }
- let!(:metafield) { create(:metafield, resource: product, metafield_definition: metafield_definition, value: 'secret') }
+ let(:custom_field_definition) { create(:custom_field_definition, label: 'Internal', key: 'internal_note') }
+ let!(:custom_field) { create(:custom_field, resource: product, custom_field_definition: custom_field_definition, value: 'secret') }
- it 'omits the metafield from the feed' do
+ it 'omits the custom_field from the feed' do
expect(xml).not_to include('internal_note')
expect(xml).not_to include('secret')
end
end
- context 'metafield whose key collides with a Ruby method name' do
+ context 'custom_field whose key collides with a Ruby method name' do
let(:product) { create(:product) }
- let(:metafield_definition) do
- create(:metafield_definition, name: 'System', key: 'brand').tap do |definition|
+ let(:custom_field_definition) do
+ create(:custom_field_definition, label: 'System', key: 'brand').tap do |definition|
definition.update_column(:key, 'system')
end
end
- let!(:metafield) { create(:metafield, resource: product, metafield_definition: metafield_definition, value: 'id') }
+ let!(:custom_field) { create(:custom_field, resource: product, custom_field_definition: custom_field_definition, value: 'id') }
it 'does not dispatch the key as a method and omits it from the feed' do
expect(xml).not_to include('<g:system>')
end
end
- context 'metafield whose key matches a required attribute' do
+ context 'custom_field whose key matches a required attribute' do
let(:product) { create(:product) }
- let(:metafield_definition) { create(:metafield_definition, name: 'Item Group', key: 'item_group_id') }
- let!(:metafield) { create(:metafield, resource: product, metafield_definition: metafield_definition, value: 'injected') }
+ let(:custom_field_definition) { create(:custom_field_definition, label: 'Item Group', key: 'item_group_id') }
+ let!(:custom_field) { create(:custom_field, resource: product, custom_field_definition: custom_field_definition, value: 'injected') }
- it 'does not emit the metafield value, only the required item_group_id' do
+ it 'does not emit the custom_field value, only the required item_group_id' do
expect(xml).to include("<g:item_group_id>#{product.id}</g:item_group_id>")
expect(xml).not_to include('<g:item_group_id>injected</g:item_group_id>')
end
diff --git a/spree/core/spec/presenters/spree/search_provider/product_presenter_spec.rb b/spree/core/spec/presenters/spree/search_provider/product_presenter_spec.rb
index 2368e82858..7c804246c0 100644
--- a/spree/core/spec/presenters/spree/search_provider/product_presenter_spec.rb
+++ b/spree/core/spec/presenters/spree/search_provider/product_presenter_spec.rb
@@ -242,27 +242,27 @@ module Spree
end
end
- context 'with searchable / sortable metafields' do
+ context 'with searchable / sortable custom_fields' do
let!(:searchable_def) do
- create(:metafield_definition, :short_text_field, :searchable,
- namespace: 'custom', key: 'pinyin_name', name: 'Pinyin')
+ create(:custom_field_definition, :short_text_field, :searchable,
+ namespace: 'custom', key: 'pinyin_name', label: 'Pinyin')
end
let!(:sortable_def) do
- create(:metafield_definition, :number_field, :sortable,
- namespace: 'custom', key: 'priority', name: 'Priority')
+ create(:custom_field_definition, :number_field, :sortable,
+ namespace: 'custom', key: 'priority', label: 'Priority')
end
let!(:ignored_def) do
- create(:metafield_definition, :short_text_field,
- namespace: 'custom', key: 'internal_note', name: 'Note')
+ create(:custom_field_definition, :short_text_field,
+ namespace: 'custom', key: 'internal_note', label: 'Note')
end
before do
- product.set_metafield(searchable_def, 'mao-tai')
- product.set_metafield(sortable_def, '10')
- product.set_metafield(ignored_def, 'secret')
+ product.set_custom_field(searchable_def, 'mao-tai')
+ product.set_custom_field(sortable_def, '10')
+ product.set_custom_field(ignored_def, 'secret')
end
- it 'indexes searchable and sortable metafield values as cf_* attributes' do
+ it 'indexes searchable and sortable custom_field values as cf_* attributes' do
doc = documents.first
expect(doc['cf_custom_pinyin_name']).to eq('mao-tai')
expect(doc['cf_custom_priority']).to eq(10.0)
@@ -283,25 +283,25 @@ module Spree
end
end
- it 'casts number metafield values to Float' do
- decimal_def = create(:metafield_definition, :number_field, :sortable,
- namespace: 'custom', key: 'rating', name: 'Rating')
- product.set_metafield(decimal_def, '42.5')
+ it 'casts number custom_field values to Float' do
+ decimal_def = create(:custom_field_definition, :number_field, :sortable,
+ namespace: 'custom', key: 'rating', label: 'Rating')
+ product.set_custom_field(decimal_def, '42.5')
doc = described_class.new(product.reload, store).call.first
expect(doc['cf_custom_rating']).to eq(42.5)
end
it 'omits registered keys when the product has no value' do
- create(:metafield_definition, :short_text_field, :searchable,
- namespace: 'custom', key: 'origin', name: 'Origin')
+ create(:custom_field_definition, :short_text_field, :searchable,
+ namespace: 'custom', key: 'origin', label: 'Origin')
doc = described_class.new(product.reload, store).call.first
expect(doc).not_to have_key('cf_custom_origin')
end
it 'includes no cf_* attributes when no definitions are searchable or sortable' do
- Spree::MetafieldDefinition.destroy_all
+ Spree::CustomFieldDefinition.destroy_all
doc = described_class.new(product.reload, store).call.first
expect(doc.keys.grep(/\Acf_/)).to be_empty
diff --git a/spree/core/spec/services/spree/imports/row_processors/product_variant_spec.rb b/spree/core/spec/services/spree/imports/row_processors/product_variant_spec.rb
index 95516442bf..ddcc5439a5 100644
--- a/spree/core/spec/services/spree/imports/row_processors/product_variant_spec.rb
+++ b/spree/core/spec/services/spree/imports/row_processors/product_variant_spec.rb
@@ -303,17 +303,17 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service do
expect(product.reload.categories).to eq [clothing_category]
end
- it 'preserves product metafields' do
- create(:metafield_definition, namespace: 'custom', key: 'brand', name: 'Brand',
- resource_type: 'Spree::Product', metafield_type: 'Spree::Metafields::ShortText')
- product.set_metafield('custom.brand', 'Awesome Brand')
- expect(product.reload.metafields.count).to eq 1
+ it 'preserves product custom_fields' do
+ create(:custom_field_definition, namespace: 'custom', key: 'brand', label: 'Brand',
+ resource_type: 'Spree::Product', field_type: 'Spree::CustomFields::ShortText')
+ product.set_custom_field('custom.brand', 'Awesome Brand')
+ expect(product.reload.custom_fields.count).to eq 1
subject.process!
product.reload
- expect(product.metafields.count).to eq 1
- expect(product.get_metafield('custom.brand').value).to eq 'Awesome Brand'
+ expect(product.custom_fields.count).to eq 1
+ expect(product.get_custom_field('custom.brand').value).to eq 'Awesome Brand'
end
context 'with compare_at_price' do
@@ -596,23 +596,23 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service do
end
end
- context 'with metafields' do
- let!(:brand_metafield_definition) do
- create(:metafield_definition,
+ context 'with custom_fields' do
+ let!(:brand_custom_field_definition) do
+ create(:custom_field_definition,
namespace: 'custom',
key: 'brand',
- name: 'Brand',
+ label: 'Brand',
resource_type: 'Spree::Product',
- metafield_type: 'Spree::Metafields::ShortText')
+ field_type: 'Spree::CustomFields::ShortText')
end
- let!(:material_metafield_definition) do
- create(:metafield_definition,
+ let!(:material_custom_field_definition) do
+ create(:custom_field_definition,
namespace: 'custom',
key: 'material',
- name: 'Material',
+ label: 'Material',
resource_type: 'Spree::Product',
- metafield_type: 'Spree::Metafields::ShortText')
+ field_type: 'Spree::CustomFields::ShortText')
end
let(:row_data) do
@@ -623,62 +623,62 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service do
'price' => '62.99',
'currency' => 'USD'
)
- # Add metafield keys directly to the hash
+ # Add custom_field keys directly to the hash
base_data.merge(
- 'metafield.custom.brand' => 'Awesome Brand',
- 'metafield.custom.material' => 'Cotton'
+ 'custom_field.custom.brand' => 'Awesome Brand',
+ 'custom_field.custom.material' => 'Cotton'
)
end
- # Override the top-level before to create mappings after metafield definitions exist
+ # Override the top-level before to create mappings after custom_field definitions exist
before do
import.create_mappings
end
let(:product) { subject.process! }
- it 'creates mappings for metafields automatically' do
- expect(import.mappings.where(schema_field: 'metafield.custom.brand').exists?).to be true
- expect(import.mappings.where(schema_field: 'metafield.custom.material').exists?).to be true
+ it 'creates mappings for custom_fields automatically' do
+ expect(import.mappings.where(schema_field: 'custom_field.custom.brand').exists?).to be true
+ expect(import.mappings.where(schema_field: 'custom_field.custom.material').exists?).to be true
end
- it 'auto-assigns file_column for metafield mappings when CSV headers match' do
- # Verify CSV headers include metafield keys
- expect(import.csv_headers).to include('metafield.custom.brand', 'metafield.custom.material')
+ it 'auto-assigns file_column for custom_field mappings when CSV headers match' do
+ # Verify CSV headers include custom_field keys
+ expect(import.csv_headers).to include('custom_field.custom.brand', 'custom_field.custom.material')
- brand_mapping = import.mappings.find_by(schema_field: 'metafield.custom.brand')
- material_mapping = import.mappings.find_by(schema_field: 'metafield.custom.material')
+ brand_mapping = import.mappings.find_by(schema_field: 'custom_field.custom.brand')
+ material_mapping = import.mappings.find_by(schema_field: 'custom_field.custom.material')
- expect(brand_mapping.file_column).to eq('metafield.custom.brand')
- expect(material_mapping.file_column).to eq('metafield.custom.material')
+ expect(brand_mapping.file_column).to eq('custom_field.custom.brand')
+ expect(material_mapping.file_column).to eq('custom_field.custom.material')
expect(brand_mapping.mapped?).to be true
expect(material_mapping.mapped?).to be true
end
- it 'sets metafields on the product' do
+ it 'sets custom_fields on the product' do
expect(product).to be_persisted
- expect(product.has_metafield?('custom.brand')).to be true
- expect(product.has_metafield?('custom.material')).to be true
- expect(product.get_metafield('custom.brand').value).to eq 'Awesome Brand'
- expect(product.get_metafield('custom.material').value).to eq 'Cotton'
+ expect(product.has_custom_field?('custom.brand')).to be true
+ expect(product.has_custom_field?('custom.material')).to be true
+ expect(product.get_custom_field('custom.brand').value).to eq 'Awesome Brand'
+ expect(product.get_custom_field('custom.material').value).to eq 'Cotton'
end
- context 'when updating an existing product with metafields' do
+ context 'when updating an existing product with custom_fields' do
let!(:existing_product) do
p = create(:product, slug: 'denim-shirt', name: 'Denim Shirt')
- p.set_metafield('custom.brand', 'Old Brand')
- p.set_metafield('custom.material', 'Old Material')
+ p.set_custom_field('custom.brand', 'Old Brand')
+ p.set_custom_field('custom.material', 'Old Material')
p
end
- it 'updates existing metafields' do
+ it 'updates existing custom_fields' do
expect(product.id).to eq existing_product.id
- expect(product.get_metafield('custom.brand').value).to eq 'Awesome Brand'
- expect(product.get_metafield('custom.material').value).to eq 'Cotton'
+ expect(product.get_custom_field('custom.brand').value).to eq 'Awesome Brand'
+ expect(product.get_custom_field('custom.material').value).to eq 'Cotton'
end
end
- context 'when metafield value is blank' do
+ context 'when custom_field value is blank' do
let(:row_data) do
base_data = csv_row_hash(
'slug' => 'denim-shirt',
@@ -688,23 +688,23 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service do
'currency' => 'USD'
)
base_data.merge(
- 'metafield.custom.brand' => 'Awesome Brand',
- 'metafield.custom.material' => ''
+ 'custom_field.custom.brand' => 'Awesome Brand',
+ 'custom_field.custom.material' => ''
)
end
- it 'skips blank metafield values' do
- expect(product.has_metafield?('custom.brand')).to be true
- expect(product.get_metafield('custom.brand').value).to eq 'Awesome Brand'
- expect(product.has_metafield?('custom.material')).to be false
+ it 'skips blank custom_field values' do
+ expect(product.has_custom_field?('custom.brand')).to be true
+ expect(product.get_custom_field('custom.brand').value).to eq 'Awesome Brand'
+ expect(product.has_custom_field?('custom.material')).to be false
end
end
- context 'when updating existing product metafields with blank values' do
+ context 'when updating existing product custom_fields with blank values' do
let!(:existing_product) do
p = create(:product, slug: 'denim-shirt', name: 'Denim Shirt')
- p.set_metafield('custom.brand', 'Old Brand')
- p.set_metafield('custom.material', 'Old Material')
+ p.set_custom_field('custom.brand', 'Old Brand')
+ p.set_custom_field('custom.material', 'Old Material')
p
end
@@ -717,22 +717,22 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service do
'currency' => 'USD'
)
base_data.merge(
- 'metafield.custom.brand' => 'New Brand',
- 'metafield.custom.material' => ''
+ 'custom_field.custom.brand' => 'New Brand',
+ 'custom_field.custom.material' => ''
)
end
- it 'removes existing metafield when empty value is uploaded' do
- expect(existing_product.metafields.count).to eq 2
+ it 'removes existing custom_field when empty value is uploaded' do
+ expect(existing_product.custom_fields.count).to eq 2
expect(product.id).to eq existing_product.id
- expect(product.has_metafield?('custom.brand')).to be true
- expect(product.get_metafield('custom.brand').value).to eq 'New Brand'
- expect(product.has_metafield?('custom.material')).to be false
- expect(product.metafields.count).to eq 1
+ expect(product.has_custom_field?('custom.brand')).to be true
+ expect(product.get_custom_field('custom.brand').value).to eq 'New Brand'
+ expect(product.has_custom_field?('custom.material')).to be false
+ expect(product.custom_fields.count).to eq 1
end
- context 'when all metafields have blank values' do
+ context 'when all custom_fields have blank values' do
let(:row_data) do
base_data = csv_row_hash(
'slug' => 'denim-shirt',
@@ -742,18 +742,18 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service do
'currency' => 'USD'
)
base_data.merge(
- 'metafield.custom.brand' => '',
- 'metafield.custom.material' => ''
+ 'custom_field.custom.brand' => '',
+ 'custom_field.custom.material' => ''
)
end
- it 'removes all existing metafields' do
- expect(existing_product.metafields.count).to eq 2
+ it 'removes all existing custom_fields' do
+ expect(existing_product.custom_fields.count).to eq 2
expect(product.id).to eq existing_product.id
- expect(product.has_metafield?('custom.brand')).to be false
- expect(product.has_metafield?('custom.material')).to be false
- expect(product.metafields.count).to eq 0
+ expect(product.has_custom_field?('custom.brand')).to be false
+ expect(product.has_custom_field?('custom.material')).to be false
+ expect(product.custom_fields.count).to eq 0
end
end
end
@@ -761,8 +761,8 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service do
context 'when processing a variant row' do
let!(:existing_product) do
p = create(:product, slug: 'denim-shirt', name: 'Denim Shirt')
- p.set_metafield('custom.brand', 'Awesome Brand')
- p.set_metafield('custom.material', 'Cotton')
+ p.set_custom_field('custom.brand', 'Awesome Brand')
+ p.set_custom_field('custom.material', 'Cotton')
p
end
@@ -776,22 +776,22 @@ RSpec.describe Spree::Imports::RowProcessors::ProductVariant, type: :service do
'option1_value' => 'Blue',
'option2_name' => 'Size',
'option2_value' => 'XS',
- 'metafield.custom.brand' => '',
- 'metafield.custom.material' => ''
+ 'custom_field.custom.brand' => '',
+ 'custom_field.custom.material' => ''
)
end
- it 'does not clear out existing metafield values' do
- expect(existing_product.metafields.count).to eq 2
+ it 'does not clear out existing custom_field values' do
+ expect(existing_product.custom_fields.count).to eq 2
product = variant.product
expect(product.id).to eq existing_product.id
- expect(product.has_metafield?('custom.brand')).to be true
- expect(product.get_metafield('custom.brand').value).to eq 'Awesome Brand'
- expect(product.has_metafield?('custom.material')).to be true
- expect(product.get_metafield('custom.material').value).to eq 'Cotton'
- expect(product.metafields.count).to eq 2
+ expect(product.has_custom_field?('custom.brand')).to be true
+ expect(product.get_custom_field('custom.brand').value).to eq 'Awesome Brand'
+ expect(product.has_custom_field?('custom.material')).to be true
+ expect(product.get_custom_field('custom.material').value).to eq 'Cotton'
+ expect(product.custom_fields.count).to eq 2
end
end
end
diff --git a/spree/core/spec/services/spree/sample_data/loader_spec.rb b/spree/core/spec/services/spree/sample_data/loader_spec.rb
index af1f289f90..45fbdf2875 100644
--- a/spree/core/spec/services/spree/sample_data/loader_spec.rb
+++ b/spree/core/spec/services/spree/sample_data/loader_spec.rb
@@ -58,13 +58,13 @@ RSpec.describe Spree::SampleData::Loader, type: :service, without_global_store:
# A required field with no value in the CSV would block the merchant from
# re-activating that product in the dashboard.
it 'backs every required field with a value on every product of the type' do
- incomplete = Spree::Product.includes(:product_type, metafields: :metafield_definition).select do |product|
+ incomplete = Spree::Product.includes(:product_type, custom_fields: :custom_field_definition).select do |product|
next false if product.product_type.nil?
required_ids = product.product_type.product_type_custom_field_definitions.required.
map(&:custom_field_definition_id)
- filled_ids = product.metafields.select { |metafield| metafield.value.present? }.
- map(&:metafield_definition_id)
+ filled_ids = product.custom_fields.select { |custom_field| custom_field.value.present? }.
+ map(&:custom_field_definition_id)
(required_ids - filled_ids).any?
end
@@ -74,7 +74,7 @@ RSpec.describe Spree::SampleData::Loader, type: :service, without_global_store:
it 'fills the required fields on the imported products' do
product = Spree::Product.joins(:product_type).find_by(spree_product_types: { name: 'Kitchen Appliance' })
- expect(product.metafields.map { |metafield| metafield.metafield_definition.key }).
+ expect(product.custom_fields.map { |custom_field| custom_field.custom_field_definition.key }).
to include('wattage', 'voltage', 'warranty')
end
end
diff --git a/spree/core/spec/services/spree/search_provider/metafield_schema_spec.rb b/spree/core/spec/services/spree/search_provider/custom_field_schema_spec.rb
similarity index 71%
rename from spree/core/spec/services/spree/search_provider/metafield_schema_spec.rb
rename to spree/core/spec/services/spree/search_provider/custom_field_schema_spec.rb
index e008d4e4e4..ea6dea9e29 100644
--- a/spree/core/spec/services/spree/search_provider/metafield_schema_spec.rb
+++ b/spree/core/spec/services/spree/search_provider/custom_field_schema_spec.rb
@@ -2,13 +2,13 @@
require 'spec_helper'
-RSpec.describe Spree::SearchProvider::MetafieldSchema do
+RSpec.describe Spree::SearchProvider::CustomFieldSchema do
subject(:schema) { described_class.new }
describe 'accessors' do
it 'exposes definitions by cf_* key' do
- definition = create(:metafield_definition, :number_field, :sortable, :searchable,
- namespace: 'custom', key: 'weight', name: 'Weight')
+ definition = create(:custom_field_definition, :number_field, :sortable, :searchable,
+ namespace: 'custom', key: 'weight', label: 'Weight')
entry = schema.entry_for('cf_custom_weight')
@@ -20,8 +20,8 @@ RSpec.describe Spree::SearchProvider::MetafieldSchema do
describe '#entries' do
it 'exposes participating definitions keyed by filter_key' do
- label = create(:metafield_definition, :short_text_field, :searchable, namespace: 'custom', key: 'label')
- priority = create(:metafield_definition, :number_field, :sortable, namespace: 'custom', key: 'priority')
+ label = create(:custom_field_definition, :short_text_field, :searchable, namespace: 'custom', key: 'label')
+ priority = create(:custom_field_definition, :number_field, :sortable, namespace: 'custom', key: 'priority')
expect(schema.entries).to include(
'cf_custom_label' => label,
@@ -32,7 +32,7 @@ RSpec.describe Spree::SearchProvider::MetafieldSchema do
describe '#parse_sort' do
before do
- create(:metafield_definition, :short_text_field, :sortable, namespace: 'custom', key: 'name')
+ create(:custom_field_definition, :short_text_field, :sortable, namespace: 'custom', key: 'name')
end
it 'parses ascending and descending cf_* sorts' do
@@ -41,7 +41,7 @@ RSpec.describe Spree::SearchProvider::MetafieldSchema do
end
it 'returns nil for unknown or non-sortable keys' do
- create(:metafield_definition, :short_text_field, :searchable, namespace: 'custom', key: 'notes')
+ create(:custom_field_definition, :short_text_field, :searchable, namespace: 'custom', key: 'notes')
expect(schema.parse_sort('cf_custom_unknown')).to be_nil
expect(schema.parse_sort('name')).to be_nil
@@ -50,8 +50,8 @@ RSpec.describe Spree::SearchProvider::MetafieldSchema do
end
describe '#parse_filter' do
- let!(:label) { create(:metafield_definition, :short_text_field, :searchable, namespace: 'custom', key: 'label') }
- let!(:weight) { create(:metafield_definition, :number_field, :sortable, namespace: 'custom', key: 'weight') }
+ let!(:label) { create(:custom_field_definition, :short_text_field, :searchable, namespace: 'custom', key: 'label') }
+ let!(:weight) { create(:custom_field_definition, :number_field, :sortable, namespace: 'custom', key: 'weight') }
it 'splits a cf_* predicate key into definition and predicate' do
expect(schema.parse_filter('cf_custom_label_cont')).to eq(definition: label, predicate: 'cont')
@@ -74,7 +74,7 @@ RSpec.describe Spree::SearchProvider::MetafieldSchema do
# `label` + the `eq` predicate. Longest-key-first resolution makes the
# more specific definition win.
it 'prefers the longest matching search key when a key ends in a predicate name' do
- label_eq = create(:metafield_definition, :short_text_field, :searchable, namespace: 'custom', key: 'label_eq')
+ label_eq = create(:custom_field_definition, :short_text_field, :searchable, namespace: 'custom', key: 'label_eq')
expect(schema.parse_filter('cf_custom_label_eq_cont')).to eq(definition: label_eq, predicate: 'cont')
expect(schema.parse_filter('cf_custom_label_eq')).to eq(definition: label, predicate: 'eq')
@@ -83,8 +83,8 @@ RSpec.describe Spree::SearchProvider::MetafieldSchema do
describe '#filterable_attribute_keys' do
it 'returns every participating search key' do
- create(:metafield_definition, :short_text_field, :searchable, namespace: 'custom', key: 'label')
- create(:metafield_definition, :number_field, :sortable, namespace: 'custom', key: 'weight')
+ create(:custom_field_definition, :short_text_field, :searchable, namespace: 'custom', key: 'label')
+ create(:custom_field_definition, :number_field, :sortable, namespace: 'custom', key: 'weight')
expect(schema.filterable_attribute_keys).to contain_exactly('cf_custom_label', 'cf_custom_weight')
end
@@ -92,8 +92,8 @@ RSpec.describe Spree::SearchProvider::MetafieldSchema do
describe '#sort_ids' do
before do
- create(:metafield_definition, :short_text_field, :sortable, namespace: 'custom', key: 'color')
- create(:metafield_definition, :number_field, :sortable, namespace: 'custom', key: 'weight')
+ create(:custom_field_definition, :short_text_field, :sortable, namespace: 'custom', key: 'color')
+ create(:custom_field_definition, :number_field, :sortable, namespace: 'custom', key: 'weight')
end
it 'returns both ascending and descending variants' do
@@ -106,8 +106,8 @@ RSpec.describe Spree::SearchProvider::MetafieldSchema do
describe '#sort_options' do
it 'returns labeled ascending and descending options for text fields' do
- create(:metafield_definition, :short_text_field, :sortable,
- namespace: 'custom', key: 'label', name: 'Material')
+ create(:custom_field_definition, :short_text_field, :sortable,
+ namespace: 'custom', key: 'label', label: 'Material')
expect(schema.sort_options).to include(
{ id: 'cf_custom_label', label: "Material (#{Spree.t(:sort_a_to_z)})" },
@@ -116,8 +116,8 @@ RSpec.describe Spree::SearchProvider::MetafieldSchema do
end
it 'returns low-high labels for number fields' do
- create(:metafield_definition, :number_field, :sortable,
- namespace: 'custom', key: 'weight', name: 'Weight')
+ create(:custom_field_definition, :number_field, :sortable,
+ namespace: 'custom', key: 'weight', label: 'Weight')
expect(schema.sort_options).to include(
{ id: 'cf_custom_weight', label: "Weight (#{Spree.t(:sort_low_to_high)})" },
@@ -126,8 +126,8 @@ RSpec.describe Spree::SearchProvider::MetafieldSchema do
end
it 'translates direction suffixes for the current locale' do
- create(:metafield_definition, :number_field, :sortable,
- namespace: 'custom', key: 'weight', name: 'Weight')
+ create(:custom_field_definition, :number_field, :sortable,
+ namespace: 'custom', key: 'weight', label: 'Weight')
I18n.backend.store_translations(:pl, spree: {
sort_low_to_high: 'od najniższej',
@@ -148,7 +148,7 @@ RSpec.describe Spree::SearchProvider::MetafieldSchema do
describe '#schema_version' do
it 'returns a stamp derived from participating entries' do
- definition = create(:metafield_definition, :short_text_field, :sortable,
+ definition = create(:custom_field_definition, :short_text_field, :sortable,
namespace: 'custom', key: 'weight')
version = schema.schema_version