Class: ActiveRecord::ValidationsJson::Serializer

Inherits:
Object
  • Object
show all
Defined in:
lib/ar-validations-json.rb

Instance Method Summary collapse

Constructor Details

#initialize(ar_class) ⇒ Serializer

Returns a new instance of Serializer.



15
16
17
# File 'lib/ar-validations-json.rb', line 15

def initialize(ar_class)
  @ar_class = ar_class
end

Instance Method Details

#default_to_skip?(validator, option) ⇒ Boolean

Returns:

  • (Boolean)


19
20
21
22
23
24
25
26
27
28
29
# File 'lib/ar-validations-json.rb', line 19

def default_to_skip?(validator, option)
  case validator
  when ActiveModel::Validations::NumericalityValidator
    case option
    when 'allow_nil'
      validator.options[option.to_sym] == false
    when 'only_integer'
      validator.options[option.to_sym] == false
    end
  end
end

#serializable?(validator) ⇒ Boolean

Returns:

  • (Boolean)


31
32
33
34
35
36
37
38
39
40
41
# File 'lib/ar-validations-json.rb', line 31

def serializable?(validator)
  options_that_might_be_procs = {
    :in => nil, :tokenizer => %r|/active_model/validations/length.rb$|,
    :with => nil
  }
  !options_that_might_be_procs.any? { |option, whitelisted_source|
    (opt_value = validator.options[option]) && opt_value.is_a?(Proc) &&
     (whitelisted_source.nil? or
      opt_value.source_location.first !~ whitelisted_source)
  }
end

#to_jsonObject



43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/ar-validations-json.rb', line 43

def to_json
  json_hash = Hash.new { |h,k| h[k] = {} }
  @ar_class.validators.each do |validator|
    if serializable?(validator)
      label = validator.class.name.split(/::/).last.
              underscore.split(/_/).first
      validator.attributes.each do |attr|
        json_hash[attr.to_s][label] = validator_hash(validator)
      end
    end
  end
  json_hash.to_json
end

#validator_hash(validator) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/ar-validations-json.rb', line 57

def validator_hash(validator)
  validator_hash = {}
  validator_options_to_try_copying.each do |option|
    if validator.options.has_key?(option.to_sym)
      unless default_to_skip?(validator, option)
        validator_hash[option] = validator.options[option.to_sym]
      end
    end
  end
  validator_hash = true if validator_hash.empty?
  validator_hash
end

#validator_options_to_try_copyingObject



70
71
72
73
74
75
76
77
# File 'lib/ar-validations-json.rb', line 70

def validator_options_to_try_copying
  %w(
    accept allow_blank allow_nil case_sensitive greater_than
    greater_than_or_equal_to equal_to even in is less_than
    less_than_or_equal_to maximum message minimum odd on only_integer
    scope too_long too_short with without wrong_length
  )
end