Class: Blueprinter::Base

Inherits:
Object
  • Object
show all
Extended by:
Reflection, Rendering
Defined in:
lib/blueprinter/base.rb

Class Method Summary collapse

Methods included from Reflection

reflections

Methods included from Rendering

hashify, prepare, render, render_as_hash, render_as_json

Class Method Details

.association(method, options = {}) {|object, options| ... } ⇒ Association

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

Passing a block to be evaluated as the value.

class UserBlueprint < Blueprinter::Base
  association :vehicles, blueprint: VehiclesBlueprint do |user, opts|
    user.vehicles + opts[:additional_vehicles]
  end
end

Parameters:

  • method (Symbol)

    the association name

  • options (Hash) (defaults to: {})

    options to overide defaults.

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.

Yields:

  • (object, options)

    The object and the options passed to render are also yielded to the block.

Returns:

Raises:



155
156
157
158
159
160
161
162
163
164
165
166
167
168
# File 'lib/blueprinter/base.rb', line 155

def association(method, options = {}, &block)
  raise ArgumentError, ':blueprint must be provided when defining an association' unless options[:blueprint]

  method = method.to_sym
  current_view << Association.new(
    method:,
    name: options.fetch(:name) { method },
    extractor: options.fetch(:extractor) { AssociationExtractor.new },
    blueprint: options.fetch(:blueprint),
    parent_blueprint: self,
    view: options.fetch(:view, :default),
    options: options.except(:name, :extractor, :blueprint, :view).merge(block:)
  )
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]

Parameters:

  • field_name (Symbol)

    the field to exclude from the current view.

Returns:

  • (Array<Symbol>)

    an array of field names



287
288
289
# File 'lib/blueprinter/base.rb', line 287

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

.excludes(*field_names) ⇒ Array<Symbol>

When mixing multiple views under a single view, some fields may required to be excluded from current view

Examples:

Excluding mutiple fields from being included into the current view.

view :normal do
  fields :name,:address,:position,
        :company, :contact
end
view :special do
  include_view :normal
  fields :birthday,:joining_anniversary
  excludes :position,:address
end
=> [:name, :company, :contact, :birthday, :joining_anniversary]

Parameters:

  • the (Array<Symbol>)

    fields to exclude from the current view.

Returns:

  • (Array<Symbol>)

    an array of field names



309
310
311
# File 'lib/blueprinter/base.rb', line 309

def excludes(*field_names)
  current_view.exclude_fields(field_names)
end

.field(method, options = {}) {|object, options| ... } ⇒ 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 do |object, options|
    "options[:title_prefix] #{object.first_name} #{object.last_name}"
  end
  # other code
end

Passing an if proc and unless method.

class UserBlueprint < Blueprinter::Base
  def skip_first_name?(_field_name, user, options)
    user.first_name == options[:first_name]
  end

  field :first_name, unless: :skip_first_name?
  field :last_name, if: ->(_field_name, user, options) { user.first_name != options[:first_name] }
  # other code
end

Parameters:

  • method (Symbol)

    the field or method name you want to include for serialization.

  • options (Hash) (defaults to: {})

    options to overide defaults.

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.

  • :datetime_format (String, Proc)

    Format Date or DateTime object If the option provided is a String, the object will be formatted with given strftime formatting. If this option is a Proc, the object will be formatted by calling the provided Proc on the Date/DateTime object.

  • :if (Symbol, Proc)

    Specifies a method, proc or string to call to determine if the field should be included (e.g. ‘if: :include_name?, or if: Proc.new { |_field_name, user, options| options == user }). The method, proc or string should return or evaluate to a true or false value.

  • :unless (Symbol, Proc)

    Specifies a method, proc or string to call to determine if the field should be included (e.g. ‘unless: :include_name?, or unless: Proc.new { |_field_name, user, options| options != user }). The method, proc or string should return or evaluate to a true or false value.

Yields:

  • (object, options)

    The object and the options passed to render are also yielded to the block.

Returns:

  • (Field)

    A Field object



113
114
115
116
117
118
119
120
121
122
123
# File 'lib/blueprinter/base.rb', line 113

def field(method, options = {}, &block)
  method = method.to_sym

  current_view << Field.new(
    method,
    options.fetch(:name) { method },
    options.fetch(:extractor) { Blueprinter.configuration.extractor_default.new },
    self,
    options.merge(block:)
  )
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

Parameters:

  • method (Symbol)

    the field or method name you want to include for serialization.

Returns:

  • (Array<Symbol>)

    an array of field names



183
184
185
186
187
# File 'lib/blueprinter/base.rb', line 183

def fields(*field_names)
  field_names.each do |field_name|
    field(field_name)
  end
end

.identifier(method, name: method, extractor: Blueprinter.configuration.extractor_default.new) {|object, options| ... } ⇒ Field

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

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

Examples:

Specifying a uuid as an identifier.

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

Passing a block to be evaluated as the value.

class UserBlueprint < Blueprinter::Base
  identifier :uuid do |user, options|
    options[:current_user].anonymize(user.uuid)
  end
end

Parameters:

Yields:

  • (object, options)

    The object and the options passed to render are also yielded to the block.

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

Returns:

  • (Field)

    A Field object



48
49
50
51
52
53
54
55
56
# File 'lib/blueprinter/base.rb', line 48

def identifier(method, name: method, extractor: Blueprinter.configuration.extractor_default.new, &block)
  view_collection[:identifier] << Field.new(
    method,
    name,
    extractor,
    self,
    block:
  )
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

Parameters:

  • view_name (Symbol)

    the view to mix into the current view.

Returns:

  • (Array<Symbol>)

    an array of view names.



242
243
244
# File 'lib/blueprinter/base.rb', line 242

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

.include_views(*view_names) ⇒ Array<Symbol>

Specify additional views that should be mixed into the current view.

@param view_name [Array<Symbol>] the views to mix into the current view.

Examples:

Including the normal and special views into an extended view.

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

Returns:

  • (Array<Symbol>)

    an array of view names.



267
268
269
# File 'lib/blueprinter/base.rb', line 267

def include_views(*view_names)
  current_view.include_views(view_names)
end

.transform(transformer) ⇒ Array<Class>

Specify one transformer to be included for serialization. Takes a class which extends Blueprinter::Transformer

Examples:

Specifying a DynamicFieldTransformer transformer for including dynamic fields to be serialized.

class User
  def custom_columns
    dynamic_fields # which is an array of some columns
  end

  def custom_fields
    custom_columns.each_with_object({}) { |col,result| result[col] = send(col) }
  end
end

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

class DynamicFieldTransformer < Blueprinter::Transformer
  def transform(hash, object, options)
    hash.merge!(object.dynamic_fields)
  end
end

Parameters:

  • class

    name [Class] which implements the method transform to include for serialization.

Returns:

  • (Array<Class>)

    an array of transformers



220
221
222
# File 'lib/blueprinter/base.rb', line 220

def transform(transformer)
  current_view.add_transformer(transformer)
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

Parameters:

  • view_name (Symbol)

    the view name

Yield Returns:

Returns:

  • (View)

    a Blueprinter::View object



328
329
330
331
332
333
# File 'lib/blueprinter/base.rb', line 328

def view(view_name)
  self.view_scope = view_collection[view_name]
  view_collection[:default].track_definition_order(view_name)
  yield
  self.view_scope = view_collection[:default]
end

.view?(view_name) ⇒ Boolean

Check whether or not a Blueprint supports the supplied view. It accepts a view name.

class ExampleBlueprint < Blueprinter::Base

view :custom do
end

end

ExampleBlueprint.view?(:custom) => true
ExampleBlueprint.view?(:doesnt_exist) => false

supported by this Blueprint.

Examples:

With the following Blueprint

Parameters:

  • view_name (Symbol)

    the view name

Returns:

  • (Boolean)

    a boolean value indicating if the view is



352
353
354
# File 'lib/blueprinter/base.rb', line 352

def view?(view_name)
  view_collection.view?(view_name)
end

.view_collectionObject



356
357
358
# File 'lib/blueprinter/base.rb', line 356

def view_collection
  @_view_collection ||= ViewCollection.new
end