class Schema::AttributeNormalizer

Public Class Methods

new() click to toggle source
# File lib/schema/attribute_normalizer.rb, line 5
def initialize
  @normalizations = []
end

Public Instance Methods

add(method, options = {}) click to toggle source
# File lib/schema/attribute_normalizer.rb, line 9
def add(method, options = {})
  @normalizations << options.merge(method: method)
end
normalize(model, value) click to toggle source
# File lib/schema/attribute_normalizer.rb, line 18
def normalize(model, value)
  return nil if value.nil?

  @normalizations.each do |normalization|
    value = apply_normalization(model, value, normalization)
  end
  value
end
normalize_model_attribute(model, attribute) click to toggle source
# File lib/schema/attribute_normalizer.rb, line 13
def normalize_model_attribute(model, attribute)
  value = normalize(model, model.public_send(attribute))
  model.public_send("#{attribute}=", value)
end

Private Instance Methods

apply_normalization(model, value, normalization) click to toggle source
# File lib/schema/attribute_normalizer.rb, line 29
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
call_method(object, method, method_arguments = nil) click to toggle source
# File lib/schema/attribute_normalizer.rb, line 53
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
skip_normalization?(model, options) click to toggle source
# File lib/schema/attribute_normalizer.rb, line 46
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