class TemplateParams::Assertion

A simple assertion suitable for view template preconditions.

Public Class Methods

assert(type = nil, options = {}, &block) click to toggle source

Convenience constructor. @api public

# File lib/template_params/assertion.rb, line 16
def self.assert(type = nil, options = {}, &block)
  new(type, options).apply(&block)
end
new(type, options) click to toggle source

@api public

# File lib/template_params/assertion.rb, line 9
def initialize(type, options)
  @type = type
  @options = options
end

Public Instance Methods

apply(&block) click to toggle source

Apply the instantiated assertion to the given block. @api public

# File lib/template_params/assertion.rb, line 22
def apply(&block)
  assert_type assert_defined(&block)
end

Private Instance Methods

allow_nil() click to toggle source

@api private

# File lib/template_params/assertion.rb, line 29
def allow_nil
  @options.fetch(:allow_nil, false)
end
assert_defined() { || ... } click to toggle source

Calls (yields to) the given block, and asserts that it does not raise a NameError. Returns the return value of the block. @api private

# File lib/template_params/assertion.rb, line 36
def assert_defined(&block)
  value = nil
  begin
    value = yield
  rescue NameError => e
    raise ArgumentError, udef_msg(e, block)
  end
  value
end
assert_type(value) click to toggle source

Raises a `TypeError` if `value` is not of `@type`. @api private

# File lib/template_params/assertion.rb, line 48
def assert_type(value)
  unless @type.nil? || value.is_a?(@type) || allow_nil && value.nil?
    raise TypeError, format("Expected %s, got %s", @type, value.class)
  end
end
udef_msg(name_error, block) click to toggle source

Given a `NameError` and the block, return a string like:

Undefined template parameter: undefined local variable or method `banana' for ..: template_param(::Banana, allow_nil: true) { banana }

`Proc#source` is provided by the `method_source` gem.

@api private

# File lib/template_params/assertion.rb, line 63
def udef_msg(name_error, block)
  prefix = "Undefined template parameter: #{name_error}"
  if block.respond_to?(:source)
    format("%s: %s", prefix, block.source.strip)
  else
    prefix
  end
end