Sha256: dd17c7dd3ad5621b8264215642d2429654f1ec04a8a73d65419a4b14cac3b8bd

Contents?: true

Size: 1.29 KB

Versions: 3

Compression:

Stored size: 1.29 KB

Contents

module RiceBubble
  class Attributes
    class Base
      def initialize(&block)
        @fetcher = block
      end

      def fetch(object, name)
        if @fetcher
          @fetcher.call(object, name)
        elsif object.respond_to?(name)
          object.public_send(name)
        else
          object[name]
        end
      end

      def valid?(_value)
        true
      end

      def coerce(value)
        value
      end

      def validate!(value, coerced:, path:)
        return if valid?(coerced)

        raise ValidationError,
              "#{path} expected #{description} but received #{value.inspect}"
      end

      def call(value, path: '')
        coerced = coerce(value)
        validate!(value, coerced:, path:)
        coerced
      end

      def optional
        Optional.new(self)
      end

      def description
        soft_name = self.class.name.split('::').last
          .gsub(/([a-z])([A-Z])/, '\1 \2')
          .downcase
        article = soft_name.start_with?(/[aeiou]/) ? 'an' : 'a'
        "#{article} #{soft_name}"
      end

      private

      def instantiate(class_or_instance)
        if class_or_instance.is_a?(Class) && class_or_instance < Serializer
          class_or_instance.new
        else
          class_or_instance
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
rice_bubble-0.1.2 lib/rice_bubble/attributes/base.rb
rice_bubble-0.1.1 lib/rice_bubble/attributes/base.rb
rice_bubble-0.1.0 lib/rice_bubble/attributes/base.rb