Sha256: 2e042174857bafff7eb49c88ba7f180a2ed3ae454827e8557c09aed5e42405ba

Contents?: true

Size: 1.03 KB

Versions: 10

Compression:

Stored size: 1.03 KB

Contents

# frozen_string_literal: true

class Shaped::Shapes::Class < Shaped::Shape
  def initialize(expected_klass, validations = {})
    if !expected_klass.is_a?(Class)
      raise(Shaped::InvalidShapeDescription, "A #{self.class} description must be a Class.")
    end

    @expected_klass = expected_klass
    @validations = validations
    @validator_klass = validator_klass(validations)
  end

  def matched_by?(object)
    object.is_a?(@expected_klass) && validations_satisfied?(object)
  end

  def to_s
    if @validations.empty?
      @expected_klass.name
    else
      "#{@expected_klass} validating #{@validations}"
    end
  end

  private

  def validator_klass(validations)
    return nil if validations.empty?

    Class.new do
      include ActiveModel::Validations

      attr_accessor :value

      validates :value, validations
    end
  end

  def validations_satisfied?(object)
    return true if @validator_klass.nil?

    validator_instance = @validator_klass.new
    validator_instance.value = object
    validator_instance.valid?
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
shaped-0.14.0 lib/shaped/shapes/class.rb
shaped-0.13.0 lib/shaped/shapes/class.rb
shaped-0.12.0 lib/shaped/shapes/class.rb
shaped-0.11.0 lib/shaped/shapes/class.rb
shaped-0.10.0 lib/shaped/shapes/class.rb
shaped-0.9.1 lib/shaped/shapes/class.rb
shaped-0.9.0 lib/shaped/shapes/class.rb
shaped-0.8.2 lib/shaped/shapes/class.rb
shaped-0.8.0 lib/shaped/shapes/class.rb
shaped-0.7.3 lib/shaped/shapes/class.rb