Sha256: 78d564d2aca4b948798f650e79cc03fb24e05a23dc7f364550254ebc43bd50a1

Contents?: true

Size: 1.75 KB

Versions: 2

Compression:

Stored size: 1.75 KB

Contents

# frozen_string_literal: true

module Schema
  class AttributeNormalizer
    def initialize
      @normalizations = []
    end

    def add(method, options = {})
      @normalizations << options.merge(method: method)
    end

    def normalize_model_attribute(model, attribute)
      value = normalize(model, model.public_send(attribute))
      model.public_send("#{attribute}=", value)
    end

    def normalize(model, value)
      return nil if value.nil?

      @normalizations.each do |normalization|
        value = apply_normalization(model, value, normalization)
      end
      value
    end

    private

    def apply_normalization(model, value, normalization)
      return value if skip_normalization?(model, normalization)

      if normalization[:with]
        if normalization[:class_name] || normalization[:class]
          kls = normalization[:class] || Object.const_get(normalization[:class_name])
          arguments = [value]
          arguments += normalization[:args] if normalization[:args]
          call_method(kls, normalization[:with], arguments)
        else
          call_method(model, normalization[:with], [value])
        end
      else
        call_method(value, normalization[:method], normalization[:args])
      end
    end
    
    def skip_normalization?(model, options)
      return true if options[:if] && !call_method(model, options[:if])
      return true if options[:unless] && call_method(model, options[:unless])
      
      false
    end

    def call_method(object, method, method_arguments = nil)
      case method
      when Symbol
        object.public_send(method, *method_arguments)
      when Proc
        object.instance_eval(&method)
      else
        raise("wrong type, failed to call method #{method}")
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
schema-normalize-0.1.2 lib/schema/attribute_normalizer.rb
schema-normalize-0.1.0 lib/schema/attribute_normalizer.rb