Sha256: d63d1f9c3dacaa5bf30f569146d352e1037327a2e805cd35472fc48648577c5f

Contents?: true

Size: 1.82 KB

Versions: 1

Compression:

Stored size: 1.82 KB

Contents

module ActiveData
  module Model
    module Attributes
      class Attribute < Base
        delegate :defaultizer, :enumerizer, :normalizers, to: :reflection

        def write value
          return if readonly?
          pollute do
            write_value value
          end
        end

        def read
          variable_cache(:value) do
            normalize(enumerize(typecast(read_before_type_cast)))
          end
        end

        def read_before_type_cast
          variable_cache(:value_before_type_cast) do
            defaultize(@value_cache)
          end
        end

        def default
          defaultizer.is_a?(Proc) ? evaluate(&defaultizer) : defaultizer
        end

        def defaultize value, default_value = nil
          defaultizer && value.nil? ? default_value || default : value
        end

        def enum
          source = enumerizer.is_a?(Proc) ? evaluate(&enumerizer) : enumerizer

          case source
          when Range
            source.to_a
          when Set
            source
          else
            Array.wrap(source)
          end.to_set
        end

        def enumerize value
          set = enum if enumerizer
          value if !set || (set.none? || set.include?(value))
        end

        def normalize value
          if normalizers.none?
            value
          else
            normalizers.inject(value) do |value, normalizer|
              case normalizer
              when Proc
                evaluate(value, &normalizer)
              when Hash
                normalizer.inject(value) do |value, (name, options)|
                  ActiveData.normalizer(name).call(value, options, self)
                end
              else
                ActiveData.normalizer(normalizer).call(value, {}, self)
              end
            end
          end
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
active_data-1.0.0 lib/active_data/model/attributes/attribute.rb