Sha256: ce811ddf248ac52d0c563433bb0e95c61d937df31de24f75ea0bc508e8dcce34

Contents?: true

Size: 1.85 KB

Versions: 2

Compression:

Stored size: 1.85 KB

Contents

module Virtus
  class Attribute

    # Class representing the default value option
    class DefaultValue
      SINGLETON_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 cloneable?
          value.clone
        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 cloneable
      #
      # # return [TrueClass, FalseClass]
      #
      # @api private
      def cloneable?
        case value
        when *SINGLETON_CLASSES then false
        else
          true
        end
      end

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

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
virtus-0.2.0 lib/virtus/attribute/default_value.rb
virtus-0.1.0 lib/virtus/attribute/default_value.rb