How do you give a plain Ruby FareQuote class as_json(only:, methods:) support with ActiveModel::Serializers::JSON, and what must the class define?
answer
- include the module, not inherit
- an attributes Hash with String keys
- values come from reader methods
- read_attribute_for_serialization hook
- root: true uses model_name.element
basics
~20 sInclude ActiveModel::Serializers::JSON and define an attributes method returning a Hash with String keys; each key needs a reader method, because values are read by calling it. as_json then accepts only:, except:, methods:, include: and root:.
solid answer
~40 s`ActiveModel::Serializers::JSON` brings Active Record's JSON behaviour to any Ruby class. You `include` it and define `attributes`, a Hash whose **keys** list the serializable attribute names as Strings. Only the keys are used: each value is read through `read_attribute_for_serialization(name)`, which by default calls the method of that name, so every key needs a reader. String keys matter because `only:` and `except:` are converted to strings and compared with them; symbol keys make `only: [:total_cents]` match nothing. Once that is in place, `as_json(only:, except:, methods:, include:)` behaves as on a model, `root: true` wraps the hash under `model_name.element` (`"fare_quote"`), and `from_json` works if you also define `attributes=`. With `ActiveModel::Attributes`, `attributes` already returns String keys.
code
ruby · 17 linesclass FareQuote
include ActiveModel::Model
include ActiveModel::Attributes
include ActiveModel::Serializers::JSON
attribute :flight_number, :string
attribute :cabin, :string
attribute :total_cents, :integer
attribute :currency, :string
attr_accessor :supplier_net_cents # not an attribute, never serialized by default
end
quote = FareQuote.new(flight_number: "KJ 118", cabin: "economy", total_cents: 12900, currency: "EUR")
quote.supplier_net_cents = 10450
quote.as_json(only: [:total_cents, :currency])
# => {"total_cents"=>12900, "currency"=>"EUR"}go deeper
Know that ActiveModel::Serializers::JSON gives non-database classes the same as_json options as models.
Explain the attributes contract: String keys as the allow-list, values read through read_attribute_for_serialization.
Use it on service and search-result objects so internal fields stay out by construction rather than by remembering except:.
Weigh ActiveModel serialization against dedicated presenter classes for objects whose shape varies by client.
## Why a plain object needs this A flight search often returns objects that are **not** database rows: a `FareQuote` assembled from a pricing engine's reply, with a total, a currency, an expiry and some internal fields such as the supplier's net cost. Without help, Active Support's default `Object#as_json` serializes a plain object by dumping its **instance variables**, every one of them, with no `only:` or `except:`. That is how internal values leak from service objects. **`ActiveModel::Serializers::JSON`** gives such a class the same `as_json` and `serializable_hash` that Active Record models have. It includes `ActiveModel::Serialization` and extends `ActiveModel::Naming`, so the class also gets a `model_name`. ## What the class must define ```ruby class FareQuote include ActiveModel::Serializers::JSON attr_reader :flight_number, :cabin, :total_cents, :currency, :expires_at, :supplier_net_cents def initialize(**attrs) = attrs.each { |k, v| instance_variable_set("@#{k}", v) } def attributes { "flight_number" => nil, "cabin" => nil, "total_cents" => nil, "currency" => nil, "expires_at" => nil } end end ``` The contract, from `ActiveModel::Serialization`: 1. **`attributes` returns a Hash.** Its keys are the names that may be serialized; `supplier_net_cents` is left out, so it can never appear unless a caller adds it with `methods:`. 2. **Keys are Strings.** `serializable_hash` turns `only:` and `except:` into strings and intersects or subtracts them from the key list. With symbol keys, `only: [:total_cents]` intersects `["total_cents"]` with `[:total_cents]` and finds nothing. 3. **Values are read, not copied.** For each key Rails calls `read_attribute_for_serialization(key)`, which defaults to `send(key)`. The hash's values are ignored, so the `nil`s above are fine, and every key needs a method. ## What you get | Call | Result | |---|---| | `quote.as_json` | every key in `attributes`, values from the readers | | `quote.as_json(only: [:total_cents, :currency])` | just those two | | `quote.as_json(methods: [:expired?])` | attributes plus `"expired?"` | | `quote.as_json(root: true)` | `{ "fare_quote" => { ... } }` via `model_name.element` | | `render json: quotes, only: [...]` | each quote shaped the same way | `include_root_in_json` is a class attribute defaulting to `false`; setting it to `true` makes `root` the default for that class. ## Overriding where values come from When data lives in a hash rather than in readers, override the hook instead of adding methods: ```ruby def read_attribute_for_serialization(key) = @data.fetch(key) ``` The same hook lets you format a value for every serializer at once, for example returning `expires_at.utc`. ## Using ActiveModel::Attributes A class that includes `ActiveModel::Model` and `ActiveModel::Attributes` declares typed attributes with `attribute :total_cents, :integer`. Its `attributes` method already returns a Hash with String keys, and readers exist for each declared attribute, so including `ActiveModel::Serializers::JSON` is enough. Internal values then belong in plain instance variables rather than in `attribute` declarations, so they stay out of the list. ## Reading JSON back `from_json(json_string)` parses the string and passes the hash to `attributes=`, which you must define (or get from `ActiveModel::Attributes`). Passing `true` as the second argument expects a root key, matching `as_json(root: true)`. It is handy in tests and for caching a quote as JSON, though most APIs only emit. ## Mistakes that look like they work - **Listing an internal field in `attributes`.** The list is the allow-list; putting `supplier_net_cents` there publishes it to every caller that omits `only:`. - **Returning instance values as `attributes`.** `instance_values` has String keys, so it appears to work, but it exposes every ivar, which defeats the point. - **Expecting the hash's values to be used.** An `attributes` hash built as `{ "total_cents" => total_cents * 100 }` still serializes the reader's value, because values are read through `read_attribute_for_serialization`. - **Forgetting the reader.** A key without a method raises `NoMethodError` the first time the object is serialized, often only in production paths that tests skipped.
- What does render json: quote send for a plain object that does not include ActiveModel::Serializers::JSON?Active Support's `Object#as_json` is used: if the object responds to `to_hash` that hash is serialized, otherwise its `instance_values`, meaning every instance variable. A supplier net cost held in an ivar would be sent. Including the module and listing `attributes` turns that implicit dump into an explicit allow-list.
- Can a FareQuote use include: like an Active Record model?Yes. `include: :flight` makes `serializable_hash` call `quote.flight` and then `serializable_hash` on the result, so the returned object must itself support it, for example another class including `ActiveModel::Serializers::JSON`, or an Active Record model. Nested options work the same way as on models.
- ActiveModel::Serializers::JSON serializes the values stored in the attributes hash.
- Symbol keys in attributes work the same as String keys with only:.
- A plain Ruby object without the module serializes to an empty object.
- as_json(root: true) wraps the hash under the class name FareQuote.
- Including the module requires inheriting from ApplicationRecord.