Sha256: fef06a12a652fd5cb2dafab08eb3df4f72a0333d99ca78542ace1819050d8d81

Contents?: true

Size: 1.8 KB

Versions: 1

Compression:

Stored size: 1.8 KB

Contents

module Virtus
  class Attribute

    # Class representing the default value option
    class DefaultValue
      DUP_CLASSES = [ ::NilClass, ::TrueClass, ::FalseClass,
                      ::Numeric,  ::Symbol ].freeze

      # Returns the attribute associated with this default value instance
      #
      # @return [Virtus::Attribute::Object]
      #
      # @api private
      attr_reader :attribute

      # Returns the value instance
      #
      # @return [Object]
      #
      # @api private
      attr_reader :value

      # Initializes an default value instance
      #
      # @param [Virtus::Attribute] attribute
      # @param [Object] value
      #
      # @return [undefined]
      #
      # @api private
      def initialize(attribute, value)
        @attribute, @value = attribute, value
      end

      # Evaluates the value
      #
      # @param [Object]
      #
      # @return [Object] evaluated value
      #
      # @api private
      def evaluate(instance)
        if callable?
          call(instance)
        elsif duplicable?
          value.dup
        else
          value
        end
      end

    private

      # Evaluates a proc value
      #
      # @param [Object]
      #
      # @return [Object] evaluated value
      #
      # @api private
      def call(instance)
        value.call(instance, attribute)
      end

      # Returns if the value is callable
      #
      # @return [TrueClass,FalseClass]
      #
      # @api private
      def callable?
        value.respond_to?(:call)
      end

      # Returns whether or not the value is duplicable
      #
      # # return [TrueClass, FalseClass]
      #
      # @api private
      def duplicable?
        DUP_CLASSES.none? { |klass| value.kind_of?(klass) }
      end

    end # class DefaultValue
  end # class Attribute
end # module Virtus

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
virtus-0.0.10 lib/virtus/attribute/default_value.rb