Class: ActiveRecord::ValidationsJson::Serializer
- Inherits:
-
Object
- Object
- ActiveRecord::ValidationsJson::Serializer
- Defined in:
- lib/ar-validations-json.rb
Instance Method Summary collapse
- #default_to_skip?(validator, option) ⇒ Boolean
-
#initialize(ar_class) ⇒ Serializer
constructor
A new instance of Serializer.
- #serializable?(validator) ⇒ Boolean
- #to_json ⇒ Object
- #validator_hash(validator) ⇒ Object
- #validator_options_to_try_copying ⇒ Object
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
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.[option.to_sym] == false when 'only_integer' validator.[option.to_sym] == false end end end |
#serializable?(validator) ⇒ Boolean
31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/ar-validations-json.rb', line 31 def serializable?(validator) = { :in => nil, :tokenizer => %r|/active_model/validations/length.rb$|, :with => nil } !.any? { |option, whitelisted_source| (opt_value = validator.[option]) && opt_value.is_a?(Proc) && (whitelisted_source.nil? or opt_value.source_location.first !~ whitelisted_source) } end |
#to_json ⇒ Object
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 = {} .each do |option| if validator..has_key?(option.to_sym) unless default_to_skip?(validator, option) validator_hash[option] = validator.[option.to_sym] end end end validator_hash = true if validator_hash.empty? validator_hash end |
#validator_options_to_try_copying ⇒ Object
70 71 72 73 74 75 76 77 |
# File 'lib/ar-validations-json.rb', line 70 def %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 |