Exclude If Blank
Here’s a more fully formed version of the ExcludeIfBlank extension from the previous section.
It works just like the built-in exclude_if_nil option, but checks for blank? instead. It checks the Blueprint
options first, then allows fields to override it.
class ExcludeIfBlankExtension < Blueprinter::Extension
# @param ctx [Blueprinter::V2::Context::Field]
def around_field_value(ctx)
val = yield ctx
exclude = ctx.blueprint.options[:exclude_if_blank]
exclude = ctx.field.options[:exclude_if_blank] if ctx.field.options.key? :exclude_if_blank
skip! if exclude && val.blank?
val
end
end
Add it to your ApplicationBlueprint and use it in your blueprints.
class ApplicationBlueprint < Blueprinter::V2::Base
add ExcludeIfBlankExtension.new
end
class WidgetBlueprint < ApplicationBlueprint
field :name
field :description, exclude_if_blank: true
end
class CategoryBlueprint < ApplicationBlueprint
set :exclude_if_blank, true
field :name, exclude_if_blank: false
field :description
end