Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
B

blueprinter

> 后端框架
Open source

Simple, Fast, and Declarative Serialization Library for Ruby

1.3K stars0 likes1 views
WebsiteGitHub

About

Simple, Fast, and Declarative Serialization Library for Ruby

Recent Organization Move

Please change your local remote to pull from this repository:

bash
git remote set-url [previous-remote-name] [email protected]:procore-oss/blueprinter.git

to see the previous upstream remote name, run:

bash
git remote -v

Blueprinter

Blueprinter 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.

Documentation

Docs can be found here.

Usage

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:

ruby
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:

json
[
  {
    "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:

ruby
Blueprinter.configure do |config|
  config.custom_array_like_classes = [Mongoid::Criteria]
end

Or if you wanted it to treat the Set class as a collection:

ruby
Blueprinter.configure do |config|
  config.custom_array_like_classes = [Set]
end

Renaming

You can rename the resulting JSON keys in both fields and associations by using the name option.

ruby
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
end

Default 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.

Global Config Setting

ruby
Blueprinter.configure do |config|
  config.field_default = "N/A"
  config.association_default = {}
end

Field-level/Association-level Setting

ruby
class 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
end

NOTE: 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:

ruby
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? }
end

Field-level Setting

ruby
class 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 }
end

Field-level Setting - datetime_format

Usage (String Option):

ruby
class UserBlueprint (datetime) { datetime.nil? ? datetime : datetime.strftime("%s").to_i }
end

Output:

json
{
  "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.

Example

Create a Transform class extending from Blueprinter::Transformer

ruby
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
end
ruby
class 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].options

Extensions

Blueprinter provides an extension system that enables certain behavior to be modified as needed.

ruby
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
end

render_as_hash

Same as render, returns a Ruby Hash.

Usage:

ruby
puts UserBlueprint.render_as_hash(user, company: company)

Output:

ruby
{
  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:

ruby
puts UserBlueprint.render_as_json(user, company: company)

Output:

ruby
{
  "uuid" => "733f0758-8f21-4719-875f-262c3ec743af",
  "company_name" => "My Company LLC"
}

Installation

Add this line to your application's Gemfile:

ruby
gem 'blueprinter'

And then execute:

bash
bundle

Or install it yourself as:

bash
gem install blueprinter

You should also have require 'json' already in your project if you are not using Rails or if you are not using Oj.

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:

ruby
require 'oj' # you can skip this if OJ has already been required.

Blueprinter.configure do |config|
  config.generator = Oj # default is JSON
end

Ensure that you have the Oj gem installed in your Gemfile if you have

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Rubyjsonpresenterrailsresource-serializer

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category后端框架
PricingOpen source

> Related tools

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架