Sha256: f07b73603066ab3dc18f2b101f76de84194f83b0c410a24cdec0cbc408b701f3

Contents?: true

Size: 1.61 KB

Versions: 2

Compression:

Stored size: 1.61 KB

Contents

require 'golden_fleece/definitions'
require 'hana'

module GoldenFleece
  class Value
    include Utility
    
    def initialize(schema)
      @schema = schema
      self.value_initialized = false
    end

    def compute(record)
      @record = record

      if dirty?
        @value = Hana::Pointer.new(schema.json_path).eval(record.read_attribute(schema.attribute))

        cast_booleans
        apply_normalizers
        apply_default

        self.value_initialized = true
      end

      value
    end

    private

    attr_accessor :value_initialized
    attr_reader :schema, :record, :value

    def dirty?
      record.send("#{schema.attribute}_changed?") || !value_initialized
    end

    # Cast boolean values the way that Rails normally does on boolean columns
    def cast_booleans
      if schema.types.include? Definitions::TYPES[:boolean]
        @value = cast_boolean(value)
      end
    end

    def apply_normalizers
      @value = schema.normalizers.reduce(value) { |memo, normalizer| normalizer.normalize record, memo }
    end

    # If there's a persisted value, use that
    # If not, use the default value; if the default is a lambda, call it
    def apply_default
      @value = if value.nil?
        if schema.parent?
          d = schema.reduce({}) { |memo, (subschema_name, subschema)|
            memo[subschema_name] = subschema.value.compute(record)
            memo
          }
          d.values.compact.empty? ? nil : d
        elsif schema.default.respond_to?(:call)
          schema.default.call(record)
        else
          schema.default
        end
      else
        value
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
golden_fleece-0.1.1 lib/golden_fleece/value.rb
golden_fleece-0.1.0 lib/golden_fleece/value.rb