class Actions::SafeContext

Public Class Methods

new(context = {}) click to toggle source
# File lib/actions/safe_context.rb, line 9
def initialize(context = {})
  @context = Context.build(context)
end

Public Instance Methods

input!(name, type: Object, required: false, mutable: false) click to toggle source
# File lib/actions/safe_context.rb, line 13
def input!(name, type: Object, required: false, mutable: false)
  attribute!(name, type: type, readonly: !mutable)
  validate!(name, type: type, required: required)
end
output!(name, type: Object) click to toggle source
# File lib/actions/safe_context.rb, line 18
def output!(name, type: Object)
  attribute!(name, type: type, readonly: false)
end

Private Instance Methods

attribute!(name, type: Object, readonly: false) click to toggle source
# File lib/actions/safe_context.rb, line 24
def attribute!(name, type: Object, readonly: false)
  define_singleton_method(name) do
    @context.__send__(name)
  end

  unless readonly
    define_singleton_method("#{name}=") do |value|
      unless value.is_a?(type)
        raise Errors::InvalidType.new("#{name} allows values of type #{type}, received #{value.class}", self)
      end

      @context.__send__("#{name}=", value)
    end
  end
end
validate!(attribute, type: Object, required: false) click to toggle source
# File lib/actions/safe_context.rb, line 40
def validate!(attribute, type: Object, required: false)
  value = @context.__send__(attribute)

  if required
    if value.nil?
      raise Errors::ValidationFailed.new("expected #{attribute} not to be nil", self)
    end
  end

  if @context.defined?(attribute)
    unless value.is_a?(type)
      raise Errors::ValidationFailed.new("expected #{attribute} to be of type #{type}, is #{value.class}", self)
    end
  end
end