class Contextualizer::Setter

Public Class Methods

new() click to toggle source
# File lib/contextualizer.rb, line 41
def initialize
  @mandatory, @with_default, @optional = [], {}, []
end

Public Instance Methods

add_attrs(*attrs, **opt_attrs) click to toggle source
# File lib/contextualizer.rb, line 45
def add_attrs(*attrs, **opt_attrs)
  optional, with_default = opt_attrs.partition { |_, v| v == OPTIONAL }.map(&:to_h)

  @mandatory |= attrs
  @optional |= optional.keys
  @with_default.merge!(with_default)
end
set(obj, args) click to toggle source
# File lib/contextualizer.rb, line 53
def set(obj, args)
  context = obj.context&.dup || {}

  @with_default.each { |key, default| context[key] = args.fetch(key, default) }
  @optional.each { |key| context[key] = args[key] if args.key?(key) }
  @mandatory.each do |key|
    fail ":#{key} was not found in scope" unless args.key?(key)
    context[key] = args[key]
  end

  context.each do |attr, value|
    obj.instance_variable_set :"@#{attr}", value
  end

  obj.instance_variable_set(:@context, context.freeze)
end