validate-response 0.0.5

Sign up to get free protection for your applications and to get access to all the features.
Files changed (54) hide show
  1. checksums.yaml +7 -0
  2. data/.gitignore +10 -0
  3. data/Gemfile +14 -0
  4. data/Gemfile.lock +100 -0
  5. data/MIT-LICENSE +20 -0
  6. data/README.md +235 -0
  7. data/Rakefile +32 -0
  8. data/app/assets/javascripts/validate-response/index.js +1 -0
  9. data/app/assets/javascripts/validate-response/validate_response_client.js.coffee +91 -0
  10. data/lib/tasks/validate_response_tasks.rake +4 -0
  11. data/lib/validate-response.rb +137 -0
  12. data/lib/validate-response/version.rb +3 -0
  13. data/test/dummy/README.rdoc +28 -0
  14. data/test/dummy/Rakefile +6 -0
  15. data/test/dummy/app/assets/images/.keep +0 -0
  16. data/test/dummy/app/assets/javascripts/application.js +13 -0
  17. data/test/dummy/app/assets/stylesheets/application.css +13 -0
  18. data/test/dummy/app/controllers/application_controller.rb +5 -0
  19. data/test/dummy/app/controllers/concerns/.keep +0 -0
  20. data/test/dummy/app/helpers/application_helper.rb +2 -0
  21. data/test/dummy/app/mailers/.keep +0 -0
  22. data/test/dummy/app/models/.keep +0 -0
  23. data/test/dummy/app/models/concerns/.keep +0 -0
  24. data/test/dummy/app/views/layouts/application.html.erb +14 -0
  25. data/test/dummy/bin/bundle +3 -0
  26. data/test/dummy/bin/rails +4 -0
  27. data/test/dummy/bin/rake +4 -0
  28. data/test/dummy/config.ru +4 -0
  29. data/test/dummy/config/application.rb +23 -0
  30. data/test/dummy/config/boot.rb +5 -0
  31. data/test/dummy/config/database.yml +25 -0
  32. data/test/dummy/config/environment.rb +5 -0
  33. data/test/dummy/config/environments/development.rb +29 -0
  34. data/test/dummy/config/environments/production.rb +80 -0
  35. data/test/dummy/config/environments/test.rb +36 -0
  36. data/test/dummy/config/initializers/backtrace_silencers.rb +7 -0
  37. data/test/dummy/config/initializers/filter_parameter_logging.rb +4 -0
  38. data/test/dummy/config/initializers/inflections.rb +16 -0
  39. data/test/dummy/config/initializers/mime_types.rb +5 -0
  40. data/test/dummy/config/initializers/secret_token.rb +12 -0
  41. data/test/dummy/config/initializers/session_store.rb +3 -0
  42. data/test/dummy/config/initializers/wrap_parameters.rb +14 -0
  43. data/test/dummy/config/locales/en.yml +23 -0
  44. data/test/dummy/config/routes.rb +56 -0
  45. data/test/dummy/lib/assets/.keep +0 -0
  46. data/test/dummy/log/.keep +0 -0
  47. data/test/dummy/public/404.html +58 -0
  48. data/test/dummy/public/422.html +58 -0
  49. data/test/dummy/public/500.html +57 -0
  50. data/test/dummy/public/favicon.ico +0 -0
  51. data/test/test_helper.rb +15 -0
  52. data/test/validate_response_test.rb +7 -0
  53. data/validate_response.gemspec +22 -0
  54. metadata +139 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 91e7b7e133902415a50dcebaeac0245c1b051ac9
4
+ data.tar.gz: ccb7aa9688e674989eade76de31b35b454bed2d7
5
+ SHA512:
6
+ metadata.gz: 92661d94472777c380758311a31bd4ccf817b13e44216dcf76faf16a030961c31e3fa69362d7f6fc8e56c60677f6d58a44c510eb6924b7570cfa969958bb41b4
7
+ data.tar.gz: 8f4f91a97aa37b03747f9a8a2afaf87cc138797f59ba3f0d965c5c9b90d716dd13901c826d9bb24e4c0164fa739e71c7e40353caa3b613f3a64ef2a0bf4588ed
data/.gitignore ADDED
@@ -0,0 +1,10 @@
1
+ .bundle/
2
+ log/*.log
3
+ pkg/
4
+ test/dummy/db/*.sqlite3
5
+ test/dummy/db/*.sqlite3-journal
6
+ test/dummy/log/*.log
7
+ test/dummy/tmp/
8
+ test/dummy/.sass-cache
9
+ .idea
10
+ .idea/*
data/Gemfile ADDED
@@ -0,0 +1,14 @@
1
+ source "https://rubygems.org"
2
+
3
+ # Declare your gem's dependencies in validate_response.gemspec.
4
+ # Bundler will treat runtime dependencies like base dependencies, and
5
+ # development dependencies will be added by default to the :development group.
6
+ gemspec
7
+
8
+ # Declare any dependencies that are still in development here instead of in
9
+ # your gemspec. These might include edge Rails or gems from your path or
10
+ # Git. Remember to move these dependencies to your gemspec before releasing
11
+ # your gem to rubygems.org.
12
+
13
+ # To use debugger
14
+ # gem 'debugger'
data/Gemfile.lock ADDED
@@ -0,0 +1,100 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ validate-response (0.0.5)
5
+ coffee-rails (>= 3.2)
6
+ rails (>= 3.2)
7
+ railties (>= 3.0)
8
+
9
+ GEM
10
+ remote: https://rubygems.org/
11
+ specs:
12
+ actionmailer (4.1.0)
13
+ actionpack (= 4.1.0)
14
+ actionview (= 4.1.0)
15
+ mail (~> 2.5.4)
16
+ actionpack (4.1.0)
17
+ actionview (= 4.1.0)
18
+ activesupport (= 4.1.0)
19
+ rack (~> 1.5.2)
20
+ rack-test (~> 0.6.2)
21
+ actionview (4.1.0)
22
+ activesupport (= 4.1.0)
23
+ builder (~> 3.1)
24
+ erubis (~> 2.7.0)
25
+ activemodel (4.1.0)
26
+ activesupport (= 4.1.0)
27
+ builder (~> 3.1)
28
+ activerecord (4.1.0)
29
+ activemodel (= 4.1.0)
30
+ activesupport (= 4.1.0)
31
+ arel (~> 5.0.0)
32
+ activesupport (4.1.0)
33
+ i18n (~> 0.6, >= 0.6.9)
34
+ json (~> 1.7, >= 1.7.7)
35
+ minitest (~> 5.1)
36
+ thread_safe (~> 0.1)
37
+ tzinfo (~> 1.1)
38
+ arel (5.0.1.20140414130214)
39
+ builder (3.2.2)
40
+ coffee-rails (4.0.1)
41
+ coffee-script (>= 2.2.0)
42
+ railties (>= 4.0.0, < 5.0)
43
+ coffee-script (2.2.0)
44
+ coffee-script-source
45
+ execjs
46
+ coffee-script-source (1.7.0)
47
+ erubis (2.7.0)
48
+ execjs (2.0.2)
49
+ hike (1.2.3)
50
+ i18n (0.6.9)
51
+ json (1.8.1)
52
+ mail (2.5.4)
53
+ mime-types (~> 1.16)
54
+ treetop (~> 1.4.8)
55
+ mime-types (1.25.1)
56
+ minitest (5.3.3)
57
+ multi_json (1.9.2)
58
+ polyglot (0.3.4)
59
+ rack (1.5.2)
60
+ rack-test (0.6.2)
61
+ rack (>= 1.0)
62
+ rails (4.1.0)
63
+ actionmailer (= 4.1.0)
64
+ actionpack (= 4.1.0)
65
+ actionview (= 4.1.0)
66
+ activemodel (= 4.1.0)
67
+ activerecord (= 4.1.0)
68
+ activesupport (= 4.1.0)
69
+ bundler (>= 1.3.0, < 2.0)
70
+ railties (= 4.1.0)
71
+ sprockets-rails (~> 2.0)
72
+ railties (4.1.0)
73
+ actionpack (= 4.1.0)
74
+ activesupport (= 4.1.0)
75
+ rake (>= 0.8.7)
76
+ thor (>= 0.18.1, < 2.0)
77
+ rake (10.3.0)
78
+ sprockets (2.12.0)
79
+ hike (~> 1.2)
80
+ multi_json (~> 1.0)
81
+ rack (~> 1.0)
82
+ tilt (~> 1.1, != 1.3.0)
83
+ sprockets-rails (2.1.3)
84
+ actionpack (>= 3.0)
85
+ activesupport (>= 3.0)
86
+ sprockets (~> 2.8)
87
+ thor (0.19.1)
88
+ thread_safe (0.3.3)
89
+ tilt (1.4.1)
90
+ treetop (1.4.15)
91
+ polyglot
92
+ polyglot (>= 0.3.1)
93
+ tzinfo (1.1.0)
94
+ thread_safe (~> 0.1)
95
+
96
+ PLATFORMS
97
+ ruby
98
+
99
+ DEPENDENCIES
100
+ validate-response!
data/MIT-LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright 2014 Alexander Gorbunov (lexgorbunov@gmail.com)
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,235 @@
1
+ # ValidationResponse
2
+
3
+ ValidationResponse это библиотека для приведения к единообразной структуре сообщения об ошибках одного или нескольких объектов ActiveRecord
4
+
5
+ + Подсветка полей с ошибками в формах
6
+
7
+ ## Установка (Installation)
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ gem 'validate-response', '~> 0.0.5'
12
+
13
+ And then execute:
14
+
15
+ $ bundle install
16
+
17
+ Add this line to your application.js
18
+
19
+ //= require validate-response
20
+
21
+ ## Как использовать (Usage)
22
+
23
+ __(!)__ ```nil``` - Используется для обозначения *new_record* записей (еще не сохраненных в базе)
24
+
25
+ ### Пример использования (Usage example):
26
+ #### Сервер (Server):
27
+
28
+ ```ruby
29
+ room = Room.create(params[:room])
30
+ render json: {
31
+ result: room.valid?,
32
+ validates: ValidateResponse.new(room)
33
+ }
34
+ ```
35
+ #### Клиент (Client):
36
+
37
+ ##### Код
38
+
39
+ ```coffeescreept
40
+ # dom element containing the highlightable fields
41
+ $form = $('.my-form')
42
+ $.ajax
43
+ url: '/'
44
+ type: 'POST'
45
+ dataType: 'json'
46
+ success: (data) ->
47
+ $(document).trigger ValidateResponse.EVENT_SHOW_ERRORS, [$form, data.validates] if data.validates
48
+ ```
49
+
50
+ ##### DOM
51
+
52
+ ```haml
53
+ .my-form
54
+ %div
55
+ %label{data: {vr_field: "rooms|#{@room.id}|field1"}} Label 1
56
+ %input{type: 'text', value: @room.field1, name: 'room[field1]'}
57
+ %div
58
+ %label{data: {vr_field: "rooms||field2", vr_way: 'border'}} Label 2
59
+ %input{type: 'text', value: @room.field2, name: 'room[field2]'}
60
+ ```
61
+
62
+ ### Привила настройки форм (Form settings rules)
63
+
64
+ #### data-vr-field:
65
+
66
+ # @room => Модель Room
67
+ # @room.id => 1
68
+
69
+ vr-field:
70
+
71
+ vr-field: 'rooms|1|field_name'
72
+ ---
73
+
74
+ #@room => Модель Room
75
+ #@room.id => nil
76
+
77
+ vr-field:
78
+
79
+ vr-field: 'rooms||field_name'
80
+
81
+ #### data-vr-way:
82
+ data-vr-way: 'color'
83
+ Вслучае ошибки цвет текста станет красным
84
+ 'title'
85
+ Вслучае ошибки текст всплывающей подсказки будет содержать сообщение об ошибке
86
+ 'outline'
87
+ Вслучае ошибки цвет внешней рамки станет красным
88
+ 'border'
89
+ Вслучае ошибки цвет рамки станет красным
90
+ 'background'
91
+ Вслучае ошибки цвет фона станет красным
92
+
93
+ После устранения ошибок для каждого поля все измененные свойства восстанавливаются до первоначального состояния
94
+
95
+ __Свойства vr-way можно группировать__
96
+
97
+ ``` vr-way: 'color|title' ```
98
+ ### Другие примеры (More examples):
99
+
100
+ ```ruby
101
+ render json: {
102
+ result: @user.update_attributes(params[:user]),
103
+ validates: ValidateResponse.new(@user.contacts)
104
+ }
105
+ ```
106
+ -- or --
107
+ ```ruby
108
+ ValidateResponse.new(
109
+ Room.create,
110
+ User.create,
111
+ User.last.tap{|u| u.email = nil; u.valid?}
112
+ )
113
+ ```
114
+ вернет (return)
115
+ ```
116
+ {
117
+ :rooms => {
118
+ nil => {
119
+ :location_id => [
120
+ [0] "не может быть пустым"
121
+ ],
122
+ :user => [
123
+ [0] "не может быть пустым"
124
+ ],
125
+ :floor => [
126
+ [0] "не является числом"
127
+ ],
128
+ :sq => [
129
+ [0] "не является числом"
130
+ ],
131
+ :price_psm => [
132
+ [0] "не является числом"
133
+ ],
134
+ :total_cost => [
135
+ [0] "не является числом"
136
+ ]
137
+ }
138
+ },
139
+ :users => {
140
+ nil => {
141
+ :email => [
142
+ [0] "не может быть пустым"
143
+ ],
144
+ :password => [
145
+ [0] "не может быть пустым"
146
+ ],
147
+ :city_id => [
148
+ [0] "не может быть пустым"
149
+ ],
150
+ :company => [
151
+ [0] "не может быть пустым"
152
+ ]
153
+ },
154
+ 242 => {
155
+ :email => [
156
+ [0] "не может быть пустым"
157
+ ]
158
+ }
159
+ }
160
+ }
161
+ ```
162
+ ### Поддерживаются объекты разных моделей (Supported object of different AR models at the same time)
163
+
164
+ ```ruby
165
+ a.update_attributes(...)
166
+ b.update_attributes(...)
167
+ ValidateResponse.new(a, b)
168
+ ```
169
+
170
+ ### Примеры заполнения (Filling examples):
171
+
172
+ #### Пример 1 (Example 1):
173
+
174
+ ```ruby
175
+ ValidateResponse.new(@user.contacts)
176
+ ```
177
+
178
+ #### Пример 2 (Example 2):
179
+ ```ruby
180
+ ValidateResponse.new(@room1, @room2)
181
+ ```
182
+
183
+ #### Пример 3 (Example 3):
184
+
185
+ ```ruby
186
+ x = ValidateResponse.new()
187
+ x << contact1
188
+ x << contact2
189
+ x << contact3 << contact4
190
+ ```
191
+
192
+ #### Пример 4. Ручное заполнение (Example 4 Manual filling):
193
+
194
+ ```ruby
195
+ x = ValidateResponse.new()
196
+ x[:users, 1] = {
197
+ name: 'ошибка такая-то',
198
+ age: ['несоответствие 1', 'несоответствие 2']
199
+ }
200
+ x[:users, nil] = {
201
+ name: 'ошибка такая-то',
202
+ age: ['несоответствие 1', 'несоответствие 2']
203
+ }
204
+ ```
205
+
206
+ #### Пример 5. Ручное заполнение (Example 5 Manual filling):
207
+
208
+ ```ruby
209
+ x = ValidateResponse.new()
210
+ x[:users] = {
211
+ 1 => {
212
+ name: 'ошибка такая-то',
213
+ age: ['несоответствие 1', 'несоответствие 2']
214
+ },
215
+ nil => {
216
+ name: 'ошибка такая-то',
217
+ age: ['несоответствие 1', 'несоответствие 2']
218
+ }
219
+ }
220
+ ```
221
+
222
+ #### Пример 6. Ручное заполнение (Example 6 Manual filling):
223
+
224
+ ```ruby
225
+ x = ValidateResponse.new()
226
+ x[:users, nil][:name] = ['несоответствие 1', 'несоответствие 2']
227
+ ```
228
+
229
+ ## Для разработчиков (Contributing)
230
+
231
+ 1. Fork it
232
+ 2. Create your feature branch (`git checkout -b my-new-feature`)
233
+ 3. Commit your changes (`git commit -am 'Add some feature'`)
234
+ 4. Push to the branch (`git push origin my-new-feature`)
235
+ 5. Create new Pull Request
data/Rakefile ADDED
@@ -0,0 +1,32 @@
1
+ begin
2
+ require 'bundler/setup'
3
+ rescue LoadError
4
+ puts 'You must `gem install bundler` and `bundle install` to run rake tasks'
5
+ end
6
+
7
+ require 'rdoc/task'
8
+
9
+ RDoc::Task.new(:rdoc) do |rdoc|
10
+ rdoc.rdoc_dir = 'rdoc'
11
+ rdoc.title = 'ValidateResponse'
12
+ rdoc.options << '--line-numbers'
13
+ rdoc.rdoc_files.include('README.rdoc')
14
+ rdoc.rdoc_files.include('lib/**/*.rb')
15
+ end
16
+
17
+
18
+
19
+
20
+ Bundler::GemHelper.install_tasks
21
+
22
+ require 'rake/testtask'
23
+
24
+ Rake::TestTask.new(:test) do |t|
25
+ t.libs << 'lib'
26
+ t.libs << 'test'
27
+ t.pattern = 'test/**/*_test.rb'
28
+ t.verbose = false
29
+ end
30
+
31
+
32
+ task default: :test
@@ -0,0 +1 @@
1
+ //= require ./validate_response_client
@@ -0,0 +1,91 @@
1
+ (($) ->
2
+ # $.fn.validate
3
+
4
+ $ ->
5
+ class ValidateResponse
6
+ WAY_EXPR = /^css:\w+/
7
+ DEFAULT_WAY: 'color|title'
8
+ # Events
9
+ EVENT_SHOW_ERRORS: 'validate-response:show-errors'
10
+
11
+ constructor: ->
12
+ # @EVENT_SHOW_ERRORS = EVENT_SHOW_ERRORS
13
+ # subscribe on show errors event
14
+ $(document).on @.EVENT_SHOW_ERRORS, (e, form, validation_data) => @show_errors(form, validation_data)
15
+
16
+ show_errors: (form, validation_data) =>
17
+ $form = $(form)
18
+ summary = $form.find('[role="vr-summary"]').empty()
19
+ need_summary = !!summary.length
20
+ # Adding summary
21
+ if need_summary
22
+ summary.addClass('vr-empty-summary')
23
+ for record_type, records_validations of validation_data
24
+ record_type_errors = $('<div class="vr-record-type-errors">').addClass("vr-record-type-#{record_type}")
25
+ for record_id, validations_fields of records_validations
26
+ record_errors = $('<div class="vr-record-errors">').addClass("vr-record-id-#{record_type}")
27
+ for field_id, validation_messages of validations_fields
28
+ field_errors = $('<div class="vr-field-errors">').addClass("vr-field-id-#{field_id}").append($('<div>').html(field_id)).append(field_errors_messages = $('<div>'))
29
+ for message in validation_messages
30
+ field_errors_messages.append $('<div class="vr-error-message">').html(message)
31
+ record_errors.append field_errors
32
+ record_type_errors.append record_errors
33
+ summary.append record_type_errors
34
+ else
35
+ summary.removeClass('vr-empty-summary')
36
+ # Highlight fields
37
+ @reset_highlight($form)
38
+ for record_type, records_validations of validation_data
39
+ for record_id, validations_fields of records_validations
40
+ for field_id, validation_messages of validations_fields
41
+ for message in validation_messages
42
+ field_selector = [record_type, record_id, field_id].join('|')
43
+ fields = $form.find("[data-vr-field=\"#{field_selector}\"]")
44
+ for field_element in fields
45
+ field = $(field_element)
46
+ for way in (field.data('vr-way') || @.DEFAULT_WAY).split('|')
47
+ switch way
48
+ when 'color'
49
+ field.data('vr-backstore-color', (field.css('color') || '#000'))
50
+ field.css('color', '#D0413B')
51
+ when 'title'
52
+ field.data('vr-backstore-title', (field.attr('title') || ''))
53
+ field.attr('title', message)
54
+ when 'outline'
55
+ field.data('vr-backstore-outline', (field.css('outline') || 'none'))
56
+ field.css('outline', '1px solid #D0413B')
57
+ when 'border'
58
+ field.data('vr-backstore-border', (field.css('border') || 'none'))
59
+ field.css('border', '1px solid #D0413B')
60
+ when 'background'
61
+ field.data('vr-backstore-background', (field.css('background') || 'none'))
62
+ field.css('background', '1px solid #D0413B')
63
+ else
64
+ continue
65
+ # --- end of show_errors ---
66
+
67
+ reset_highlight: (form) =>
68
+ $form = $(form)
69
+ vr_fields = $form.find('[data-vr-field]')
70
+ for field in vr_fields
71
+ $fields = $(field)
72
+ for field in $fields
73
+ $field = $(field)
74
+ for way in ($field.data('vr-way') || @.DEFAULT_WAY).split('|')
75
+ switch way
76
+ when 'color'
77
+ $field.css('color', vr_backval) if (vr_backval = $field.data('vr-backstore-color'))?
78
+ when 'title'
79
+ $field.attr('title', vr_backval) if (vr_backval = $field.data('vr-backstore-title'))?
80
+ when 'outline'
81
+ $field.css('outline', vr_backval) if (vr_backval = $field.data('vr-backstore-outline'))?
82
+ when 'border'
83
+ $field.css('border', vr_backval) if (vr_backval = $field.data('vr-backstore-border'))?
84
+ when 'background'
85
+ $field.css('background', vr_backval) if (vr_backval = $field.data('vr-backstore-background'))?
86
+ else
87
+ continue
88
+ # --- end of reset_highlight ---
89
+
90
+ window.ValidateResponse = new ValidateResponse()
91
+ )(jQuery)