Sha256: 5d98f1bb1e995e0515787f26683d0333b8a812d84299cda7a46c41eb880bdc38

Contents?: true

Size: 1.37 KB

Versions: 2

Compression:

Stored size: 1.37 KB

Contents

require 'golden_fleece/definitions'
require 'hana'

module GoldenFleece
  class Value
    include Utility

    def initialize(schema)
      @schema = schema
    end

    def compute(record)
      @record = record
      @value = Hana::Pointer.new(schema.json_path).eval(record.read_attribute(schema.attribute))

      cast_booleans
      apply_normalizers
      apply_default

      value
    end

    private

    attr_reader :schema, :record, :value

    # 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.4 lib/golden_fleece/value.rb
golden_fleece-0.1.3 lib/golden_fleece/value.rb