better_form 0.3.2 → 0.4.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -6,6 +6,8 @@ module BetterForm
6
6
  helpers.each do |name|
7
7
  define_method(name) do |field_name, *args|
8
8
  options = args.extract_options!
9
+ validations = generate_validations(@object, field_name)
10
+ options.merge!(validations)
9
11
  label = options.delete(:label)
10
12
  if label == false
11
13
  super(field_name, *(args << options))
@@ -39,5 +41,55 @@ module BetterForm
39
41
 
40
42
  label(method, label_text)
41
43
  end
44
+
45
+ def generate_validations(object, attribute)
46
+ validations = {}
47
+
48
+ # Don't try to add validations for an object that doesn't have _validators
49
+ return {} unless object.respond_to?(:_validators)
50
+
51
+ # Iterate over each validator for this attribute, and add the appropriate HTML5 data-* attributes
52
+ object._validators[attribute].each do |validator|
53
+ validation = case validator
54
+ when ActiveModel::Validations::AcceptanceValidator
55
+ if validation_applies?(validator.options)
56
+ { 'data-validates-acceptance' => true }
57
+ end
58
+ when ActiveModel::Validations::ConfirmationValidator
59
+ if validation_applies?(validator.options)
60
+ {}
61
+ end
62
+ when ActiveModel::Validations::ExclusionValidator
63
+ {}
64
+ when ActiveModel::Validations::FormatValidator
65
+ if validation_applies?(validator.options)
66
+ { 'data-validates-format' => true, 'data-validates-format-with' => validator.options[:with].inspect }
67
+ end
68
+ when ActiveModel::Validations::InclusionValidator
69
+ {}
70
+ when ActiveModel::Validations::LengthValidator
71
+ if validation_applies?(validator.options)
72
+ {}
73
+ end
74
+ when ActiveModel::Validations::NumericalityValidator
75
+ if validation_applies?(validator.options)
76
+ { 'data-validates-numericality' => true }
77
+ end
78
+ when ActiveModel::Validations::PresenceValidator
79
+ { 'data-validates-presence' => true }
80
+ end
81
+ validations.merge!(validation ||= {})
82
+ end
83
+
84
+ validations
85
+ end
86
+
87
+ def validation_applies?(options)
88
+ case options[:on]
89
+ when :create then true if @object.new_record?
90
+ when :update then true if !@object.new_record?
91
+ else true
92
+ end
93
+ end
42
94
  end
43
95
  end
@@ -1,3 +1,3 @@
1
1
  module BetterForm
2
- VERSION = "0.3.2"
2
+ VERSION = "0.4.0"
3
3
  end
metadata CHANGED
@@ -2,7 +2,7 @@
2
2
  name: better_form
3
3
  version: !ruby/object:Gem::Version
4
4
  prerelease:
5
- version: 0.3.2
5
+ version: 0.4.0
6
6
  platform: ruby
7
7
  authors:
8
8
  - Nicholas Firth-McCoy
@@ -10,7 +10,7 @@ autorequire:
10
10
  bindir: bin
11
11
  cert_chain: []
12
12
 
13
- date: 2011-03-16 00:00:00 +11:00
13
+ date: 2011-03-17 00:00:00 +11:00
14
14
  default_executable:
15
15
  dependencies: []
16
16