Class: Blueprinter::Base

Inherits:
Object
  • Object
show all
Includes:
ActiveRecordHelpers
Defined in:
lib/blueprinter/base.rb

Class Method Summary collapse

Methods included from ActiveRecordHelpers

#active_record_relation?, included

Class Method Details

.association(method, options = {}) ⇒ Field

Specify an associated object to be included for serialization. Takes a required method and an option.

Examples:

Specifying an association

class UserBlueprint < Blueprinter::Base
  # code
  association :vehicles, view: :extended, blueprint: VehiclesBlueprint
  # code
end

Options Hash (options):

  • :blueprint (Symbol)

    Required. Use this to specify the blueprint to use for the associated object.

  • :name (Symbol)

    Use this to rename the association in the JSON output.

  • :view (Symbol)

    Specify the view to use or fall back to to the :default view.

Raises:



104
105
106
107
108
109
110
111
# File 'lib/blueprinter/base.rb', line 104

def self.association(method, options = {})
  raise BlueprinterError, 'blueprint required' unless options[:blueprint]
  name = options.delete(:name) || method
  current_view << Field.new(method,
                                   name,
                                   AssociationExtractor,
                                   options.merge(association: true))
end

.associations(view_name = :default) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



201
202
203
# File 'lib/blueprinter/base.rb', line 201

def self.associations(view_name = :default)
  view_collection.fields_for(view_name).select { |f| f.options[:association] }
end

.exclude(field_name) ⇒ Array<Symbol>

Exclude a field that was mixed into the current view.

Examples:

Excluding a field from being included into the current view.

view :normal do
  fields :position, :company
end
view :special do
  include_view :normal
  field :birthday
  exclude :position
end
#=> [:company, :birthday]


244
245
246
# File 'lib/blueprinter/base.rb', line 244

def self.exclude(field_name)
  current_view.exclude_field(field_name)
end

.field(method, options = {}) {|Object| ... } ⇒ Field

Specify a field or method name to be included for serialization. Takes a required method and an option.

Examples:

Specifying a user’s first_name to be serialized.

class UserBlueprint < Blueprinter::Base
  field :first_name
  # other code
end

Passing a block to be evaluated as the value.

class UserBlueprint < Blueprinter::Base
  field :full_name {|obj| "#{obj.first_name} #{obj.last_name}"}
  # other code
end

Options Hash (options):

  • :extractor (AssociationExtractor, BlockExtractor, HashExtractor, PublicSendExtractor)

    Kind of extractor to use. Either define your own or use Blueprinter’s premade extractors. The Default extractor is AutoExtractor

  • :name (Symbol)

    Use this to rename the method. Useful if if you want your JSON key named differently in the output than your object’s field or method name.

Yields:

  • (Object)

    The object passed to ‘render` is also passed to the block.



72
73
74
75
76
77
78
79
80
81
82
# File 'lib/blueprinter/base.rb', line 72

def self.field(method, options = {}, &block)
  options = if block_given?
    {name: method, extractor: BlockExtractor, block: {method => block}}
  else
    {name: method, extractor: AutoExtractor}
  end.merge(options)
  current_view << Field.new(method,
                            options[:name],
                            options[:extractor],
                            options)
end

.fields(*field_names) ⇒ Array<Symbol>

Specify one or more field/method names to be included for serialization. Takes at least one field or method names.

Examples:

Specifying a user’s first_name and last_name to be serialized.

class UserBlueprint < Blueprinter::Base
  fields :first_name, :last_name
  # other code
end


194
195
196
197
198
# File 'lib/blueprinter/base.rb', line 194

def self.fields(*field_names)
  field_names.each do |field_name|
    current_view << Field.new(field_name, field_name, AutoExtractor)
  end
end

.identifier(method, name: method, extractor: AutoExtractor) ⇒ Field

Specify a field or method name used as an identifier. Usually, this is something like :id

Note: identifiers are always rendered and considerered their own view, similar to the :default view.

Examples:

Specifying a uuid as an identifier.

class UserBlueprint < Blueprinter::Base
  identifier :uuid
  # other code
end


39
40
41
# File 'lib/blueprinter/base.rb', line 39

def self.identifier(method, name: method, extractor: AutoExtractor)
  view_collection[:identifier] << Field.new(method, name, extractor)
end

.include_view(view_name) ⇒ Array<Symbol>

Specify another view that should be mixed into the current view.

Examples:

Including a normal view into an extended view.

class UserBlueprint < Blueprinter::Base
  # other code...
  view :normal do
    fields :first_name, :last_name
  end
  view :extended do
    include_view :normal # include fields specified from above.
    field :description
  end
  #=> [:first_name, :last_name, :description]
end


223
224
225
# File 'lib/blueprinter/base.rb', line 223

def self.include_view(view_name)
  current_view.include_view(view_name)
end

.prepare(object, view_name:, local_options:) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This is the magic method that converts complex objects into a simple hash ready for JSON conversion.

Note: we accept view (public interface) that is in reality a view_name, so we rename it for clarity



162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
# File 'lib/blueprinter/base.rb', line 162

def self.prepare(object, view_name:, local_options:)
  unless view_collection.has_view? view_name
    raise BlueprinterError, "View '#{view_name}' is not defined"
  end
  fields = view_collection.fields_for(view_name)
  prepared_object = include_associations(object, view_name: view_name)
  if array_like?(object)
    prepared_object.map do |obj|
      object_to_hash(obj,
                     view_name: view_name,
                     local_options: local_options)
    end
  else
    object_to_hash(prepared_object,
                   view_name: view_name,
                   local_options: local_options)
  end
end

.render(object, options = {}) ⇒ String

Generates a JSON formatted String. Takes a required object and an optional view.

Examples:

Generating JSON with an extended view

post = Post.all
Blueprinter::Base.render post, view: :extended
# => "[{\"id\":1,\"title\":\"Hello\"},{\"id\":2,\"title\":\"My Day\"}]"

Options Hash (options):

  • :view (Symbol)

    Defaults to :default. The view name that corresponds to the group of fields to be serialized.



129
130
131
132
# File 'lib/blueprinter/base.rb', line 129

def self.render(object, options = {})
  view_name = options.delete(:view) || :default
  jsonify(prepare(object, view_name: view_name, local_options: options))
end

.render_as_hash(object, options = {}) ⇒ Hash

Generates a hash. Takes a required object and an optional view.

Examples:

Generating a hash with an extended view

post = Post.all
Blueprinter::Base.render_as_hash post, view: :extended
# => [{id:1, title: Hello},{id:2, title: My Day}]

Options Hash (options):

  • :view (Symbol)

    Defaults to :default. The view name that corresponds to the group of fields to be serialized.



150
151
152
153
# File 'lib/blueprinter/base.rb', line 150

def self.render_as_hash(object, options= {})
  view_name = options.delete(:view) || :default
  prepare(object, view_name: view_name, local_options: options)
end

.view(view_name) ⇒ View

Specify a view and the fields it should have. It accepts a view name and a block. The block should specify the fields.

Examples:

Using views

view :extended do
  fields :position, :company
  include_view :normal
  exclude :first_name
end

Yield Returns:



263
264
265
266
267
# File 'lib/blueprinter/base.rb', line 263

def self.view(view_name)
  @current_view = view_collection[view_name]
  yield
  @current_view = view_collection[:default]
end