module Troupe::Contract

Constants

VALID_TYPES

Public Class Methods

included(base) click to toggle source
# File lib/troupe/contract.rb, line 5
def self.included(base)
  base.class_eval do
    extend ClassMethods
  end

  private

  def violation_table
    @violation_table ||= {}
  end

  def validate_contract_expectations
    populate_violation_table
    check_each_violation
  end

  def missing_properties
    @missing_properties ||= self.class.missing_properties(context)
  end

  def ensure_contract_defaults
    self.class.all_properties.each do |attr|
      send(attr)
    end
  end

  def populate_violation_table
    missing_properties.each do |property_name|
      violation_table[property_name] = ContractViolation.new(
        self,
        property: property_name,
        message: "Expected context to include property '#{property_name}'."
      )
    end
  end

  def check_each_violation
    return if violation_table.empty?
    violation_table.each do |property_name, violation|
      if block = violation_block_for(property_name)
        instance_exec(violation, &block)
      else
        raise violation
      end
    end
  end

  def violation_block_for(property_name)
    self.class.violation_block_for(property_name) ||
      self.class.on_violation_block
  end
end

Public Instance Methods

check_each_violation() click to toggle source
# File lib/troupe/contract.rb, line 41
def check_each_violation
  return if violation_table.empty?
  violation_table.each do |property_name, violation|
    if block = violation_block_for(property_name)
      instance_exec(violation, &block)
    else
      raise violation
    end
  end
end
ensure_contract_defaults() click to toggle source
# File lib/troupe/contract.rb, line 25
def ensure_contract_defaults
  self.class.all_properties.each do |attr|
    send(attr)
  end
end
missing_properties() click to toggle source
# File lib/troupe/contract.rb, line 21
def missing_properties
  @missing_properties ||= self.class.missing_properties(context)
end
populate_violation_table() click to toggle source
# File lib/troupe/contract.rb, line 31
def populate_violation_table
  missing_properties.each do |property_name|
    violation_table[property_name] = ContractViolation.new(
      self,
      property: property_name,
      message: "Expected context to include property '#{property_name}'."
    )
  end
end
validate_contract_expectations() click to toggle source
# File lib/troupe/contract.rb, line 16
def validate_contract_expectations
  populate_violation_table
  check_each_violation
end
violation_block_for(property_name) click to toggle source
# File lib/troupe/contract.rb, line 52
def violation_block_for(property_name)
  self.class.violation_block_for(property_name) ||
    self.class.on_violation_block
end
violation_table() click to toggle source
# File lib/troupe/contract.rb, line 12
def violation_table
  @violation_table ||= {}
end