Simple, Fast, and Declarative Serialization Library for Ruby
Simple, Fast, and Declarative Serialization Library for Ruby
Please change your local remote to pull from this repository:
git remote set-url [previous-remote-name] [email protected]:procore-oss/blueprinter.gitto see the previous upstream remote name, run:
git remote -vBlueprinter is a JSON Object Presenter for Ruby that takes business objects and breaks them down into simple hashes and serializes them to JSON. It can be used in Rails in place of other serializers (like JBuilder or ActiveModelSerializers). It is designed to be simple, direct, and performant.
It heavily relies on the idea of views which, similar to Rails views, are ways of predefining output for data in different contexts.
Docs can be found here.
Basic
If you have an object you would like serialized, simply create a blueprint. Say, for example, you have a User record with the following attributes [:uuid, :email, :first_name, :last_name, :password, :address].
You may define a simple blueprint like so:
class UserBlueprint
Collections
You can also pass a collection object or an array to the render method.
```ruby
puts UserBlueprint.render(User.all)This will result in JSON that looks something like this:
[
{
"uuid": "733f0758-8f21-4719-875f-262c3ec743af",
"email": "[email protected]",
"first_name": "John",
"last_name": "Doe"
},
{
"uuid": "733f0758-8f21-4719-875f-743af262c3ec",
"email": "[email protected]",
"first_name": "John",
"last_name": "Doe 2"
}
]You can also configure other classes to be treated like collections. For example, if you are using Mongoid, you can configure it to treat Mongoid::Criteria objects as collections:
Blueprinter.configure do |config|
config.custom_array_like_classes = [Mongoid::Criteria]
endOr if you wanted it to treat the Set class as a collection:
Blueprinter.configure do |config|
config.custom_array_like_classes = [Set]
endRenaming
You can rename the resulting JSON keys in both fields and associations by using the name option.
class UserBlueprint
Views
You may define different outputs by utilizing views:
```ruby
class UserBlueprint
Identifiers
`identifier`s are used to specify a field or method name used as an identifier. Usually, this is something like `:id`.
Example:
```rb
class UserBlueprint
Root
You can also optionally pass in a root key to wrap your resulting json in:
```ruby
class UserBlueprint
Meta Attributes
You can additionally add meta-data to the json as well:
```ruby
class UserBlueprint
Exclude Fields
You can specifically choose to exclude certain fields for specific views
```ruby
class UserBlueprint
Associations
You may include associated objects. Say for example, a user has projects:
```ruby
class ProjectBlueprint (driver) { { trim: driver.preferred_trim } }
end
endDefault Association/Field Option
By default, an association or field that evaluates to nil is serialized as nil. A default serialized value can be specified as an option on the association or field for cases when the association/field could potentially evaluate to nil. You can also specify a global field_default or association_default in the Blueprinter config which will be used for all fields/associations that evaluate to nil.
Blueprinter.configure do |config|
config.field_default = "N/A"
config.association_default = {}
endclass UserBlueprint
default_if
Sometimes, you may want certain "empty" values to pass through to the default value.
Blueprinter provides the ability to treat the following empty types as the default value (or `nil` if no default provided).
### Blueprinter::EMPTY_COLLECTION
An empty array or empty active record collection.
### Blueprinter::EMPTY_HASH
An empty hash.
### Blueprinter::EMPTY_STRING
An empty string or symbol.
#### Field-level/Association-level Setting - EMPTY_STRING
```ruby
class UserBlueprint
Supporting Dynamic Blueprints For Associations
When defining an association, we can dynamically evaluate the blueprint. This comes in handy when adding polymorphic associations, by allowing reuse of existing blueprints.
```ruby
class Task (taskable) {taskable.blueprint}, default: {}
end
endNOTE: taskable.blueprint should return a valid Blueprint class. Currently, has_many is not supported because of the very nature of polymorphic associations.
Defining A Field Directly In The Blueprint
You can define a field directly in the Blueprint by passing it a block. This is especially useful if the object does not already have such an attribute or method defined, and you want to define it specifically for use with the Blueprint. This is done by passing field a block. The block also yields the object and any options that were passed from render. For example:
class UserBlueprint
Accessing the View Option
The `view` provided to the `render` call is implicitly available in the `options` hash within a `field` block, and can be referenced as needed. For example:
```ruby
class UserBlueprint
Defining An Identifier Directly In The Blueprint
You can also pass a block to an identifier:
```ruby
class UserBlueprint
Defining An Association Directly In The Blueprint
You can also pass a block to an association:
```ruby
class ProjectBlueprint
Passing Additional Properties To #render
`render` takes an options hash which you can pass additional properties, allowing you to utilize those additional properties in the `field` block. For example:
```ruby
class UserBlueprint
Conditional Fields
Both the `field` and the global Blueprinter Configuration supports `:if` and `:unless` options that can be used to serialize fields conditionally.
### Global Config Setting - if and unless
```ruby
Blueprinter.configure do |config|
config.if = ->(field_name, obj, _options) { !obj[field_name].nil? }
config.unless = ->(field_name, obj, _options) { obj[field_name].nil? }
endclass UserBlueprint (_field_name, user, options) { user.first_name != options[:first_name] }
field :age, unless: ->(_field_name, user, _options) { user.age
Exclude Fields with nil Values
By default, fields with `nil` values are included when rendering. You can override this behavior by setting `:exclude_if_nil: true` in the field definition.
Usage:
```ruby
class UserBlueprint
Custom Formatting for Dates and Times
To define a custom format for a Date or DateTime field, include the option `datetime_format`.
This global or field-level option can be either a string representing the associated `strftime` format,
or a Proc which receives the original Date/DateTime object and returns the formatted value.
When using a Proc, it is the Proc's responsibility to handle any errors in formatting.
#### Global Config Setting - datetime
If a global datetime_format is set (either as a string format or a Proc), this option will be
invoked and used to format all fields that respond to `strftime`.
```ruby
Blueprinter.configure do |config|
config.datetime_format = ->(datetime) { datetime.nil? ? datetime : datetime.strftime("%s").to_i }
endUsage (String Option):
class UserBlueprint (datetime) { datetime.nil? ? datetime : datetime.strftime("%s").to_i }
endOutput:
{
"name": "John Doe",
"birthday": 762739200
}NOTE: The field-level setting overrides the global config setting (for the field) if both are set.
Transform Classes
Blueprinter provides the ability to specify transforms on views, which enable further
processing and transforming of resulting view field hashes prior to serialization.
Use transform to specify one transformer to be included for serialization.
A transformer is a class, extending Blueprinter::Transformer and implementing the transform method.
The modified hash object will be the resulting hash passed to serialization.
Create a Transform class extending from Blueprinter::Transformer
class DynamicFieldTransformer
Configurable Extractors
Blueprinter gets a given objects' values from the fields definitions using extractor classes. You can substitute your own extractor class globally or per-field.
#### Examples
For a specific kind of field, create an extractor class extending from `Blueprinter::Extractor`
```ruby
class MyFieldExtractor
Sorting Fields
By default the response sorts the keys by name. If you want the fields to be sorted in the order of definition, use the below configuration option.
Usage:
```ruby
Blueprinter.configure do |config|
config.sort_fields_by = :definition
endclass UserBlueprint
Reflection
Blueprint classes may be reflected on to inspect their views, fields, and associations. Extensions often make use of this ability.
```ruby
class WidgetBlueprint [:default, :extended]
# Hashes of fields and associations, keyed by name
fields = views[:default].fields
assoc = views[:default].associations
# Get info about a field
fields[:description].name
fields[:description].display_name
fields[:description].options
# Get info about an association
assoc[:category].name
assoc[:category].display_name
assoc[:category].blueprint
assoc[:category].view
assoc[:category].optionsExtensions
Blueprinter provides an extension system that enables certain behavior to be modified as needed.
Blueprinter.configure do |config|
config.extensions **_NOTE:_** The following are not officially maintained/supported by Procore OSS.
* [blueprinter_schema](https://github.com/thisismydesign/blueprinter_schema) - Create JSON Schemas from Blueprinter Serializers
Deprecations
When functionality in Blueprinter is invoked, that has been deprecated, the default behavior is to
write a deprecation notice to stderror.
However, deprecations can be configured to report at three different levels:
| Key | Result |
|:-----------------:|:---------------------------------------------------------------:|
| `:stderr` (Default) | Deprecations will be written to stderror |
| `:raise` | Deprecations will be raised as `Blueprinter::BlueprinterError`s |
| `:silence` | Deprecations will be silenced and will not be raised or logged |
### Example - deprecations
```ruby
Blueprinter.configure do |config|
config.deprecations = :raise
endrender_as_hash
Same as render, returns a Ruby Hash.
Usage:
puts UserBlueprint.render_as_hash(user, company: company)Output:
{
uuid: "733f0758-8f21-4719-875f-262c3ec743af",
company_name: "My Company LLC"
}render_as_json
Same as render, returns a Ruby Hash JSONified. This will call JSONify all keys and values.
Usage:
puts UserBlueprint.render_as_json(user, company: company)Output:
{
"uuid" => "733f0758-8f21-4719-875f-262c3ec743af",
"company_name" => "My Company LLC"
}Add this line to your application's Gemfile:
gem 'blueprinter'And then execute:
bundleOr install it yourself as:
gem install blueprinterYou should also have require 'json' already in your project if you are not using Rails or if you are not using Oj.
By default, Blueprinter will be calling JSON.generate(object) internally and it expects that you have require 'json' already in your project's code. You may use Oj to generate in place of JSON like so:
require 'oj' # you can skip this if OJ has already been required.
Blueprinter.configure do |config|
config.generator = Oj # default is JSON
endEnsure that you have the Oj gem installed in your Gemfile if you have
No open issues yet, or sync has not completed.