Module: Shale::Builder

Extended by:
T::Helpers, T::Sig
Defined in:
lib/shale/builder.rb,
lib/shale/builder/value.rb,
lib/shale/builder/version.rb,
lib/shale/builder/nested_validations.rb,
lib/shale/builder/assigned_attributes.rb

Overview

It’s meant to be included in subclasses of ‘Shale::Mapper` to provide an easier way of building instances.

Example:

require 'shale/builder'

class PaymentInstrument < Shale::Mapper
  include Shale::Builder

  attribute :number, Shale::Type::String
  attribute :expiration_year, ::Shale::Type::Integer
  attribute :expiration_month, ::Shale::Type::Integer
end

class Transaction < ::Shale::Mapper
  include Shale::Builder

  attribute :cvv_code, Shale::Type::String
  attribute :payment_instrument, PaymentInstrument
end

transaction = Transaction.build do |t|
    t.cvv_code = '123'
    t.payment_instrument do |p|
        p.number = '4242424242424242'
        p.expiration_year = 2045
        p.expiration_month = 12
    end
end

@requires_ancestor: Object

Defined Under Namespace

Modules: AssignedAttributes, ClassMethods, NestedValidations Classes: Value

Constant Summary collapse

S =
::Shale::Type
VERSION =
'0.8.5'

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(mod) ⇒ Object

Gets called after including this module in a module or class. : (Module mod) -> void



54
55
56
57
# File 'lib/shale/builder.rb', line 54

def included(mod)
  mod.extend ClassMethods
  Builder.prepare_mod(mod)
end

.prepare_mod(mod) ⇒ Object

Prepares the received module or class for dynamic method definition. : (Module mod) -> void



62
63
64
65
66
# File 'lib/shale/builder.rb', line 62

def prepare_mod(mod)
  builder_methods_module = ::Module.new
  mod.instance_variable_set :@builder_methods_module, builder_methods_module
  mod.include builder_methods_module
end

Instance Method Details

#attribute_valuesObject

Returns an array of shale values that have been assigned.

: -> Array



217
218
219
220
221
222
# File 'lib/shale/builder.rb', line 217

def attribute_values
  klass = self.class #: as untyped
  klass.attributes.map do |name, attr|
    Shale::Builder::Value.new(attr, public_send(name))
  end
end

#inject_context(**context) ⇒ Object

Attempts to set the given attributes and values within this shale builder object and all of its sub-builders. Attributes that aren’t defined are ignored.

: (**untyped) -> void



229
230
231
232
233
234
235
236
237
238
239
240
241
242
# File 'lib/shale/builder.rb', line 229

def inject_context(**context)
  context.each do |name, val|
    setter = :"#{name}="
    public_send(setter, val) if respond_to?(setter)
  end

  klass = self.class #: as untyped
  klass.builder_attributes.each_key do |name|
    val = public_send(name)
    next unless val

    val.inject_context(**context) if respond_to?(:inject_context)
  end
end