Overview
Scalar types represent primitive leaf values in a GraphQL type system. They are the basic building blocks for all GraphQL values. Inherits from:Rails::GraphQL::Type
Specification: GraphQL Scalar Type Definition
Overview
Scalars work similarly toActiveModel::Type::Value but operate in a singleton fashion rather than with instances. They handle serialization and deserialization of primitive values.
Built-in Scalars
Rails GraphQL includes all standard GraphQL scalar types:Represents signed 32-bit integers
Represents signed double-precision floating-point values
Represents textual data as UTF-8 character sequences
Represents
true or falseRepresents unique identifiers, serialized as strings
Additional Scalars
Rails GraphQL provides extended scalar types:Accepts any JSON-compatible value
Represents large integers beyond the 32-bit range
Represents binary data
Represents date values (without time)
Represents date and time values
Represents arbitrary-precision decimal numbers
Represents JSON data structures
Represents time values (without date)
Class Methods
valid_input?(value)
Check if a value is valid scalar input (before deserialization).
The value to validate
Returns
true if the value is valid for this scalar typevalid_output?(value)
Check if a value is valid scalar output (before serialization).
The value to validate
Returns
true if the value can be serialized by this scalardeserialize(value)
Turn user input into a Ruby object.
The input value to deserialize
The deserialized Ruby value
as_json(value)
Transform a value to its representation in a Hash object.
The value to serialize
The value converted to a string
to_json(value)
Transform a value to its representation in a JSON string.
The value to serialize
The value as a JSON-compatible quoted string
Creating Custom Scalars
Define custom scalar types by inheriting fromRails::GraphQL::Type::Scalar:
Usage Examples
Basic Field with Scalar
Custom Scalar Field
Extended Scalars
With Input
Implementation Details
ActiveRecord Type Integration
Scalars can define anar_type attribute to indicate which ActiveRecord type the value should be cast to when serializing to hash. This helps determine if a cast is necessary.
Token Handling
Scalars automatically handleGQLParser::Token values during deserialization, converting them to appropriate Ruby types.
Setup
Scalars are configured with:- Leaf types: Terminal nodes in the GraphQL tree
- Input types: Can be used in arguments
- Output types: Can be used in fields