visual_condition_builder 0.1.1 → 0.1.3

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA1:
3
- metadata.gz: 21b282ae1f76851c3fa269f704e7bce918948b35
4
- data.tar.gz: ff210a4140a81bb4c3d4da3b3a24df682b0c172f
3
+ metadata.gz: 639abf269b7370702e88934eefc01fc5f6292f80
4
+ data.tar.gz: 93bcd1e3a0c9ff762184ab51e97f8c8d92e024e6
5
5
  SHA512:
6
- metadata.gz: e74f401deb7f39c547daa37b2fe48a61a3ec8d839fa9fb6b81686ed0efe014b9d4d37533b6bd44206db5a4eb28682685c37b6e2e0e8517a59a4b1ff6bb12c9eb
7
- data.tar.gz: 4bbfa1aa0b1ea8033d832710443037963250a6eb70c86ffd0c2b993586adfe818f9dd421a97b56fde09beb7d33f79098197c0b0a19ab10d62e2deee2000f5e6d
6
+ metadata.gz: fa73289dcaa864aff9e537d962aa5ac20ab1626318fb77ce547d9b8d7afb78d15eed9dd66e610fb9478c2a1cafba55f0a9e7379f8771e583d5d13c1b790308df
7
+ data.tar.gz: 513d33a4de95f3332b77c5fdc3eef2eb170ec0a2ef5e0c361b575c357dabb8a580eb977b828627940cf6eb484d1b6eb5b6202d2a57b0bc10fca9844bba4a9e8e
data/README.md CHANGED
@@ -1,6 +1,6 @@
1
- # Search Builder
1
+ # Visual Condition Builder
2
2
 
3
- A great and easy search builder to your rails project
3
+ A great and easy condition builder to your rails project
4
4
 
5
5
  ## How to install
6
6
 
@@ -27,12 +27,15 @@ Add it to your **app/assets/javascripts/application.js**
27
27
 
28
28
  ## Dependency
29
29
 
30
- Antes de iniciar o plugin você precisa ter o jQuery adicionado no seu application.js
30
+ To work properly, the builder needs your project to have:
31
31
 
32
- Caso você tenha os seguintes plugins jQuery indicados no seu application.js, você deve remover:
32
+ - jQuery
33
+
34
+ The builder already has some plugins that can conflict with your current plugins:
33
35
 
34
36
  - [select2](https://github.com/select2/select2)
35
37
  - [autoNumeric](https://github.com/BobKnothe/autoNumeric#default-settings--supported-options)
38
+ - [Sortable](https://github.com/RubaXa/Sortable)
36
39
 
37
40
  ### Select2 Languages
38
41
 
@@ -44,15 +47,13 @@ Select2 supports multiple languages by simply including the right language JS fi
44
47
 
45
48
  ## Dictionaries
46
49
 
47
- As informações do gerador de condições são baseadas em um dicionário, portanto é necessário que você crie seus dicionários de acordo com o necessário.
48
-
49
- Para gerar um novo dicionário use o comando:
50
+ The condition builder information is based on a dictionary, so you need to create your dictionaries as needed.
50
51
 
52
+ To generate the dictionary structure run:
51
53
  ```sh
52
54
  $ rails g visual_condiction_builder:dictionary example
53
55
  ```
54
-
55
- Será criado um arquivo na pasta `app/condition_dictionaries/example_dictionary.rb` com a seguinte estrutura:
56
+ Will be created a file `app/condition_dictionaries/example_dictionary.rb`:
56
57
 
57
58
  ```ruby
58
59
  class ExampleDictionary < VisualConditionBuilder::Dictionary
@@ -64,7 +65,7 @@ class ExampleDictionary < VisualConditionBuilder::Dictionary
64
65
  end
65
66
  ```
66
67
 
67
- Você pode criar multiplos contextos para esse dicionário:
68
+ You can create multiple contexts for a dictionary, so give it a name:
68
69
  ```ruby
69
70
  dictionary :simple do
70
71
  param :name
@@ -78,8 +79,8 @@ Você pode criar multiplos contextos para esse dicionário:
78
79
 
79
80
  ### Params
80
81
 
81
- Você não tem restrição ao uso dos parametros, pois eles não tem ligação com model ou qualquer outro elemento da aplicação.
82
- Ao informar os parametros você pode passar argumentos para personalizar a forma como o gerador de condições será criado:
82
+ You have no restrictions on the use of parameters, they have no binding with models or any element of the application.
83
+ You can pass arguments to customize how the condition generator will be created:
83
84
 
84
85
  ```ruby
85
86
  dictionary do
@@ -90,13 +91,19 @@ Ao informar os parametros você pode passar argumentos para personalizar a forma
90
91
  end
91
92
  ```
92
93
 
93
- Veja abaixo todos os argumentos que você pode usar na construção dos operadores:
94
+ See below all the arguments you can use:
94
95
 
95
- **TABELA DE PARAMETROS DE OPERADORES**
96
+ Param | Description
97
+ --- | ----
98
+ label | Label of the field, if not informed, will search in the file.yml (ver i18n)
99
+ type | Type of the field. Responsible for defining how the values will be inserted (DatePicker, Numeric Mask, ...)
100
+ operators | Defines which operators you want to use, if not informed, the default operators will be used
101
+ values | Sets the default values for this field, restricting the user to those values.
102
+ group | Creates a separation in the field list by grouping the fields with this group
96
103
 
97
- Por padrão, o gerador de condições implementa alguns operadores e argumentos, possibilitando que você informe apenas o nome do operador `operators: [:eq, :between]`
104
+ By default, the condition builder implements some operators and arguments, allowing you to enter only the operator name, like: `operators: [:eq, :between]`
98
105
 
99
- Lista de operadores padrões do gerador de condições
106
+ List of default operators:
100
107
 
101
108
  Operator | Description | Default Arguments
102
109
  --- | --- | ---
@@ -136,8 +143,8 @@ blank | Opposite :present | no_value: true, multiple: false
136
143
  null | where a field is null | no_value: true, multiple: false
137
144
  not_null | Opposite :null | no_value: true, multiple: false
138
145
 
139
- Caso você não informe os operadores, o gerador de condições irá selecionar os operadores baseado no tipo informado:
140
- *Se um tipo não for informado, será considerado STRING*
146
+ if you dont fill the operators, the builder will use the operators by field type.
147
+ *If a type is not informed, it will be considered STRING*
141
148
 
142
149
  Type | Default Operators
143
150
  --- | ---
@@ -147,18 +154,18 @@ DECIMAL, INTEGER | eq, between
147
154
  STRING | cont, eq, start, end, present, blank
148
155
  ... | eq
149
156
 
150
- Também é possível informar listas de valores ou valores pré-definidos para que o gerador de condições para carregar esses valores por padrão:
157
+ The values parameter must be informed to the constructor so the user can make a selection between them.
151
158
 
152
159
  ```ruby
153
160
  dictionary do
154
161
  param :status, values: [{id: 1, label: 'Active', id: 2, label: 'Inactive'}]
155
162
  param :status_list, values: MyStatus.all.dictionary_values(:code, :title)
156
- param :status_proc, values: -> { MyService.get_status }
157
- param :status_ajax, values: ajax_my_status_path
163
+ param :status_proc, values: -> { current_user.get_status }
164
+ param :status_ajax, values: -> { ajax_my_status_path }
158
165
  end
159
166
  ```
160
167
 
161
- Em todos os exemplos acima o resultado deve sempre seguir a estrutura :
168
+ In all the above examples the result must always follow the structure:
162
169
 
163
170
  ```ruby
164
171
  [
@@ -169,11 +176,11 @@ Em todos os exemplos acima o resultado deve sempre seguir a estrutura :
169
176
  ]
170
177
  ```
171
178
 
172
- Quando for utilizar uma chamada AJAX o gerador de condições fará requisições passando dois tipos de parametros: **init** ou **key**, onde:
173
- * init - é o parametro com o valor inicial da lista. Quando o plugin tenta carregar a lista ele deverá mostrar um valor inicial antes da busca feita pelo usuário, portanto esse valor inicial deve ser retornado através do parametro init:
174
- * key - é o parametro com o valor digitado pelo usuário para efetuar o retorno dos valores da lista.
179
+ When using an AJAX call, the condition generator will make requests by passing two types of parameters: ** init ** or ** key **:
180
+ * init - is the parameter with the initial value of the list. When the plugin tries to load the list it should show an initial value before the search made by the user, so this initial value must be returned through the parameter init
181
+ * key - is the parameter with the value entered by the user to return the values from the list.
175
182
 
176
- O retorno deverá seguir a estrutua padrão de valores do dicionário e retornar em formato JSON. Exemplo de um controller que implementa essa função:
183
+ The return must follow the standard dictionary value structure and return in JSON format. Example of a controller that implements this function:
177
184
  ```ruby
178
185
  class CitiesController < ApplicationController
179
186
  def ajax
@@ -192,6 +199,7 @@ end
192
199
  Dictionary Class have public methods to get informations about self:
193
200
  * fields(dictionary_context_name)
194
201
  * dictionary(dictionary_context_name)
202
+ * .new(rails_context).dictionary(dictionary_context_name)
195
203
  * dictionaries
196
204
 
197
205
  ```ruby
@@ -206,6 +214,10 @@ class ExampleDictionary < VisualConditionBuilder::Dictionary
206
214
  param :name
207
215
  param :age
208
216
  end
217
+
218
+ dictionary :with_app_request do
219
+ param :cities, values: -> { ajax_cities_path }
220
+ end
209
221
 
210
222
  end
211
223
 
@@ -223,13 +235,20 @@ ExampleDictionary.dictionary(:complex)
223
235
  # => [{:type=>"STRING", :operators=>[{:operator=>:cont, :multiple=>false, :no_value=>false, :label=>"Contém"}, {:operator=>:eq, :multiple=>false, :no_value=>false, :label=>"Igual"}, {:operator=>:start, :multiple=>false, :no_value=>false, :label=>"Começa com"}, {:operator=>:end, :multiple=>false, :no_value=>false, :label=>"Termina com"}, {:operator=>:present, :no_value=>true, :multiple=>false, :label=>"Presente"}, {:operator=>:blank, :no_value=>true, :multiple=>false, :label=>"Não Presente"}], :values=>[], :group=>"", :label=>"Name", :field=>:name}, {:type=>"STRING", :operators=>[{:operator=>:cont, :multiple=>false, :no_value=>false, :label=>"Contém"}, {:operator=>:eq, :multiple=>false, :no_value=>false, :label=>"Igual"}, {:operator=>:start, :multiple=>false, :no_value=>false, :label=>"Começa com"}, {:operator=>:end, :multiple=>false, :no_value=>false, :label=>"Termina com"}, {:operator=>:present, :no_value=>true, :multiple=>false, :label=>"Presente"}, {:operator=>:blank, :no_value=>true, :multiple=>false, :label=>"Não Presente"}], :values=>[], :group=>"", :label=>"Age", :field=>:age}]
224
236
 
225
237
  ExampleDictionary.dictionaries
226
- # => {:default=>[{:type=>"STRING", :operators=>[{:operator=>:cont, :multiple=>false, :no_value=>false, :label=>"Contém"}, {:operator=>:eq, :multiple=>false, :no_value=>false, :label=>"Igual"}, {:operator=>:start, :multiple=>false, :no_value=>false, :label=>"Começa com"}, {:operator=>:end, :multiple=>false, :no_value=>false, :label=>"Termina com"}, {:operator=>:present, :no_value=>true, :multiple=>false, :label=>"Presente"}, {:operator=>:blank, :no_value=>true, :multiple=>false, :label=>"Não Presente"}], :values=>[], :group=>"", :label=>"Name", :field=>:name}], :padrao=>[{:type=>"STRING", :operators=>[{:operator=>:cont, :multiple=>false, :no_value=>false, :label=>"Contém"}, {:operator=>:eq, :multiple=>false, :no_value=>false, :label=>"Igual"}, {:operator=>:start, :multiple=>false, :no_value=>false, :label=>"Começa com"}, {:operator=>:end, :multiple=>false, :no_value=>false, :label=>"Termina com"}, {:operator=>:present, :no_value=>true, :multiple=>false, :label=>"Presente"}, {:operator=>:blank, :no_value=>true, :multiple=>false, :label=>"Não Presente"}], :values=>[], :group=>"", :label=>"Name", :field=>:name}, {:type=>"STRING", :operators=>[{:operator=>:cont, :multiple=>false, :no_value=>false, :label=>"Contém"}, {:operator=>:eq, :multiple=>false, :no_value=>false, :label=>"Igual"}, {:operator=>:start, :multiple=>false, :no_value=>false, :label=>"Começa com"}, {:operator=>:end, :multiple=>false, :no_value=>false, :label=>"Termina com"}, {:operator=>:present, :no_value=>true, :multiple=>false, :label=>"Presente"}, {:operator=>:blank, :no_value=>true, :multiple=>false, :label=>"Não Presente"}], :values=>[], :group=>"", :label=>"Age", :field=>:age}]}
238
+ # => {:default=>[{:type=>"STRING", :operators=>[{:operator=>:cont, :multiple=>false, :no_value=>false, :label=>"Contém"}, {:operator=>:eq, :multiple=>false, :no_value=>false, :label=>"Igual"}, {:operator=>:start, :multiple=>false, :no_value=>false, :label=>"Começa com"}, {:operator=>:end, :multiple=>false, :no_value=>false, :label=>"Termina com"}, {:operator=>:present, :no_value=>true, :multiple=>false, :label=>"Presente"}, {:operator=>:blank, :no_value=>true, :multiple=>false, :label=>"Não Presente"}], :values=>[], :group=>"", :label=>"Name", :field=>:name}], :padrao=>[{:type=>"STRING", :operators=>[{:operator=>:cont, :multiple=>false, :no_value=>false, :label=>"Contém"}, {:operator=>:eq, :multiple=>false, :no_value=>false, :label=>"Igual"}, {:operator=>:start, :multiple=>false, :no_value=>false, :label=>"Começa com"}, {:operator=>:end, :multiple=>false, :no_value=>false, :label=>"Termina com"}, {:operator=>:present, :no_value=>true, :multiple=>false, :label=>"Presente"}, {:operator=>:blank, :no_value=>true, :multiple=>false, :label=>"Não Presente"}], :values=>[], :group=>"", :label=>"Name", :field=>:name}, {:type=>"STRING", :operators=>[{:operator=>:cont, :multiple=>false, :no_value=>false, :label=>"Contém"}, {:operator=>:eq, :multiple=>false, :no_value=>false, :label=>"Igual"}, {:operator=>:start, :multiple=>false, :no_value=>false, :label=>"Começa com"}, {:operator=>:end, :multiple=>false, :no_value=>false, :label=>"Termina com"}, {:operator=>:present, :no_value=>true, :multiple=>false, :label=>"Presente"}, {:operator=>:blank, :no_value=>true, :multiple=>false, :label=>"Não Presente"}], :values=>[], :group=>"", :label=>"Age", :field=>:age}]}
239
+
240
+ ExampleDictionary.dictionary(:with_app_request)
241
+ # => [{:values=>#<Proc:0x00000008ddffb0@/path_to_project/app/condition_dictionaries/example_dictionary.rb:12 (lambda)>, :type=>"STRING", ...
242
+
243
+ ExampleDictionary.new(rails_app_request).dictionary(:with_app_context)
244
+ # => [{:values=>"/municipios/ajax", :type=>"STRING", ...
227
245
  ```
228
246
 
229
247
  ## Helpers
230
248
 
231
249
  #### (class) dictionary_values(param_id, param_label)
232
- Deve ser utilizado em objetos do tipo: Array ou ActiveRecord::Relation e usa o primeiro parametro como **id** e o segundo como **label** na construção da estrutura de valores para o dicionário
250
+ It should be used in objects of type: **Array** or **ActiveRecord::Relation**, the first parameter is **id** and the second is **label** for the dictionary
251
+
233
252
  ```ruby
234
253
  dictionary do
235
254
  param :book_id, values: Book.all.dictionary_values(:code, :title)
@@ -239,7 +258,10 @@ end
239
258
  ```
240
259
 
241
260
  #### (view) conditions_fields(name_of_dictionary)
261
+
262
+ Creates a field selector in a dropdown element (bootstrap).
242
263
  Cria um seletor de campos em um elemento dropdown (bootstrap).
264
+
243
265
  ```haml
244
266
  = conditions_fields :example
245
267
  -# with context:
@@ -42,32 +42,33 @@
42
42
  return;
43
43
  }
44
44
 
45
+ var new_id = new Date().getTime();
46
+
45
47
  //BLOCK ELEMENTS HTML
46
- var block = $('<div class="group-conditions clearfix"></div>');
48
+ var block = $('<div id="group_conditions_'+new_id+'" data-id="'+new_id+'" class="group-conditions clearfix"></div>');
47
49
  block.append('<span class="conditions-move"></span>');
48
50
  var field_label = fieldObj.label;
49
51
  if (!is_blank(fieldObj.group)) {
50
52
  field_label = Object.values(fieldObj.group)[0] + ' : ' + field_label;
51
53
  }
52
- block.append('<input type="hidden" class="field form-control" value="' + fieldObj.field + '" data-type="' + fieldObj.type + '" />');
53
- block.append('<span class="field_name label label-info">' + field_label + ' <a href="" class="remove-condition">&#10006;</a></span>');
54
- block.append('<select class="operators hide form-control"></select>');
55
- block.append('<span class="fixed_operator hide form-control"></span>');
56
- block.append('<select class="values hide form-control"></select>');
57
- block.append('<input class="fixed_value hide form-control" />');
54
+ block.append('<input id="field_'+new_id+'" data-group-id="'+new_id+'" type="hidden" class="field form-control" value="' + fieldObj.field + '" data-type="' + fieldObj.type + '" />');
55
+ block.append('<span id="field_name_'+new_id+'" data-group-id="'+new_id+'" class="field_name label label-info">' + field_label + ' <a href="" id="remove_condition_'+new_id+'" data-group-id="'+new_id+'" class="remove-condition">&#10006;</a></span>');
56
+ block.append('<select id="operators_'+new_id+'" data-group-id="'+new_id+'" class="operators hide form-control"></select>');
57
+ block.append('<span id="fixed_operator_'+new_id+'" data-group-id="'+new_id+'" class="fixed_operator hide form-control"></span>');
58
+ block.append('<select id="values_'+new_id+'" data-group-id="'+new_id+'" class="values hide form-control"></select>');
59
+ block.append('<input id="fixed_value_'+new_id+'" data-group-id="'+new_id+'" class="fixed_value hide form-control" />');
58
60
  if (plugin.parameters.debug == true) {
59
61
  block.append('<p class="expression help-block"></p>');
60
62
  }
61
- $elField = block.find('.field');
62
- $elOperators = block.find('.operators');
63
- $elValues = block.find('.values, .fixed_value');
63
+ $elField = block.find('#field_'+new_id);
64
+ $elOperators = block.find('#operators_'+new_id);
65
+ $elValues = block.find('#values_'+new_id+', #fixed_value_'+new_id);
64
66
 
65
67
  //EVENTS
66
- block.find('.remove-condition').on('click', event_remove_condition);
68
+ block.find('#remove_condition_'+new_id).on('click', event_remove_condition);
67
69
  $elOperators.on('change', event_load_values);
68
70
 
69
71
  $element.append(block);
70
- $element.trigger('change');
71
72
 
72
73
  //LOAD OPERATORS
73
74
  plugin.load_operators($elField);
@@ -85,16 +86,16 @@
85
86
 
86
87
  plugin.load_operators = function (fieldEl) {
87
88
  var $fieldElement = $(fieldEl);
89
+ var groupConditionId = $fieldElement.attr('data-group-id');
88
90
  var field_name = getFieldValue($fieldElement);
89
91
  var field = getFieldByName(field_name);
90
- var $groupConditions = $fieldElement.closest('.group-conditions');
91
- var $operators = $groupConditions.find('.operators');
92
- var $fixedOperator = $groupConditions.find('.fixed_operator');
93
- var $values = $groupConditions.find('.values');
94
- var $fixedValue = $groupConditions.find('.fixed_value');
92
+ var $operators = $('#operators_'+groupConditionId);
93
+ var $fixedOperator = $('#fixed_operator_'+groupConditionId);
94
+ var $values = $('.values_'+groupConditionId);
95
+ var $fixedValue = $('.fixed_value_'+groupConditionId);
95
96
  var operators = field.operators;
96
97
 
97
- remove_plugins_elements($groupConditions);
98
+ remove_plugins_elements(groupConditionId);
98
99
  $operators.html('').addClass('hide');
99
100
  $fixedOperator.val('').addClass('hide');
100
101
  $values.html('').addClass('hide');
@@ -113,8 +114,9 @@
113
114
  $operators.trigger('change');
114
115
  };
115
116
 
116
- plugin.fill_condition = function (groupConditions, data) {
117
- if (data != undefined && data.length > 0 && groupConditions != undefined) {
117
+ plugin.fill_condition = function (groupConditionId, data) {
118
+ if (data != undefined && data.length > 0 && groupConditionId != undefined) {
119
+ var groupConditions = getGroupConditionById(groupConditionId)
118
120
  $elOperators = getOperatorElement(groupConditions);
119
121
  $elOperators.val(data[1]).trigger('change');
120
122
 
@@ -136,6 +138,7 @@
136
138
  }
137
139
  });
138
140
  $elValues.val(values).trigger('change');
141
+ triggerEl = false;
139
142
  }
140
143
  } else {
141
144
  $elValues.val(data[2]);
@@ -152,7 +155,6 @@
152
155
  if ($elInput.length > 0) {
153
156
  plugin.parameters.values = JSON.parse($elInput.val());
154
157
  }
155
- console.log(plugin.parameters.values);
156
158
  } else {
157
159
  plugin.parameters.values = values;
158
160
  }
@@ -187,6 +189,10 @@
187
189
  }; //END getResult;
188
190
 
189
191
  //~~~ PRIVATE
192
+ var getGroupConditionById = function (groupConditionId) {
193
+ return $('#group_conditions_'+groupConditionId);
194
+ }; //END getFieldElement
195
+
190
196
  var getFieldByName = function (field_name) {
191
197
  var f = $.map(plugin.parameters.dictionary, function (h, i) {
192
198
  if (h.field == field_name) {
@@ -286,12 +292,14 @@
286
292
  }; //END event_remove_condition
287
293
 
288
294
  var event_load_values = function (ev) {
289
- var $groupConditions = $(this).closest('.group-conditions');
295
+ var $target = $(ev.target);
296
+ var groupConditionId = $target.attr('data-group-id');
297
+ var $groupConditions = getGroupConditionById(groupConditionId);
290
298
  var field_name = getFieldValue($groupConditions);
291
299
  var field = getFieldByName(field_name);
292
- var op_el = $(this).hasClass('operators') ? $(this).find('option:selected') : $(this);
300
+ var op_el = $target.hasClass('operators') ? $target.find('option:selected') : $target;
293
301
  var values = field.values;
294
- build_values(op_el, values);
302
+ build_values(op_el, values, groupConditionId);
295
303
  }; //END event_load_values
296
304
 
297
305
  var event_build_expression = function (ev) {
@@ -313,13 +321,14 @@
313
321
  $.each(plugin.parameters.values, function (i, data) {
314
322
  var field = data[0];
315
323
  var groupConditions = plugin.add_condition(field);
316
- plugin.fill_condition(groupConditions, data);
324
+ var groupConditionId = groupConditions.attr('data-id');
325
+ plugin.fill_condition(groupConditionId, data);
317
326
  });
318
327
  }
319
328
  };
320
329
 
321
- var build_values = function (op_el, values) {
322
- var $groupConditions = $(op_el).closest('.group-conditions');
330
+ var build_values = function (op_el, values, groupConditionId) {
331
+ var $groupConditions = getGroupConditionById(groupConditionId);
323
332
  var no_value = op_el.attr('data-no-value');
324
333
  var $values = $groupConditions.find('.values');
325
334
  var $fixedValue = $groupConditions.find('.fixed_value');
@@ -364,19 +373,21 @@
364
373
  }
365
374
  }
366
375
 
367
- validate_multiple_values($groupConditions);
368
- normalize_values_type($groupConditions, list_with_item, multiple);
376
+ validate_multiple_values(groupConditionId);
377
+ normalize_values_type(groupConditionId, list_with_item, multiple);
369
378
  }; //END build_values
370
379
 
371
- var validate_multiple_values = function (groupConditions) {
372
- var $groupConditions = $(groupConditions);
380
+ var validate_multiple_values = function(groupConditionId) {
381
+ var $groupConditions = getGroupConditionById(groupConditionId);
373
382
  var $operatorEl = getOperatorElement($groupConditions);
374
383
  var $valueEl = getValueElement($groupConditions);
375
384
  if ($operatorEl.hasClass('operators')) {
376
385
  $operatorEl = $operatorEl.find('option:selected');
377
386
  }
378
387
  var multiple = $operatorEl.attr('data-multiple');
379
- remove_plugins_elements(groupConditions);
388
+
389
+ remove_plugins_elements(groupConditionId);
390
+
380
391
  if (!isNaN(multiple)) {
381
392
  for (var i = 1; i < parseInt(multiple); i++) {
382
393
  var $valueElClone = $valueEl.clone();
@@ -389,18 +400,18 @@
389
400
  $valueEl.attr('multiple', multiple == 'true');
390
401
  }; //END validate_multiple_values
391
402
 
392
- var remove_plugins_elements = function (groupConditions) {
393
- $groupConditions = $(groupConditions);
403
+ var remove_plugins_elements = function (groupConditionId) {
404
+ $groupConditions = getGroupConditionById(groupConditionId);
394
405
  $groupConditions.find('.fixed_value[class*="select2-"], .values[class*="select2-"]').select2('destroy');
395
406
  $groupConditions.find('.values.clone, .fixed_value.clone').remove();
396
407
  }; //END remove_plugins_elements
397
408
 
398
- var normalize_values_type = function (groupConditions, list_with_item, multiple) {
399
- var $groupConditions = $(groupConditions);
409
+ var normalize_values_type = function (groupConditionId, list_with_item, multiple) {
410
+ var $groupConditions = getGroupConditionById(groupConditionId);
400
411
  var $fieldEl = getFieldElement($groupConditions);
401
412
  var $valueEl = getValueElement($groupConditions);
402
413
  var uTypeField = $fieldEl.attr('data-type'); //.toUpperCase();
403
- var field_name = getFieldValue(groupConditions);
414
+ var field_name = getFieldValue($groupConditions);
404
415
 
405
416
  $.each($valueEl, function (i, el) {
406
417
  var $el = $(el);
@@ -506,7 +517,6 @@
506
517
  if (cb != undefined && typeof cb == 'function') {
507
518
  cb(dates)
508
519
  }
509
- ;
510
520
  }, errorr: function (errorr) {
511
521
  alert("Could not load url " + url);
512
522
  }
@@ -518,9 +528,10 @@
518
528
  var build_select2_element = function (el, tags) {
519
529
  if (tags == undefined) tags = true;
520
530
  var $el = $(el);
521
- var select2Config = plugin.parameters.select2Config;
531
+ var select2Config = $.extend({},plugin.parameters.select2Config);
522
532
  var ajax_url = $el.attr('data-ajax-values');
523
- if (ajax_url != undefined) {
533
+
534
+ if (ajax_url !== undefined) {
524
535
  $.extend(select2Config, {
525
536
  ajax: {
526
537
  url: ajax_url,
@@ -552,7 +563,7 @@
552
563
  data: {init: initVal}
553
564
  }).done(function (data) {
554
565
  var row = $.isArray(data) ? data[0] : data;
555
- if (!is_blank(row.id) && !is_blank(row.label)) {
566
+ if (row!==undefined && row.id!==undefined && row.label!==undefined) {
556
567
  callback({id: row.id, text: row.label});
557
568
  } else {
558
569
  callback({id: initVal, text: initVal});
@@ -567,13 +578,11 @@
567
578
  var totalItems = $el.find('option').length;
568
579
  if ($el.hasClass('operators')) {
569
580
  $.extend(select2Config, {placeholder: plugin.parameters.placeholder.operators});
570
- }
571
- if ($el.hasClass('values')) {
581
+ } else if ($el.hasClass('values')) {
572
582
  $.extend(select2Config, {placeholder: plugin.parameters.placeholder.values});
573
583
  }
574
-
575
584
  if (tags == true) {
576
- $.extend(select2Config, {tags: true, tokenSeparators: [',', ';']});
585
+ $.extend(select2Config, {tags: true, tokenSeparators: [',',';']});
577
586
  }
578
587
 
579
588
  $.fn.select2.defaults.set("theme", (select2Config.theme || 'bootstrap'));
@@ -0,0 +1,22 @@
1
+ class ApplicationDictionary < ::ApplicationController
2
+ include VisualConditionBuilder::ApplicationHelper
3
+
4
+ def initialize(request)
5
+ self.request = request
6
+ end
7
+
8
+ def dictionary(dictionar_klass_name, context)
9
+ @klass = Object.const_get "#{dictionar_klass_name}".classify
10
+ dictionary = @klass.dictionary(context)
11
+ dictionary.each do |field|
12
+ if field[:values].present? && field[:values].is_a?(Proc)
13
+ field[:values] = self.instance_exec(&field[:values])
14
+ end
15
+ if field[:operators].present? && field[:operators].is_a?(Proc)
16
+ field[:operators] = self.instance_exec(&field[:operators])
17
+ end
18
+ end
19
+ dictionary
20
+ end
21
+
22
+ end
@@ -9,7 +9,7 @@ module VisualConditionBuilder
9
9
  hArgs = normalize_placeholder_label(hArgs)
10
10
 
11
11
  builder_options = {
12
- dictionary: ObrigacaoDictionary.dictionary
12
+ dictionary: ObrigacaoDictionary.dictionary(get_dictionary_context(dictionary), self.request)
13
13
  }.deep_merge(hArgs)
14
14
 
15
15
  capture do
@@ -9,11 +9,15 @@ module VisualConditionBuilder
9
9
  end
10
10
  end
11
11
 
12
- def dictionary(name=:default, &block)
12
+ def dictionary(name=:default, request=nil, &block)
13
13
  (self.dictionaries ||= {})[name] ||= []
14
14
  @dictionary_name = name
15
15
  block.call if block_given?
16
- self.dictionaries[name]
16
+ if request.present?
17
+ ApplicationDictionary.new(request).send(:dictionary, self.name, name)
18
+ else
19
+ self.dictionaries[name]
20
+ end
17
21
  end
18
22
 
19
23
  def fields(dictionary_name=:default)
@@ -47,9 +51,6 @@ module VisualConditionBuilder
47
51
  args[:label] ||= I18n.t(attr.to_sym, default: attr.to_s.humanize, scope: [:condition_dictionaries, dictionary_name])
48
52
  args[:field] ||= attr
49
53
  end
50
- if args[:values].present? && args[:values].is_a?(Proc)
51
- args[:values] = args[:values].call
52
- end
53
54
  if normalized_name(args[:type])==:boolean && args[:label] !~ /\?$/
54
55
  args[:label]+='?'
55
56
  end
@@ -1,5 +1,4 @@
1
1
  module VisualConditionBuilder
2
2
  class Engine < ::Rails::Engine
3
-
4
3
  end
5
4
  end
@@ -1,3 +1,3 @@
1
1
  module VisualConditionBuilder
2
- VERSION = "0.1.1"
2
+ VERSION = "0.1.3"
3
3
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: visual_condition_builder
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.1
4
+ version: 0.1.3
5
5
  platform: ruby
6
6
  authors:
7
7
  - Bruno Porto
@@ -78,9 +78,8 @@ files:
78
78
  - app/assets/stylesheets/visual_condition_builder/condition_builder.css
79
79
  - app/assets/stylesheets/visual_condition_builder/select2-bootstrap.css
80
80
  - app/assets/stylesheets/visual_condition_builder/select2.css
81
- - app/controllers/application_widget.rb
81
+ - app/controllers/application_dictionary.rb
82
82
  - app/controllers/visual_condition_builder/application_controller.rb
83
- - app/controllers/visual_condition_builder/widgets_controller.rb
84
83
  - app/helpers/visual_condition_builder/application_helper.rb
85
84
  - app/models/visual_condition_builder/user.rb
86
85
  - app/views/visual_condition_builder/widgets/_widgets_list.html.erb
@@ -1,56 +0,0 @@
1
- class ApplicationWidget < ::ApplicationController
2
- include SingletonHelper
3
-
4
- attr_singleton :refresh_interval, 0
5
-
6
- def initialize(request)
7
- self.request = request
8
- end
9
-
10
- def render_template(view_file=nil, *args)
11
- args << {template: view_file}
12
- render_to_string *args
13
- end
14
-
15
- def view(view_file=nil, klass=nil)
16
- class_caller = klass || (caller[0].match(/(\b\w+)\.rb/)[1] rescue '')
17
- action_caller = view_file || (caller[0].match(/`(.*)'/)[1] rescue '')
18
- view_file = "widgets/#{class_caller.to_s.sub('_widget','')}/#{action_caller}" unless lookup_context.find_all(view_file).any?
19
- instance_variable_set(:@view_file, view_file)
20
- end
21
-
22
- def self.name?
23
- instance_variable_defined?(:@widget_name) ? instance_variable_get(:@widget_name) : ''
24
- end
25
-
26
- def self.name!(value)
27
- # define_singleton_method(:widget_name) {value}
28
- instance_variable_set(:@widget_name, value)
29
- end
30
-
31
- def self.description?(attr=nil)
32
- attr='widget' if attr.nil?
33
- instance_variable_defined?("@description_#{attr}") ? instance_variable_get("@description_#{attr}") : ''
34
- end
35
-
36
- def self.description!(*args)
37
- if args.size == 1
38
- instance_variable_set(:@description_widget, args[0])
39
- elsif args.size == 2
40
- instance_variable_set("@description_#{args[0]}", args[1])
41
- end
42
- end
43
-
44
- def self.widgets
45
- # ApplicationWidget.descendants.map do |klass| #Não estava carregando no primeiro load...
46
- Dir["#{Rails.root}/app/widgets/*.rb"].map do |file_path|
47
- file_name = File.basename(file_path, ".rb")
48
- klass = Object.const_get file_name.classify
49
- actions = klass.instance_methods(false).map do |action|
50
- {name: action, description: klass.description?(action)}
51
- end
52
- {code: klass.to_s.tableize.sub('_widgets',''), name: klass.name?, description: klass.description?, actions: actions}
53
- end
54
- end
55
-
56
- end
@@ -1,45 +0,0 @@
1
- require_dependency "visual_condition_builder/application_controller"
2
-
3
- module VisualConditionBuilder
4
- class WidgetsController < ApplicationController
5
-
6
- def load
7
- widget = VisualConditionBuilder::Widget.new(params[:widget_name], self.request)
8
- content = widget.html(params[:widget_action])
9
- rescue Exception => e
10
- content = e.message
11
- ensure
12
- render html: content, layout: false
13
- end
14
-
15
- def user
16
- user_id = params[:id] || current_user.id
17
- @widgets_code = VisualConditionBuilder::User.where(user_id: user_id).pluck(:widget, :action).map{|r| "#{r[0]}_#{r[1]}"}
18
- render partial: 'widgets_list'
19
- end
20
-
21
- def index
22
- end
23
-
24
- def save
25
- user_id = params[:user_id] || current_user.id
26
- widgets = params[:widgets]
27
- widget_name_user = []
28
- action_user = []
29
- if widgets.present?
30
- widgets.each do |widget|
31
- widget_name, action = widget.split('|')
32
- if widget_name && action
33
- widget_name_user << widget_name
34
- action_user << action
35
- VisualConditionBuilder::User.find_or_create_by(widget: widget_name, action: action, user_id: user_id)
36
- end
37
- end
38
- end
39
- VisualConditionBuilder::User.where(user_id: user_id).where.not(widget: widget_name_user, action: action_user).destroy_all
40
- flash[:success] = 'Alterações foram salvas com sucesso!'
41
- redirect_to visual_condition_builder_path
42
- end
43
-
44
- end
45
- end