cck_forms 3.0.1 → 3.1.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (29) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +254 -1
  3. data/lib/cck_forms/date_time.rb +4 -0
  4. data/lib/cck_forms/engine.rb +2 -2
  5. data/lib/cck_forms/form_builder_extensions.rb +2 -1
  6. data/lib/cck_forms/neofiles_denormalize.rb +71 -0
  7. data/lib/cck_forms/parameter_type_class/album.rb +15 -11
  8. data/lib/cck_forms/parameter_type_class/base.rb +58 -63
  9. data/lib/cck_forms/parameter_type_class/boolean.rb +6 -0
  10. data/lib/cck_forms/parameter_type_class/checkboxes.rb +31 -15
  11. data/lib/cck_forms/parameter_type_class/date.rb +5 -0
  12. data/lib/cck_forms/parameter_type_class/date_range.rb +8 -2
  13. data/lib/cck_forms/parameter_type_class/date_time.rb +10 -8
  14. data/lib/cck_forms/parameter_type_class/enum.rb +11 -0
  15. data/lib/cck_forms/parameter_type_class/file.rb +27 -20
  16. data/lib/cck_forms/parameter_type_class/float.rb +3 -0
  17. data/lib/cck_forms/parameter_type_class/image.rb +3 -1
  18. data/lib/cck_forms/parameter_type_class/integer.rb +10 -4
  19. data/lib/cck_forms/parameter_type_class/integer_range.rb +18 -0
  20. data/lib/cck_forms/parameter_type_class/map.rb +23 -23
  21. data/lib/cck_forms/parameter_type_class/phones.rb +14 -15
  22. data/lib/cck_forms/parameter_type_class/string.rb +3 -0
  23. data/lib/cck_forms/parameter_type_class/string_collection.rb +6 -0
  24. data/lib/cck_forms/parameter_type_class/text.rb +4 -0
  25. data/lib/cck_forms/parameter_type_class/time.rb +4 -0
  26. data/lib/cck_forms/parameter_type_class/work_hours.rb +24 -36
  27. data/lib/cck_forms/version.rb +1 -1
  28. data/vendor/assets/javascripts/cck_forms/index.js +2 -0
  29. metadata +4 -2
@@ -1,3 +1,5 @@
1
+ # Represents a floating point value.
2
+ #
1
3
  class CckForms::ParameterTypeClass::Float
2
4
  include CckForms::ParameterTypeClass::Base
3
5
 
@@ -13,6 +15,7 @@ class CckForms::ParameterTypeClass::Float
13
15
  value.to_f != 0.0 ? value.to_f : ''
14
16
  end
15
17
 
18
+ # HTML input
16
19
  def build_form(form_builder, options)
17
20
  set_value_in_hash options
18
21
  form_builder.number_field :value, {class: 'form-control input-small'}.merge(options)
@@ -1,5 +1,6 @@
1
+ # Represents a single image. A subclass of File.
2
+ #
1
3
  class CckForms::ParameterTypeClass::Image < CckForms::ParameterTypeClass::File
2
- include CckForms::ParameterTypeClass::Base
3
4
 
4
5
  def self.name
5
6
  'Картинка'
@@ -13,6 +14,7 @@ class CckForms::ParameterTypeClass::Image < CckForms::ParameterTypeClass::File
13
14
  self.class.file_type
14
15
  end
15
16
 
17
+ # Returns a 64x64 IMG
16
18
  def to_diff_value(options = {})
17
19
  view_context = options[:view_context]
18
20
  "<img style='width: 64px; height: 64px;' src='#{view_context.neofiles_image_path(id: value, format: '64x64', crop: 1)}'>".html_safe
@@ -1,3 +1,5 @@
1
+ # Represents a decimal value.
2
+ #
1
3
  class CckForms::ParameterTypeClass::Integer
2
4
  include CckForms::ParameterTypeClass::Base
3
5
 
@@ -39,11 +41,15 @@ class CckForms::ParameterTypeClass::Integer
39
41
  end
40
42
  end
41
43
 
42
- # Примеры options[:values] (работает, если передано options[:as] == :select и options[:for] == :search):
44
+ # Examples of options[:values] (works only if options[:as] == :select or options[:for] == :search):
43
45
  #
44
- # диапазоны: [['не больше 10', '/10'], ['11-20', '11/20'], ['21-30', '21/30'], ['свыше 30', '31/']]
45
- # перечисление: [['один', '1'], ['два', '2'], ['три', '3']]
46
- # комбинирование: [['один', '1'], ['два', '2'], ['три и больше', '3/']]
46
+ # ranges: [['not more that 10', '/10'], ['11-20', '11/20'], ['21-30', '21/30'], ['more that 30', '31/']]
47
+ # counting: [['one', '1'], ['two', '2'], ['three', '3']]
48
+ # combined: [['one', '1'], ['two', '2'], ['three and more', '3/']]
49
+ #
50
+ # Other options:
51
+ #
52
+ # only - leave only these keys (array/string)
47
53
  def build_form(form_builder, options = {})
48
54
  set_value_in_hash options
49
55
 
@@ -1,3 +1,9 @@
1
+ # Represents a decimal range — two integer values.
2
+ #
3
+ # Has an extra_options (see base.rb): :ranges
4
+ # If passed, on each object save the intersection of the target range and :ranges will be calculated and saved into DB
5
+ # (denormalized) for easy finding later via where('some_field.ranged.300-600' => true).
6
+ #
1
7
  class CckForms::ParameterTypeClass::IntegerRange # Rover :)
2
8
  include CckForms::ParameterTypeClass::Base
3
9
 
@@ -49,6 +55,13 @@ class CckForms::ParameterTypeClass::IntegerRange # Rover :)
49
55
  db_representation
50
56
  end
51
57
 
58
+ # "from 10"
59
+ # "till 20"
60
+ # "10-20"
61
+ #
62
+ # options:
63
+ #
64
+ # delimeter - instead of "-"
52
65
  def to_s(options = {})
53
66
  options ||= {}
54
67
  return '' if value.blank?
@@ -71,6 +84,10 @@ class CckForms::ParameterTypeClass::IntegerRange # Rover :)
71
84
  end
72
85
  end
73
86
 
87
+ # If options[:for] == :search and options[:as] == :select, builds a SELECT with options from extra_options[:rages].
88
+ # Otherwise, two inputs are built.
89
+ #
90
+ # options[:only/:except] are available if the former case.
74
91
  def build_form(form_builder, options)
75
92
  set_value_in_hash options
76
93
  if options.delete(:for) == :search
@@ -80,6 +97,7 @@ class CckForms::ParameterTypeClass::IntegerRange # Rover :)
80
97
  end
81
98
  end
82
99
 
100
+ # Search with the help of extra_options[:ranges]
83
101
  def search(criteria, field, query)
84
102
  criteria.where("#{field}.ranges.#{query}" => true)
85
103
  end
@@ -1,3 +1,5 @@
1
+ # Represents a map point in Google Maps or Yandex.Maps.
2
+ #
1
3
  class CckForms::ParameterTypeClass::Map
2
4
  include CckForms::ParameterTypeClass::Base
3
5
 
@@ -14,9 +16,9 @@ class CckForms::ParameterTypeClass::Map
14
16
  'Точка на карте'
15
17
  end
16
18
 
17
- # Было базе: {latlon: [x, y], zoom: z}
19
+ # In MongoDB: {latlon: [x, y], zoom: z}
18
20
  #
19
- # Стало в модели: {
21
+ # In application: {
20
22
  # latitude: x,
21
23
  # longitude: y,
22
24
  # zoom: z
@@ -39,13 +41,13 @@ class CckForms::ParameterTypeClass::Map
39
41
  end
40
42
 
41
43
 
42
- # Было в модели: {
44
+ # In application: {
43
45
  # latitude: x,
44
46
  # longitude: y,
45
47
  # zoom: z
46
48
  # }
47
49
  #
48
- # Стало в базе: {latlon: [x, y], zoom: z}
50
+ # In MongoDB: {latlon: [x, y], zoom: z}
49
51
  def mongoize
50
52
  value = self.value.is_a?(Hash) ? self.value : {}
51
53
  return {
@@ -55,7 +57,7 @@ class CckForms::ParameterTypeClass::Map
55
57
  }
56
58
  end
57
59
 
58
- # Если переданы :width и :height, вызовет img_tag, иначе вернет пустую строку.
60
+ # Call #img_tag if :width & :height
59
61
  def to_s(options = {})
60
62
  options ||= {}
61
63
  if options[:width].to_i > 0 and options[:height].to_i > 0
@@ -66,8 +68,10 @@ class CckForms::ParameterTypeClass::Map
66
68
  ''
67
69
  end
68
70
 
69
- # Возвращает тэг IMG с картинкой карты и точкой на ней, если value не пустое (содержит координаты точки).
70
- # См. Google/Yandex Maps Static API.
71
+ # IMG tag of options[:with] X options[:height] size with a point on it in the current value position (unless value
72
+ # is empty, of course).
73
+ #
74
+ # See Google/Yandex Maps Static API.
71
75
  def img_tag(width, height, options = {})
72
76
  map_type = value['type']
73
77
 
@@ -105,7 +109,7 @@ class CckForms::ParameterTypeClass::Map
105
109
  end
106
110
  end
107
111
 
108
- # Возвращает тэг A со ссылкой на карту с маркером объекта.
112
+ # <A> tag with a link to the Google/Yandex Maps with marker placed on the current value position
109
113
  def a_tag(content, attrs)
110
114
  if attrs[:href] = url
111
115
  attrs_strings = []
@@ -116,7 +120,7 @@ class CckForms::ParameterTypeClass::Map
116
120
  end
117
121
  end
118
122
 
119
- # Возвращает урл на карту.
123
+ # Returns a URL to Google/Yandex Maps map with marker placed on the current value position
120
124
  def url
121
125
  if value['latitude'].present? and value['longitude'].present?
122
126
  if value['type'] == MAP_TYPE_GOOGLE
@@ -137,25 +141,20 @@ class CckForms::ParameterTypeClass::Map
137
141
  end
138
142
  end
139
143
 
140
- # Построим форму для карты. Представляет собой 3 спрятанных поля latitude, longitude, zoom. Затем рядом ставится ДИВ,
141
- # на который вешается карта Гугла, и с помощью скриптов изменение полей привязывается к кликам на карте и изменению
142
- # масштаба.
144
+ # 3 hidden field: latitude, longitude, zoom. Next we place a DIV nearby on which Google/Yandex Map is hooked.
143
145
  #
144
- # 1 клик на пустом месте ставит точку (пишем в поля), старая точка при этом удаляется. Клик на точке удаляет ее
145
- # (очищаем поля).
146
+ # 1 click on a map places a point (writing to hidden fields). 1 click on a point removes it (emptying fields).
146
147
  #
147
- # Также, слушает событие change поля "город" (facility_page_cck_params_city_value), чтобы по известным названиям
148
- # городов отцентровать карту на выбранном городе.
148
+ # TODO: remove listeners of "city" events, it's out of scope for this gem
149
149
  #
150
150
  # options:
151
151
  #
152
- # value - тек. значение, см. self.demongoize_value
153
- # width - ширина карты
154
- # height - высота карты
155
- # latitude - широта центра карты, если ничего не выбрано
156
- # longitude - долгота центра карты, если ничего не выбрано
157
- # zoom - масштаб карты, если ничего не выбрано
158
-
152
+ # value - current point
153
+ # width - map width
154
+ # height - map height
155
+ # latitude - default map center lat
156
+ # longitude - default map center lon
157
+ # zoom - default map center zoom
159
158
  def build_form(form_builder, options)
160
159
  set_value_in_hash options
161
160
 
@@ -252,6 +251,7 @@ class CckForms::ParameterTypeClass::Map
252
251
  |
253
252
  end
254
253
 
254
+ # Returns a 64x64 IMG with a marker (see #img_tag)
255
255
  def to_diff_value(options = {})
256
256
  demongoize_value!
257
257
  img_tag(64, 64, marker_size: :small)
@@ -1,3 +1,5 @@
1
+ # Represents a set of phone numbers.
2
+ #
1
3
  class CckForms::ParameterTypeClass::Phones
2
4
  include CckForms::ParameterTypeClass::Base
3
5
 
@@ -10,12 +12,12 @@ class CckForms::ParameterTypeClass::Phones
10
12
  'Телефоны'
11
13
  end
12
14
 
13
- # Проверяет входной массив на наличие телефонов (хэша с ключами prefix, code и number).
14
- # На выходе выдает очищенный массив хэшей с такими ключами, пропуская пустые телефоны.
15
+ # Filters input array for phone-like Hashes: prefix: ..., code: ..., number: ...
16
+ # Cleans them up and returns.
15
17
  #
16
- # Было в модели: [{prefix: '+7'}, {code: ' 123 ', number: '1234567', zzz: ''}]
18
+ # In application: [{prefix: '+7'}, {code: ' 123 ', number: '1234567', zzz: ''}]
17
19
  #
18
- # Стало в базе: [{prefix: '', code: '123', number: '1234567'}]
20
+ # In MongoDB: [{prefix: '', code: '123', number: '1234567'}]
19
21
  def mongoize
20
22
  value = self.value
21
23
  return [] unless value.respond_to? :each
@@ -43,7 +45,7 @@ class CckForms::ParameterTypeClass::Phones
43
45
  result
44
46
  end
45
47
 
46
- # Просто приводит телефоны в базе в соответствие формату.
48
+ # Cleanup phone format
47
49
  def self.demongoize_value(value, parameter_type_class=nil)
48
50
  if value
49
51
  value.map do |phone|
@@ -57,12 +59,9 @@ class CckForms::ParameterTypeClass::Phones
57
59
  end
58
60
  end
59
61
 
60
- # Строит форму для заполнения телефонов. В ней будет минимум MIN_PHONES_IN_FORM телефонов, если их меньше, остальные
61
- # будут добавлены пустые.
62
+ # A form with pre-set MIN_PHONES_IN_FORM empty phones.
62
63
  #
63
- # Также, если заполнены все MIN_PHONES_IN_FORM, добавит 1 пустое поле, чтобы можно было добавить новый телефон.
64
- #
65
- # Возвращает ХТМЛ.
64
+ # If MIN_PHONES_IN_FORM are taken, add one more field to add more phones.
66
65
  def build_form(form_builder, options)
67
66
  set_value_in_hash options
68
67
  value = options[:value].presence
@@ -76,7 +75,7 @@ class CckForms::ParameterTypeClass::Phones
76
75
  sprintf '<div id="%s">%s</div>%s', id, result.join, script(id)
77
76
  end
78
77
 
79
- # Строит форму для 1 телефона из значения вида {prefix: '', code: '', number: ''}
78
+ # HTML for sinle phone number
80
79
  def build_single_form(form_builder, phone)
81
80
  phone = {} unless phone.is_a? Hash
82
81
  phone = blank_phone.merge phone
@@ -92,7 +91,7 @@ class CckForms::ParameterTypeClass::Phones
92
91
  sprintf '<p class="form-inline">%s &mdash; %s &mdash; %s</p>', phone_form[0], phone_form[1], phone_form[2]
93
92
  end
94
93
 
95
- # Возвращает 1 пустой телефон (хэш вида {prefix: '+7', code: '', number: ''}). Так сказать, эталон.
94
+ # 1 empty phone Hash: {prefix: '+7', code: '', number: ''}
96
95
  def blank_phone
97
96
  {
98
97
  'prefix' => PREFIX,
@@ -176,12 +175,12 @@ HTML
176
175
  number.gsub /\D/, ''
177
176
  end
178
177
 
179
- # 1234567 -> 123 45 67 с тэгами
178
+ # 1234567 -> 123 45 67 with tags
180
179
  def split_number(number)
181
180
  if number.length > 4
182
181
  tokens = []
183
182
 
184
- # перевернем строку и разобъем на пары
183
+ # reverse & split by doubles
185
184
  number.reverse.scan(/.(?:.|$)/) do |token|
186
185
  token.reverse!
187
186
  if token.length == 1
@@ -191,7 +190,7 @@ HTML
191
190
  end
192
191
  end
193
192
 
194
- # сольем все обратно
193
+ # merge back
195
194
  tokens.reverse!
196
195
  tokens.tap do |tokens|
197
196
  tokens.map! { |token| yield token } if block_given?
@@ -1,3 +1,5 @@
1
+ # Represents a short text string.
2
+ #
1
3
  class CckForms::ParameterTypeClass::String
2
4
  include CckForms::ParameterTypeClass::Base
3
5
 
@@ -5,6 +7,7 @@ class CckForms::ParameterTypeClass::String
5
7
  'Строка'
6
8
  end
7
9
 
10
+ # HTML input element
8
11
  def build_form(form_builder, options)
9
12
  set_value_in_hash options
10
13
  attrs = @extra_options.slice(:maxlength, :pattern)
@@ -1,3 +1,5 @@
1
+ # Represents a collection of text strings (tags etc.)
2
+ #
1
3
  class CckForms::ParameterTypeClass::StringCollection
2
4
  include CckForms::ParameterTypeClass::Base
3
5
 
@@ -5,6 +7,8 @@ class CckForms::ParameterTypeClass::StringCollection
5
7
  'Массив строк'
6
8
  end
7
9
 
10
+ # String: "aaa\r\nxxx" -> ["aaa", "xxx"]
11
+ # :each: -> array
8
12
  def mongoize
9
13
  if value.is_a? String
10
14
  value.split "\r\n"
@@ -13,6 +17,7 @@ class CckForms::ParameterTypeClass::StringCollection
13
17
  end
14
18
  end
15
19
 
20
+ # Everything to array
16
21
  def self.demongoize_value(value, parameter_type_class=nil)
17
22
  if value.is_a? String
18
23
  value = [value]
@@ -22,6 +27,7 @@ class CckForms::ParameterTypeClass::StringCollection
22
27
  super
23
28
  end
24
29
 
30
+ # Builds a TEXTAREA, each string is a separate line
25
31
  def build_form(form_builder, options)
26
32
  set_value_in_hash options
27
33
  options[:value] = value.join("\r\n") if value
@@ -1,3 +1,5 @@
1
+ # Represents a long text string (TEXTAREA).
2
+ #
1
3
  class CckForms::ParameterTypeClass::Text
2
4
  include CckForms::ParameterTypeClass::Base
3
5
 
@@ -5,11 +7,13 @@ class CckForms::ParameterTypeClass::Text
5
7
  'Текст'
6
8
  end
7
9
 
10
+ # Builds a TEXTAREA
8
11
  def build_form(form_builder, options)
9
12
  set_value_in_hash options
10
13
  form_builder.text_area :value, {cols: 50, rows: 5, class: 'form-control'}.merge(options)
11
14
  end
12
15
 
16
+ # Wrap DIFF output to .wall (bootstrap-specific bounded block)
13
17
  def to_diff_value(options = {})
14
18
  to_html.presence.try do |html|
15
19
  "<div class='well well-small'>#{html}</div>".html_safe
@@ -1,3 +1,5 @@
1
+ # Represents a single time.
2
+ #
1
3
  class CckForms::ParameterTypeClass::Time
2
4
  include CckForms::ParameterTypeClass::Base
3
5
  include CckForms::DateTime
@@ -6,6 +8,7 @@ class CckForms::ParameterTypeClass::Time
6
8
  'Время'
7
9
  end
8
10
 
11
+ # Time SELECT
9
12
  def build_form(form_builder, options)
10
13
  set_value_in_hash options
11
14
  value = CckForms::ParameterTypeClass::Time::date_object_from_what_stored_in_database(options[:value])
@@ -15,6 +18,7 @@ class CckForms::ParameterTypeClass::Time
15
18
  ('<div class="form-inline">%s</div>' % form_builder.fields_for(:value) { |datetime_builder| datetime_builder.time_select '', form_element_options, form_element_html})
16
19
  end
17
20
 
21
+ # "19:34"
18
22
  def to_s(options = nil)
19
23
  if value.is_a? Time
20
24
  the_value = {
@@ -1,3 +1,5 @@
1
+ # Represents a set of weekly based work hours: essentially a set of SELECTs one for each week day.
2
+ #
1
3
  class CckForms::ParameterTypeClass::WorkHours
2
4
  include CckForms::ParameterTypeClass::Base
3
5
 
@@ -13,11 +15,7 @@ class CckForms::ParameterTypeClass::WorkHours
13
15
  DAYS_RU_SHORT[DAYS.index(day.to_s)]
14
16
  end
15
17
 
16
- # Входящий хэш или массив объектов WorkHoursDat
17
- #
18
- # mon: {open_time: ..., open_24_hours: ...}, tue: {...}, ...
19
- #
20
- # преобразует в хэш для Монго.
18
+ # mon: {open_time: ..., open_24_hours: ...}, tue: {...}, ... -> MongoDB Hash
21
19
  def mongoize
22
20
  return {} unless value.is_a? Hash
23
21
 
@@ -27,7 +25,7 @@ class CckForms::ParameterTypeClass::WorkHours
27
25
  end
28
26
  end
29
27
 
30
- # Конструирует хэш объектов WorkHoursDay (ключ - название дня вида :mon, см. DAYS).
28
+ # Makes a Hash of WorkHoursDay (key - day name of form :mon, see DAYS)
31
29
  def self.demongoize_value(value, parameter_type_class=nil)
32
30
  return {} unless value.is_a? Hash
33
31
  value.reduce({}) do |r, (day_name, day_row)|
@@ -37,7 +35,7 @@ class CckForms::ParameterTypeClass::WorkHours
37
35
  end
38
36
  end
39
37
 
40
- # Строит форму для редактирования режима работы. 1 строка формы - 1 день со всеми своими параметрами.
38
+ # Builds HTML form. 1 row 1 day
41
39
  def build_form(form_builder, options)
42
40
  set_value_in_hash options
43
41
 
@@ -70,7 +68,7 @@ class CckForms::ParameterTypeClass::WorkHours
70
68
  sprintf '<div class="work-hours" id="%1$s">%2$s</div><script type="text/javascript">$(function() {$("#%1$s").workhours()})</script>', form_builder_name_to_id(form_builder), result.join
71
69
  end
72
70
 
73
- # Строит строку вида: "Пн—Ср 10:00—23:00; Чт—Сб круглосуточно"
71
+ # Makes a string: "Mon—Wed 10:00—23:00; Thu-Sat 24h"
74
72
  def to_html(options = nil)
75
73
  value = self.value
76
74
  return value.to_s unless value.respond_to? :each
@@ -79,7 +77,7 @@ class CckForms::ParameterTypeClass::WorkHours
79
77
 
80
78
  value = value.deep_stringify_keys if value.respond_to? :deep_stringify_keys
81
79
 
82
- # разобьем на группы дней с одинаковым значением (режимом работы), типа {'круглосуточно' => %w{mon tue wed}, ...}
80
+ # split by groups with equal value: {'25h' => %w{mon tue wed}, ...}
83
81
  groups = {}
84
82
  value.send(value.respond_to?(:each_value) ? :each_value : :each) do |day|
85
83
  day = CckForms::ParameterTypeClass::WorkHours::WorkHoursDay.new(day) unless day.is_a? CckForms::ParameterTypeClass::WorkHours::WorkHoursDay
@@ -88,7 +86,7 @@ class CckForms::ParameterTypeClass::WorkHours
88
86
  groups[hash] << day.day
89
87
  end
90
88
 
91
- # построим строки для групп
89
+ # make string for each group
92
90
  result = []
93
91
  groups.each_pair do |hours_description, days|
94
92
  if hours_description.present?
@@ -116,10 +114,10 @@ class CckForms::ParameterTypeClass::WorkHours
116
114
  to_html with_tags: false
117
115
  end
118
116
 
119
- # Входной массив вида %w{mon, tue, wed, sat} преобразует в сгруппированную строку вида: "Пн—Ср, Сб".
117
+ # %w{mon, tue, wed, sat} -> "Mon—Wed, Sat"
120
118
  def self.grouped_days_string(days)
121
119
 
122
- # разобьем на непрерывные группы типа [%w{mon tue wed}, %w{sat}]
120
+ # split by continuous blocks: [%w{mon tue wed}, %w{sat}]
123
121
  days.sort! { |a, b| DAYS.index(a) <=> DAYS.index(b) }
124
122
  prev_index = -2
125
123
  groups = []
@@ -133,7 +131,7 @@ class CckForms::ParameterTypeClass::WorkHours
133
131
  prev_index = index
134
132
  end
135
133
 
136
- # получившиеся группы преобразуем в строки и сольем воедино
134
+ # convert to string and join
137
135
  groups.map do |group|
138
136
  if group.length == 1
139
137
  group[0]
@@ -147,16 +145,14 @@ class CckForms::ParameterTypeClass::WorkHours
147
145
 
148
146
 
149
147
 
150
- # Модель-представление рабочего графика одного дня недели. При получении данных из Монги преобразовываем в эту модель,
151
- # для удобства работы (чтобы не с хэшами возиться).
148
+ # A utility model for one work day.
152
149
  #
153
- # day - строка из массива CckForms::ParameterTypeClass::WorkHours::DAYS.
154
- # open_time и close_time хранятся в виде хэшей {hours: 10, minutes: 5}.
150
+ # day - one of CckForms::ParameterTypeClass::WorkHours::DAYS.
151
+ # open_time & close_time are hashes: {hours: 10, minutes: 5}
155
152
  class WorkHoursDay
156
153
 
157
154
  attr_accessor :day, :open_time, :close_time, :open_24_hours, :open_until_last_client
158
155
 
159
- # Инициализирует свои поля из хэша.
160
156
  def initialize(other)
161
157
  if other.is_a? Hash
162
158
  other = other.symbolize_keys
@@ -174,7 +170,7 @@ class CckForms::ParameterTypeClass::WorkHours
174
170
  end
175
171
  end
176
172
 
177
- # Равны ли два объекта. Да, если все их поля равны.
173
+ # Are equal if all fields are equal
178
174
  def ==(other)
179
175
  other = self.class.new(other) unless other.is_a? self.class
180
176
 
@@ -185,12 +181,12 @@ class CckForms::ParameterTypeClass::WorkHours
185
181
  self.open_until_last_client == other.open_until_last_client
186
182
  end
187
183
 
188
- # Строит целочисленный хэш на основе всех полей, кроме day, чтобы группировать одинаковые режимы работы.
184
+ # Hash key for grouping (all fields except for day)
189
185
  def hash_without_day
190
186
  sprintf('%s:%s:%s:%s', open_time, close_time, open_24_hours, open_until_last_client).hash
191
187
  end
192
188
 
193
- # Строит строковое описание режима работы в формате: "с 12:00 до последнего клиента"
189
+ # "from 12:00 till last client"
194
190
  def to_s_without_day
195
191
  result = ''
196
192
  if open_24_hours
@@ -214,7 +210,7 @@ class CckForms::ParameterTypeClass::WorkHours
214
210
  result
215
211
  end
216
212
 
217
- # Строит форму редактирования одного дня.
213
+ # Single day form HTML
218
214
  def build_form(form_builder, template = false, options = {})
219
215
  form_builder.object = self
220
216
 
@@ -270,24 +266,24 @@ HTML
270
266
 
271
267
  private
272
268
 
273
- # Преобразует значение из запроса (чексбокс) в булево, типа 1 -> true.
269
+ # HTML form to boolean: '1' -> true
274
270
  def form_to_boolean(value)
275
271
  return value == '1' if value.is_a? String
276
272
  !!value
277
273
  end
278
274
 
279
- # Преобразует хэше времени {hours: ..., minutes: ...} в строку "10:42"
275
+ # {hours: ..., minutes: ...} -> "10:42"
280
276
  def time_to_s(time)
281
277
  return nil unless time.is_a?(Hash) and time['hours'].present? and time['minutes'].present?
282
278
  sprintf '%s:%s', time['hours'].to_s.rjust(2, '0'), time['minutes'].to_s.rjust(2, '0')
283
279
  end
284
280
 
285
- # Не пустое ли значение времени?
281
+ # Time present?
286
282
  def time_present?(time)
287
283
  return time.is_a?(Hash) && time['hours'].present? && time['minutes'].present?
288
284
  end
289
285
 
290
- # Строим форму с селектами времени вида: [18]:[45]
286
+ # SELECTs: [18]:[45]
291
287
  def build_time_form(form_builder, value)
292
288
  hours = []
293
289
  24.times { |hour| hours << [hour.to_s.rjust(2, '0'), hour] }
@@ -306,7 +302,6 @@ HTML
306
302
 
307
303
  public
308
304
 
309
- # Преборазование самого себя для сохранения в Монго (хэш).
310
305
  def mongoize
311
306
  {
312
307
  'day' => day.to_s,
@@ -319,7 +314,6 @@ HTML
319
314
 
320
315
  class << self
321
316
 
322
- # Преборазование самого себя из представления Монго (из хэша).
323
317
  def demongoize(object)
324
318
  object = object.symbolize_keys
325
319
  WorkHoursDay.new(
@@ -331,7 +325,6 @@ HTML
331
325
  )
332
326
  end
333
327
 
334
- # "Статическое" преборазование самого себя для сохранения в Монго (хэш).
335
328
  def mongoize(object)
336
329
  case object
337
330
  when WorkHoursDay then object.mongoize
@@ -340,14 +333,12 @@ HTML
340
333
  end
341
334
  end
342
335
 
343
- # TODO: сделать нормальный evolve
336
+ # TODO: make evolve
344
337
  def evolve(object)
345
338
  object
346
339
  end
347
340
 
348
- # Преобразовываем значение времени для Монго. Берет Time или DateTime или хэш и выдает хэш вида:
349
- #
350
- # {hours: 10, minutes: 5}
341
+ # Time/DateTime -> {hours: 10, minutes: 5}
351
342
  def mongoize_time(time)
352
343
  if time.is_a? Time or time.is_a? DateTime
353
344
  {'hours' => time.hour, 'minutes' => time.min}
@@ -357,9 +348,6 @@ HTML
357
348
  end
358
349
  end
359
350
 
360
- # Преобразовываем значение времени для Монго. Берет Time или DateTime или хэш и выдает хэш вида:
361
- #
362
- # {hours: 10, minutes: 5}
363
351
  def demongoize_time(time)
364
352
  mongoize_time(time)
365
353
  end
@@ -1,3 +1,3 @@
1
1
  module CckForms
2
- VERSION = '3.0.1'
2
+ VERSION = '3.1.0'
3
3
  end
@@ -0,0 +1,2 @@
1
+ //= require ./jquery.workhours
2
+ //= require ./map
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: cck_forms
3
3
  version: !ruby/object:Gem::Version
4
- version: 3.0.1
4
+ version: 3.1.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Ilya Konanykhin
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2016-12-02 00:00:00.000000000 Z
11
+ date: 2017-02-27 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: rails
@@ -66,6 +66,7 @@ files:
66
66
  - lib/cck_forms/date_time.rb
67
67
  - lib/cck_forms/engine.rb
68
68
  - lib/cck_forms/form_builder_extensions.rb
69
+ - lib/cck_forms/neofiles_denormalize.rb
69
70
  - lib/cck_forms/parameter_type_class/album.rb
70
71
  - lib/cck_forms/parameter_type_class/base.rb
71
72
  - lib/cck_forms/parameter_type_class/boolean.rb
@@ -87,6 +88,7 @@ files:
87
88
  - lib/cck_forms/parameter_type_class/time.rb
88
89
  - lib/cck_forms/parameter_type_class/work_hours.rb
89
90
  - lib/cck_forms/version.rb
91
+ - vendor/assets/javascripts/cck_forms/index.js
90
92
  - vendor/assets/javascripts/cck_forms/jquery.workhours.js
91
93
  - vendor/assets/javascripts/cck_forms/map.js.coffee
92
94
  homepage: http://github.com/ilya-konanykhin/cck_forms