Sha256: 79a33b6e1fdb2573c300f11be0536823f40d2bf42cc640810b3fa10f71e7f033

Contents?: true

Size: 1.55 KB

Versions: 2

Compression:

Stored size: 1.55 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 = attribute
        @value     = case value when *DUP_CLASSES then value else value.dup end
      end

      # Evaluates the value
      #
      # @param [Object]
      #
      # @return [Object] evaluated value
      #
      # @api private
      def evaluate(instance)
        callable? ? call(instance) : value
      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

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

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
virtus-0.0.9 lib/virtus/attribute/default_value.rb
virtus-0.0.8 lib/virtus/attribute/default_value.rb