From 992ca7887b0838ae520c6f9d570a9183357b0dd4 Mon Sep 17 00:00:00 2001 From: Bogdan Gusiev Date: Sat, 2 Nov 2024 22:00:18 +0100 Subject: [PATCH 001/157] Refactor --- lib/datagrid/form_builder.rb | 41 +++++++++++++++++++----------------- 1 file changed, 22 insertions(+), 19 deletions(-) diff --git a/lib/datagrid/form_builder.rb b/lib/datagrid/form_builder.rb index d3c6a3f..02cfc48 100644 --- a/lib/datagrid/form_builder.rb +++ b/lib/datagrid/form_builder.rb @@ -24,7 +24,7 @@ def datagrid_label(filter_or_attribute, text = nil, **options, &block) end # @visibility private - def datagrid_filter_input(attribute_or_filter, **options) + def datagrid_filter_input(attribute_or_filter, **options, &block) filter = datagrid_get_filter(attribute_or_filter) value = object.filter_value_as_string(filter) type = options[:type]&.to_sym @@ -33,19 +33,33 @@ def datagrid_filter_input(attribute_or_filter, **options) options[:value] = "" end if type == :"datetime-local" - datetime_local_field filter.name, **options + datetime_local_field filter.name, **options, &block elsif type == :"date" - date_field filter.name, **options + date_field filter.name, **options, &block elsif type == :textarea - text_area filter.name, value: value, **options, type: nil + text_area filter.name, value: value, **options, type: nil, &block + elsif type == :select + select( + filter.name, + object.select_options(filter) || [], + { + include_blank: filter.include_blank, + prompt: filter.prompt, + include_hidden: false + }, + multiple: filter.multiple?, + **options, + type: nil, + &block + ) else - text_field filter.name, value: value, **options + text_field filter.name, value: value, **options, &block end end protected - def datagrid_extended_boolean_filter(filter, options = {}) - datagrid_enum_filter(filter, options) + def datagrid_extended_boolean_filter(filter, options = {}, &block) + datagrid_filter_input(filter, **options, type: :select, &block) end def datagrid_boolean_filter(filter, options = {}) @@ -82,18 +96,7 @@ def datagrid_enum_filter(filter, options = {}, &block) } ) else - select( - filter.name, - object.select_options(filter) || [], - { - include_blank: filter.include_blank, - prompt: filter.prompt, - include_hidden: false - }, - multiple: filter.multiple?, - **options, - &block - ) + datagrid_filter_input(filter, **options, type: :select, &block) end end From a3daafcd9113adad75c68f201fa516a699b37f75 Mon Sep 17 00:00:00 2001 From: Bogdan Gusiev Date: Sun, 3 Nov 2024 10:09:13 +0100 Subject: [PATCH 002/157] Add debugger --- Gemfile | 1 + 1 file changed, 1 insertion(+) diff --git a/Gemfile b/Gemfile index 4a624e7..aed7bd1 100644 --- a/Gemfile +++ b/Gemfile @@ -9,6 +9,7 @@ group :development do gem "csv" # removed from standard library in Ruby 3.4 gem "nokogiri" # used to test html output gem "pry-byebug" + gem 'debug' gem "rspec" gem "sequel" gem "sqlite3", "~> 1.7.0" From f3337caf86402000b7869443eba7c8ec926fbb06 Mon Sep 17 00:00:00 2001 From: Bogdan Gusiev Date: Sun, 3 Nov 2024 10:34:39 +0100 Subject: [PATCH 003/157] Migrate to rails-dom-testing --- Gemfile | 1 + lib/datagrid/form_builder.rb | 4 +++- spec/support/matchers.rb | 8 +++++--- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/Gemfile b/Gemfile index aed7bd1..cf03de9 100644 --- a/Gemfile +++ b/Gemfile @@ -10,6 +10,7 @@ group :development do gem "nokogiri" # used to test html output gem "pry-byebug" gem 'debug' + gem "rails-dom-testing", "~> 2.2" gem "rspec" gem "sequel" gem "sqlite3", "~> 1.7.0" diff --git a/lib/datagrid/form_builder.rb b/lib/datagrid/form_builder.rb index 02cfc48..9542b27 100644 --- a/lib/datagrid/form_builder.rb +++ b/lib/datagrid/form_builder.rb @@ -38,6 +38,8 @@ def datagrid_filter_input(attribute_or_filter, **options, &block) date_field filter.name, **options, &block elsif type == :textarea text_area filter.name, value: value, **options, type: nil, &block + elsif type == :checkbox + check_box filter.name, **options elsif type == :select select( filter.name, @@ -63,7 +65,7 @@ def datagrid_extended_boolean_filter(filter, options = {}, &block) end def datagrid_boolean_filter(filter, options = {}) - check_box(filter.name, options) + datagrid_filter_input(filter.name, **options, type: :checkbox) end def datagrid_date_filter(filter, options = {}) diff --git a/spec/support/matchers.rb b/spec/support/matchers.rb index a0ae6cd..76dd2f1 100644 --- a/spec/support/matchers.rb +++ b/spec/support/matchers.rb @@ -1,4 +1,4 @@ -require "nokogiri" +require 'rails/dom/testing' def equal_to_dom(text) EqualToDom.new(text) @@ -8,7 +8,9 @@ def match_css_pattern(pattern) CssPattern.new(pattern) end + class EqualToDom + include Rails::Dom::Testing::Assertions::DomAssertions def initialize(expectation) @expectation = normalize(expectation) @@ -16,11 +18,11 @@ def initialize(expectation) def matches?(text) @matcher = normalize(text) - @matcher == @expectation + compare_doms(@expectation, @matcher, false) end def normalize(text) - Nokogiri::HTML::DocumentFragment.parse(text.split("\n").map(&:strip).join("")).to_s + fragment(text) end def failure_message From c278f0c458e28c6b456bd66a824adef4b6b7e832 Mon Sep 17 00:00:00 2001 From: Bogdan Gusiev Date: Sun, 3 Nov 2024 10:45:05 +0100 Subject: [PATCH 004/157] Refactor --- lib/datagrid/form_builder.rb | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/lib/datagrid/form_builder.rb b/lib/datagrid/form_builder.rb index 9542b27..e9461e9 100644 --- a/lib/datagrid/form_builder.rb +++ b/lib/datagrid/form_builder.rb @@ -10,7 +10,7 @@ module FormBuilder # * text_field for other filter types def datagrid_filter(filter_or_attribute, partials: nil, **options, &block) filter = datagrid_get_filter(filter_or_attribute) - options = add_html_classes({**filter.input_options, **options}, filter.name, datagrid_filter_html_class(filter)) + options = add_html_classes({**filter.input_options, **options}, *datagrid_filter_html_classes(filter)) self.send( filter.form_builder_helper_name, filter, **options, &block) end @@ -26,7 +26,6 @@ def datagrid_label(filter_or_attribute, text = nil, **options, &block) # @visibility private def datagrid_filter_input(attribute_or_filter, **options, &block) filter = datagrid_get_filter(attribute_or_filter) - value = object.filter_value_as_string(filter) type = options[:type]&.to_sym if options.has_key?(:value) && options[:value].nil? && [:"datetime-local", :"date"].include?(type) # https://github.com/rails/rails/pull/53387 @@ -37,9 +36,11 @@ def datagrid_filter_input(attribute_or_filter, **options, &block) elsif type == :"date" date_field filter.name, **options, &block elsif type == :textarea - text_area filter.name, value: value, **options, type: nil, &block + text_area filter.name, value: object.filter_value_as_string(filter) , **options, type: nil, &block elsif type == :checkbox check_box filter.name, **options + elsif type == :hidden + hidden_field filter.name, **options elsif type == :select select( filter.name, @@ -55,7 +56,7 @@ def datagrid_filter_input(attribute_or_filter, **options, &block) &block ) else - text_field filter.name, value: value, **options, &block + text_field filter.name, value: object.filter_value_as_string(filter) , **options, &block end end @@ -209,8 +210,8 @@ def datagrid_get_filter(attribute_or_filter) end end - def datagrid_filter_html_class(filter) - filter.class.to_s.demodulize.underscore + def datagrid_filter_html_classes(filter) + [filter.name, filter.class.to_s.demodulize.underscore] end def add_html_classes(options, *classes) From 494b1832cfc7d27895edc888fab183f814ea1850 Mon Sep 17 00:00:00 2001 From: Bogdan Gusiev Date: Sun, 3 Nov 2024 13:41:37 +0100 Subject: [PATCH 005/157] Make CSS classes generation consistent --- app/views/datagrid/_enum_checkboxes.html.erb | 4 +- lib/datagrid/filters/base_filter.rb | 5 +- lib/datagrid/filters/enum_filter.rb | 6 +++ lib/datagrid/form_builder.rb | 20 ++++--- spec/datagrid/form_builder_spec.rb | 56 ++++++++++---------- 5 files changed, 52 insertions(+), 39 deletions(-) diff --git a/app/views/datagrid/_enum_checkboxes.html.erb b/app/views/datagrid/_enum_checkboxes.html.erb index 9f48319..f114c17 100644 --- a/app/views/datagrid/_enum_checkboxes.html.erb +++ b/app/views/datagrid/_enum_checkboxes.html.erb @@ -4,8 +4,8 @@ You can add indent if whitespace doesn't matter for you %> <%- elements.each do |value, text, checked| -%> <%- id = [form.object_name, filter.name, value].join('_').underscore -%> -<%= form.label filter.name, options.merge(for: id) do -%> -<%= form.check_box(filter.name, {multiple: true, id: id, checked: checked, include_hidden: false}, value.to_s, nil) -%> +<%= form.datagrid_label(filter.name, **options, for: id) do -%> +<%= form.datagrid_filter_input(filter.name, type: :checkbox, multiple: true, id: id, checked: checked, include_hidden: false, value: value.to_s) -%> <%= text -%> <%- end -%> <%- end -%> diff --git a/lib/datagrid/filters/base_filter.rb b/lib/datagrid/filters/base_filter.rb index db468d7..710d244 100644 --- a/lib/datagrid/filters/base_filter.rb +++ b/lib/datagrid/filters/base_filter.rb @@ -136,6 +136,10 @@ def enabled?(grid) ::Datagrid::Utils.process_availability(grid, options[:if], options[:unless]) end + def default_html_classes + [ name, self.class.to_s.demodulize.underscore ] + end + protected def default_filter_where(scope, value) @@ -179,6 +183,5 @@ def default_filter(value, scope, grid) default_filter_where(scope, value) end end - end diff --git a/lib/datagrid/filters/enum_filter.rb b/lib/datagrid/filters/enum_filter.rb index a76b097..809d10c 100644 --- a/lib/datagrid/filters/enum_filter.rb +++ b/lib/datagrid/filters/enum_filter.rb @@ -17,6 +17,12 @@ def parse(value) value end + def default_html_classes + res = super + res.push('checkboxes') if checkboxes? + res + end + def strict options[:strict] end diff --git a/lib/datagrid/form_builder.rb b/lib/datagrid/form_builder.rb index e9461e9..45f0fb2 100644 --- a/lib/datagrid/form_builder.rb +++ b/lib/datagrid/form_builder.rb @@ -10,7 +10,6 @@ module FormBuilder # * text_field for other filter types def datagrid_filter(filter_or_attribute, partials: nil, **options, &block) filter = datagrid_get_filter(filter_or_attribute) - options = add_html_classes({**filter.input_options, **options}, *datagrid_filter_html_classes(filter)) self.send( filter.form_builder_helper_name, filter, **options, &block) end @@ -20,12 +19,13 @@ def datagrid_filter(filter_or_attribute, partials: nil, **options, &block) # @return [String] a form label tag for the corresponding filter name def datagrid_label(filter_or_attribute, text = nil, **options, &block) filter = datagrid_get_filter(filter_or_attribute) - label(filter.name, text || filter.header, **filter.label_options, **options, &block) + label(filter.name, text || filter.header, class: filter.default_html_classes, **filter.label_options, **options, &block) end # @visibility private def datagrid_filter_input(attribute_or_filter, **options, &block) filter = datagrid_get_filter(attribute_or_filter) + options = add_filter_options(filter, **options) type = options[:type]&.to_sym if options.has_key?(:value) && options[:value].nil? && [:"datetime-local", :"date"].include?(type) # https://github.com/rails/rails/pull/53387 @@ -38,7 +38,8 @@ def datagrid_filter_input(attribute_or_filter, **options, &block) elsif type == :textarea text_area filter.name, value: object.filter_value_as_string(filter) , **options, type: nil, &block elsif type == :checkbox - check_box filter.name, **options + # raise options.inspect + check_box filter.name, options, options.fetch(:value, 1) elsif type == :hidden hidden_field filter.name, **options elsif type == :select @@ -83,7 +84,6 @@ def datagrid_default_filter(filter, options = {}) def datagrid_enum_filter(filter, options = {}, &block) if filter.checkboxes? - options = add_html_classes(options, 'checkboxes') elements = object.select_options(filter).map do |element| text, value = @template.send(:option_text_and_value, element) checked = enum_checkbox_checked?(filter, value) @@ -124,6 +124,7 @@ def datagrid_integer_filter(filter, options = {}) def datagrid_dynamic_filter(filter, options = {}) input_name = "#{object_name}[#{filter.name.to_s}][]" field, operation, value = object.filter_value(filter) + options = add_filter_options(filter, **options) options = options.merge(name: input_name) field_input = dynamic_filter_select( filter.name, @@ -210,10 +211,6 @@ def datagrid_get_filter(attribute_or_filter) end end - def datagrid_filter_html_classes(filter) - [filter.name, filter.class.to_s.demodulize.underscore] - end - def add_html_classes(options, *classes) Datagrid::Utils.add_html_classes(options, *classes) end @@ -233,6 +230,13 @@ def render_partial(name, locals) @template.render partial: partial_path(name), locals: locals end + def add_filter_options(filter, **options) + add_html_classes( + {**filter.input_options, **options}, + *filter.default_html_classes, + ) + end + class Error < StandardError end end diff --git a/spec/datagrid/form_builder_spec.rb b/spec/datagrid/form_builder_spec.rb index c374330..1ca89a3 100644 --- a/spec/datagrid/form_builder_spec.rb +++ b/spec/datagrid/form_builder_spec.rb @@ -161,27 +161,27 @@ class MyTemplate let(:_filter_options) { {:id => "hello"} } let(:_range) { [1,2]} it { should equal_to_dom( - '' + + '' + ' - ' + - '' + '' )} end context "with only left bound" do let(:_range) { [10, nil]} it { should equal_to_dom( - '' + + '' + ' - ' + - '' + '' )} it { should be_html_safe } end context "with only right bound" do let(:_range) { [nil, 10]} it { should equal_to_dom( - '' + + '' + ' - ' + - '' + '' )} it { should be_html_safe } end @@ -189,9 +189,9 @@ class MyTemplate context "with invalid range value" do let(:_range) { 2..1 } it { should equal_to_dom( - '' + + '' + ' - ' + - '' + '' )} end @@ -207,7 +207,7 @@ class MyTemplate let(:view_options) { { :partials => 'not_existed' } } let(:_range) { nil } it { should equal_to_dom( - ' - ' + ' - ' ) } end @@ -223,9 +223,9 @@ class MyTemplate } let(:_range) { [1.5,2.5]} it { should equal_to_dom( - '' + + '' + ' - ' + - '' + '' )} end @@ -241,9 +241,9 @@ class MyTemplate let(:_range) { ["2012-01-03", nil]} it { should equal_to_dom( - '' + + '' + ' - ' + - '' + '' )} it { should be_html_safe } end @@ -255,18 +255,18 @@ class MyTemplate end let(:_range) { ["2013/01/01", '2013/02/02']} it { should equal_to_dom( - '' + + '' + ' - ' + - '' + '' )} end context "with only right bound" do let(:_range) { [nil, "2012-01-03"]} it { should equal_to_dom( - '' + + '' + ' - ' + - '' + '' )} it { should be_html_safe } end @@ -274,9 +274,9 @@ class MyTemplate context "with invalid range value" do let(:_range) { Date.parse('2012-01-02')..Date.parse('2012-01-01') } it { should equal_to_dom( - '' + + '' + ' - ' + - '' + '' )} end context "with blank range value" do @@ -287,9 +287,9 @@ class MyTemplate end let(:_range) { [nil, nil] } it { should equal_to_dom( - '' + + '' + ' - ' + - '' + '' )} end end @@ -372,8 +372,8 @@ class MyTemplate let(:_category_filter_options) { {checkboxes: true} } it { should equal_to_dom( ' - - + + ' )} @@ -522,9 +522,9 @@ class MyTemplate let(:_filter) { :column_names } let(:expected_html) do <Id - - + + + DOM end @@ -641,7 +641,7 @@ class MyTemplate end it "should generate label for filter" do expect(view.datagrid_label(:name)).to equal_to_dom( - '' + '' ) end it "should pass options through to the helper" do @@ -656,7 +656,7 @@ class MyTemplate end it "should support explicit label" do expect(view.datagrid_label(:name, "The Name")).to equal_to_dom( - '' + '' ) end end From bf68e7db36e38fe6dd049c4fb8a62a5d002a9f5a Mon Sep 17 00:00:00 2001 From: Bogdan Gusiev Date: Sun, 3 Nov 2024 16:01:36 +0100 Subject: [PATCH 006/157] Never override built-in generated html classes --- app/views/datagrid/_form.html.erb | 2 +- lib/datagrid/form_builder.rb | 15 +++++++++------ spec/datagrid/form_builder_spec.rb | 12 ++++++------ 3 files changed, 16 insertions(+), 13 deletions(-) diff --git a/app/views/datagrid/_form.html.erb b/app/views/datagrid/_form.html.erb index 7e175c1..b0132f5 100644 --- a/app/views/datagrid/_form.html.erb +++ b/app/views/datagrid/_form.html.erb @@ -1,4 +1,4 @@ -<%= form_for grid, options do |f| -%> +<%= form_for grid, **options do |f| -%> <% grid.filters.each do |filter| %>
<%= f.datagrid_label filter %> diff --git a/lib/datagrid/form_builder.rb b/lib/datagrid/form_builder.rb index 45f0fb2..bfdd80e 100644 --- a/lib/datagrid/form_builder.rb +++ b/lib/datagrid/form_builder.rb @@ -19,24 +19,28 @@ def datagrid_filter(filter_or_attribute, partials: nil, **options, &block) # @return [String] a form label tag for the corresponding filter name def datagrid_label(filter_or_attribute, text = nil, **options, &block) filter = datagrid_get_filter(filter_or_attribute) - label(filter.name, text || filter.header, class: filter.default_html_classes, **filter.label_options, **options, &block) + options = add_html_classes( + {**filter.label_options, **options}, + filter.default_html_classes + ) + label(filter.name, text || filter.header, **options, &block) end # @visibility private def datagrid_filter_input(attribute_or_filter, **options, &block) filter = datagrid_get_filter(attribute_or_filter) options = add_filter_options(filter, **options) - type = options[:type]&.to_sym - if options.has_key?(:value) && options[:value].nil? && [:"datetime-local", :"date"].include?(type) + type = options.delete(:type)&.to_sym + if options.has_key?(:value) && options[:value].nil? && [:"datetime-local", :date].include?(type) # https://github.com/rails/rails/pull/53387 options[:value] = "" end if type == :"datetime-local" datetime_local_field filter.name, **options, &block - elsif type == :"date" + elsif type == :date date_field filter.name, **options, &block elsif type == :textarea - text_area filter.name, value: object.filter_value_as_string(filter) , **options, type: nil, &block + text_area filter.name, value: object.filter_value_as_string(filter) , **options, &block elsif type == :checkbox # raise options.inspect check_box filter.name, options, options.fetch(:value, 1) @@ -53,7 +57,6 @@ def datagrid_filter_input(attribute_or_filter, **options, &block) }, multiple: filter.multiple?, **options, - type: nil, &block ) else diff --git a/spec/datagrid/form_builder_spec.rb b/spec/datagrid/form_builder_spec.rb index 1ca89a3..6aa5826 100644 --- a/spec/datagrid/form_builder_spec.rb +++ b/spec/datagrid/form_builder_spec.rb @@ -636,22 +636,22 @@ class MyTemplate end it "should generate label for filter" do expect(view.datagrid_label(:created_at)).to equal_to_dom( - '' + '' ) end it "should generate label for filter" do expect(view.datagrid_label(:name)).to equal_to_dom( - '' + '' ) end it "should pass options through to the helper" do - expect(view.datagrid_label(:name, :class => 'foo')).to equal_to_dom( - '' + expect(view.datagrid_label(:name, class: 'foo')).to equal_to_dom( + '' ) end it "should support block" do - expect(view.datagrid_label(:name, :class => 'foo') { 'The Name' }).to equal_to_dom( - '' + expect(view.datagrid_label(:name, class: 'foo') { 'The Name' }).to equal_to_dom( + '' ) end it "should support explicit label" do From 1f0b5a6f114c06b7c2993ac542c4e888c7aa4084 Mon Sep 17 00:00:00 2001 From: Bogdan Gusiev Date: Sun, 3 Nov 2024 19:30:01 +0100 Subject: [PATCH 007/157] Remove filter class from wrapping block --- app/views/datagrid/_form.html.erb | 2 +- spec/datagrid/helper_spec.rb | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/app/views/datagrid/_form.html.erb b/app/views/datagrid/_form.html.erb index b0132f5..911d163 100644 --- a/app/views/datagrid/_form.html.erb +++ b/app/views/datagrid/_form.html.erb @@ -1,6 +1,6 @@ <%= form_for grid, **options do |f| -%> <% grid.filters.each do |filter| %> -
+
<%= f.datagrid_label filter %> <%= f.datagrid_filter filter %>
diff --git a/spec/datagrid/helper_spec.rb b/spec/datagrid/helper_spec.rb index 1cd558c..2ec195f 100644 --- a/spec/datagrid/helper_spec.rb +++ b/spec/datagrid/helper_spec.rb @@ -483,8 +483,8 @@ class FormForGrid expect(subject.datagrid_form_for(object, url: "/grid")).to match_css_pattern( "form.datagrid-form.form_for_grid[action='/grid']" => 1, "form input[name=utf8]" => 1, - "form .filter label" => "Category", - "form .filter input.category.default_filter[name='form_for_grid[category]'][value=hello]" => 1, + "form .datagrid-filter label" => "Category", + "form .datagrid-filter input.category.default_filter[name='form_for_grid[category]'][value=hello]" => 1, "form input[name=commit][value=Search]" => 1, "form a.datagrid-reset[href='/location']" => 1 ) From e1ad783f2d3bf43d0a34fd209d591837b10c9722 Mon Sep 17 00:00:00 2001 From: Bogdan Gusiev Date: Sun, 3 Nov 2024 19:37:37 +0100 Subject: [PATCH 008/157] Rubocop install --- .rubocop.yml | 3 + .rubocop_todo.yml | 1021 +++++++++++++++++ Gemfile | 6 +- Rakefile | 22 +- datagrid.gemspec | 5 +- gemfiles/rails_6.1.gemfile | 2 +- gemfiles/rails_7.0.gemfile | 2 +- gemfiles/rails_7.1.gemfile | 2 +- gemfiles/rails_7.2.gemfile | 2 +- lib/datagrid.rb | 8 +- lib/datagrid/active_model.rb | 10 +- lib/datagrid/column_names_attribute.rb | 15 +- lib/datagrid/columns.rb | 43 +- lib/datagrid/columns/column.rb | 24 +- lib/datagrid/configuration.rb | 1 - lib/datagrid/core.rb | 44 +- lib/datagrid/drivers.rb | 1 - lib/datagrid/drivers/abstract_driver.rb | 22 +- lib/datagrid/drivers/active_record.rb | 28 +- lib/datagrid/drivers/array.rb | 10 +- lib/datagrid/drivers/mongo_mapper.rb | 23 +- lib/datagrid/drivers/mongoid.rb | 28 +- lib/datagrid/drivers/sequel.rb | 17 +- lib/datagrid/engine.rb | 5 +- lib/datagrid/filters.rb | 22 +- lib/datagrid/filters/base_filter.rb | 28 +- lib/datagrid/filters/boolean_filter.rb | 2 - lib/datagrid/filters/composite_filters.rb | 20 +- lib/datagrid/filters/date_filter.rb | 11 +- lib/datagrid/filters/date_time_filter.rb | 2 - lib/datagrid/filters/dynamic_filter.rb | 48 +- lib/datagrid/filters/enum_filter.rb | 11 +- .../filters/extended_boolean_filter.rb | 7 +- lib/datagrid/filters/float_filter.rb | 2 +- lib/datagrid/filters/integer_filter.rb | 5 +- lib/datagrid/filters/ranged_filter.rb | 18 +- lib/datagrid/filters/select_options.rb | 17 +- lib/datagrid/filters/string_filter.rb | 1 - lib/datagrid/form_builder.rb | 47 +- lib/datagrid/helper.rb | 7 +- lib/datagrid/ordering.rb | 46 +- lib/datagrid/renderer.rb | 41 +- lib/datagrid/rspec.rb | 14 +- lib/datagrid/scaffold.rb | 38 +- lib/datagrid/utils.rb | 42 +- lib/tasks/datagrid_tasks.rake | 1 - spec/datagrid/active_model_spec.rb | 8 +- spec/datagrid/column_names_attribute_spec.rb | 34 +- spec/datagrid/columns/column_spec.rb | 7 +- spec/datagrid/columns_spec.rb | 233 ++-- spec/datagrid/core_spec.rb | 79 +- spec/datagrid/drivers/active_record_spec.rb | 31 +- spec/datagrid/drivers/array_spec.rb | 66 +- spec/datagrid/drivers/mongo_mapper_spec.rb | 72 +- spec/datagrid/drivers/mongoid_spec.rb | 68 +- spec/datagrid/drivers/sequel_spec.rb | 73 +- spec/datagrid/filters/base_filter_spec.rb | 17 +- .../filters/composite_filters_spec.rb | 33 +- spec/datagrid/filters/date_filter_spec.rb | 58 +- .../datagrid/filters/date_time_filter_spec.rb | 56 +- spec/datagrid/filters/dynamic_filter_spec.rb | 127 +- spec/datagrid/filters/enum_filter_spec.rb | 35 +- .../filters/extended_boolean_filter_spec.rb | 16 +- spec/datagrid/filters/float_filter_spec.rb | 9 +- spec/datagrid/filters/integer_filter_spec.rb | 31 +- spec/datagrid/filters/string_filter_spec.rb | 39 +- spec/datagrid/filters_spec.rb | 137 +-- spec/datagrid/form_builder_spec.rb | 540 +++++---- spec/datagrid/helper_spec.rb | 213 ++-- spec/datagrid/ordering_spec.rb | 43 +- spec/datagrid/scaffold_spec.rb | 17 +- spec/datagrid/stylesheet_spec.rb | 4 +- spec/datagrid/utils_spec.rb | 4 +- spec/datagrid_spec.rb | 27 +- spec/spec_helper.rb | 87 +- spec/support/active_record.rb | 7 +- spec/support/configuration.rb | 37 +- spec/support/i18n_helpers.rb | 2 +- spec/support/matchers.rb | 17 +- spec/support/mongo_mapper.rb | 2 - spec/support/mongoid.rb | 7 +- spec/support/sequel.rb | 5 - spec/support/simple_report.rb | 23 +- 83 files changed, 2442 insertions(+), 1596 deletions(-) create mode 100644 .rubocop.yml create mode 100644 .rubocop_todo.yml diff --git a/.rubocop.yml b/.rubocop.yml new file mode 100644 index 0000000..e5ccac6 --- /dev/null +++ b/.rubocop.yml @@ -0,0 +1,3 @@ +# inherit_from: .rubocop_todo.yml +Style/StringLiterals: + EnforcedStyle: double_quotes diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml new file mode 100644 index 0000000..88da75f --- /dev/null +++ b/.rubocop_todo.yml @@ -0,0 +1,1021 @@ +# This configuration was generated by +# `rubocop --auto-gen-config` +# on 2024-11-03 18:32:09 UTC using RuboCop version 1.68.0. +# The point is for the user to remove these configuration records +# one by one as the offenses are removed from the code base. +# Note that changes in the inspected code, or installation of new +# versions of RuboCop, may require this file to be generated again. + +# Offense count: 6 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: TreatCommentsAsGroupSeparators, ConsiderPunctuation, Include. +# Include: **/*.gemfile, **/Gemfile, **/gems.rb +Bundler/OrderedGems: + Exclude: + - 'Gemfile' + - 'gemfiles/rails_6.1.gemfile' + - 'gemfiles/rails_7.0.gemfile' + - 'gemfiles/rails_7.1.gemfile' + - 'gemfiles/rails_7.2.gemfile' + +# Offense count: 3 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: EnforcedStyle, IndentationWidth. +# SupportedStyles: with_first_argument, with_fixed_indentation +Layout/ArgumentAlignment: + Exclude: + - 'lib/datagrid/filters.rb' + - 'lib/datagrid/form_builder.rb' + +# Offense count: 5 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: EnforcedStyleAlignWith. +# SupportedStylesAlignWith: either, start_of_block, start_of_line +Layout/BlockAlignment: + Exclude: + - 'spec/datagrid/drivers/mongo_mapper_spec.rb' + - 'spec/datagrid/filters/enum_filter_spec.rb' + +# Offense count: 35 +# This cop supports safe autocorrection (--autocorrect). +Layout/BlockEndNewline: + Exclude: + - 'spec/datagrid/form_builder_spec.rb' + - 'spec/datagrid/helper_spec.rb' + - 'spec/datagrid_spec.rb' + +# Offense count: 4 +# This cop supports safe autocorrection (--autocorrect). +Layout/ClosingHeredocIndentation: + Exclude: + - 'lib/datagrid/scaffold.rb' + - 'spec/datagrid/helper_spec.rb' + - 'spec/datagrid/scaffold_spec.rb' + +# Offense count: 40 +# This cop supports safe autocorrection (--autocorrect). +Layout/EmptyLineAfterGuardClause: + Exclude: + - 'lib/datagrid/columns.rb' + - 'lib/datagrid/columns/column.rb' + - 'lib/datagrid/drivers/active_record.rb' + - 'lib/datagrid/drivers/array.rb' + - 'lib/datagrid/drivers/mongo_mapper.rb' + - 'lib/datagrid/drivers/mongoid.rb' + - 'lib/datagrid/drivers/sequel.rb' + - 'lib/datagrid/filters.rb' + - 'lib/datagrid/filters/base_filter.rb' + - 'lib/datagrid/filters/dynamic_filter.rb' + - 'lib/datagrid/filters/enum_filter.rb' + - 'lib/datagrid/filters/float_filter.rb' + - 'lib/datagrid/filters/integer_filter.rb' + - 'lib/datagrid/ordering.rb' + - 'lib/datagrid/utils.rb' + +# Offense count: 1 +# This cop supports safe autocorrection (--autocorrect). +Layout/EmptyLineAfterMagicComment: + Exclude: + - 'spec/datagrid/form_builder_spec.rb' + +# Offense count: 14 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: EmptyLineBetweenMethodDefs, EmptyLineBetweenClassDefs, EmptyLineBetweenModuleDefs, DefLikeMacros, AllowAdjacentOneLineDefs, NumberOfEmptyLines. +Layout/EmptyLineBetweenDefs: + Exclude: + - 'lib/datagrid/columns.rb' + - 'lib/datagrid/columns/column.rb' + - 'lib/datagrid/core.rb' + - 'lib/datagrid/filters/date_filter.rb' + - 'lib/datagrid/helper.rb' + - 'lib/datagrid/ordering.rb' + - 'spec/datagrid/columns_spec.rb' + - 'spec/support/active_record.rb' + - 'spec/support/matchers.rb' + - 'spec/support/sequel.rb' + +# Offense count: 60 +# This cop supports safe autocorrection (--autocorrect). +Layout/EmptyLines: + Enabled: false + +# Offense count: 6 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: EnforcedStyle. +# SupportedStyles: around, only_before +Layout/EmptyLinesAroundAccessModifier: + Exclude: + - 'lib/datagrid/core.rb' + - 'lib/datagrid/drivers/abstract_driver.rb' + - 'lib/datagrid/form_builder.rb' + - 'lib/datagrid/renderer.rb' + - 'lib/datagrid/scaffold.rb' + - 'lib/datagrid/utils.rb' + +# Offense count: 2 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: AllowAliasSyntax, AllowedMethods. +# AllowedMethods: alias_method, public, protected, private +Layout/EmptyLinesAroundAttributeAccessor: + Exclude: + - 'spec/datagrid/columns_spec.rb' + - 'spec/datagrid/filters_spec.rb' + +# Offense count: 96 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: EnforcedStyle. +# SupportedStyles: empty_lines, no_empty_lines +Layout/EmptyLinesAroundBlockBody: + Enabled: false + +# Offense count: 37 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: EnforcedStyle. +# SupportedStyles: empty_lines, empty_lines_except_namespace, empty_lines_special, no_empty_lines, beginning_only, ending_only +Layout/EmptyLinesAroundClassBody: + Enabled: false + +# Offense count: 3 +# This cop supports safe autocorrection (--autocorrect). +Layout/EmptyLinesAroundMethodBody: + Exclude: + - 'lib/datagrid/columns/column.rb' + - 'lib/datagrid/filters/ranged_filter.rb' + - 'lib/datagrid/utils.rb' + +# Offense count: 16 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: EnforcedStyle. +# SupportedStyles: empty_lines, empty_lines_except_namespace, empty_lines_special, no_empty_lines +Layout/EmptyLinesAroundModuleBody: + Exclude: + - 'lib/datagrid.rb' + - 'lib/datagrid/columns.rb' + - 'lib/datagrid/configuration.rb' + - 'lib/datagrid/core.rb' + - 'lib/datagrid/filters.rb' + - 'lib/datagrid/filters/composite_filters.rb' + - 'lib/datagrid/filters/ranged_filter.rb' + - 'lib/datagrid/helper.rb' + - 'lib/datagrid/ordering.rb' + +# Offense count: 1 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: EnforcedStyleAlignWith, Severity. +# SupportedStylesAlignWith: keyword, variable, start_of_line +Layout/EndAlignment: + Exclude: + - 'spec/datagrid/drivers/mongo_mapper_spec.rb' + +# Offense count: 16 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: AllowForAlignment, AllowBeforeTrailingComments, ForceEqualSignAlignment. +Layout/ExtraSpacing: + Exclude: + - 'lib/datagrid/active_model.rb' + - 'lib/datagrid/columns.rb' + - 'lib/datagrid/drivers/active_record.rb' + - 'lib/datagrid/drivers/sequel.rb' + - 'lib/datagrid/filters/composite_filters.rb' + - 'lib/datagrid/ordering.rb' + - 'spec/datagrid/columns_spec.rb' + - 'spec/datagrid/filters/dynamic_filter_spec.rb' + - 'spec/datagrid/filters/enum_filter_spec.rb' + - 'spec/datagrid/ordering_spec.rb' + +# Offense count: 6 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: IndentationWidth. +# SupportedStyles: special_inside_parentheses, consistent, align_brackets +Layout/FirstArrayElementIndentation: + EnforcedStyle: consistent + +# Offense count: 16 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: IndentationWidth. +# SupportedStyles: special_inside_parentheses, consistent, align_braces +Layout/FirstHashElementIndentation: + EnforcedStyle: consistent + +# Offense count: 1 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: AllowMultipleStyles, EnforcedHashRocketStyle, EnforcedColonStyle, EnforcedLastArgumentHashStyle. +# SupportedHashRocketStyles: key, separator, table +# SupportedColonStyles: key, separator, table +# SupportedLastArgumentHashStyles: always_inspect, always_ignore, ignore_implicit, ignore_explicit +Layout/HashAlignment: + Exclude: + - 'spec/spec_helper.rb' + +# Offense count: 6 +# This cop supports safe autocorrection (--autocorrect). +Layout/HeredocIndentation: + Exclude: + - 'lib/datagrid/scaffold.rb' + - 'spec/datagrid/form_builder_spec.rb' + - 'spec/datagrid/helper_spec.rb' + +# Offense count: 4 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: EnforcedStyle. +# SupportedStyles: normal, indented_internal_methods +Layout/IndentationConsistency: + Exclude: + - 'spec/datagrid/columns_spec.rb' + +# Offense count: 5 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: Width, AllowedPatterns. +Layout/IndentationWidth: + Exclude: + - 'spec/datagrid/drivers/mongo_mapper_spec.rb' + - 'spec/datagrid/helper_spec.rb' + +# Offense count: 11 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: AllowDoxygenCommentStyle, AllowGemfileRubyComment, AllowRBSInlineAnnotation, AllowSteepAnnotation. +Layout/LeadingCommentSpace: + Exclude: + - 'lib/datagrid/drivers/mongo_mapper.rb' + - 'lib/datagrid/rspec.rb' + - 'spec/datagrid/filters/dynamic_filter_spec.rb' + - 'spec/spec_helper.rb' + - 'spec/support/active_record.rb' + - 'spec/support/mongoid.rb' + +# Offense count: 1 +# This cop supports safe autocorrection (--autocorrect). +Layout/LeadingEmptyLines: + Exclude: + - 'spec/support/simple_report.rb' + +# Offense count: 35 +# This cop supports safe autocorrection (--autocorrect). +Layout/MultilineBlockLayout: + Exclude: + - 'spec/datagrid/form_builder_spec.rb' + - 'spec/datagrid/helper_spec.rb' + - 'spec/datagrid_spec.rb' + +# Offense count: 1 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: EnforcedStyle, IndentationWidth. +# SupportedStyles: aligned, indented +Layout/MultilineOperationIndentation: + Exclude: + - 'lib/datagrid/filters/integer_filter.rb' + +# Offense count: 36 +# This cop supports safe autocorrection (--autocorrect). +Layout/SpaceAfterComma: + Exclude: + - 'lib/datagrid/columns.rb' + - 'spec/datagrid/drivers/array_spec.rb' + - 'spec/datagrid/drivers/sequel_spec.rb' + - 'spec/datagrid/filters/date_filter_spec.rb' + - 'spec/datagrid/filters/date_time_filter_spec.rb' + - 'spec/datagrid/filters/enum_filter_spec.rb' + - 'spec/datagrid/filters/integer_filter_spec.rb' + - 'spec/datagrid/filters_spec.rb' + - 'spec/datagrid/form_builder_spec.rb' + - 'spec/datagrid/helper_spec.rb' + +# Offense count: 5 +# This cop supports safe autocorrection (--autocorrect). +Layout/SpaceAfterNot: + Exclude: + - 'lib/datagrid/columns/column.rb' + - 'lib/datagrid/drivers/active_record.rb' + - 'lib/datagrid/drivers/mongoid.rb' + - 'lib/datagrid/drivers/sequel.rb' + +# Offense count: 14 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: AllowForAlignment, EnforcedStyleForExponentOperator, EnforcedStyleForRationalLiterals. +# SupportedStylesForExponentOperator: space, no_space +# SupportedStylesForRationalLiterals: space, no_space +Layout/SpaceAroundOperators: + Exclude: + - 'lib/datagrid/columns.rb' + - 'lib/datagrid/drivers/active_record.rb' + - 'lib/datagrid/drivers/mongo_mapper.rb' + - 'lib/datagrid/drivers/mongoid.rb' + - 'lib/datagrid/drivers/sequel.rb' + - 'spec/datagrid/drivers/array_spec.rb' + - 'spec/datagrid/drivers/mongo_mapper_spec.rb' + - 'spec/datagrid/drivers/mongoid_spec.rb' + - 'spec/datagrid/drivers/sequel_spec.rb' + - 'spec/datagrid/filters/date_time_filter_spec.rb' + - 'spec/datagrid/filters/enum_filter_spec.rb' + - 'spec/datagrid/filters/integer_filter_spec.rb' + - 'spec/spec_helper.rb' + +# Offense count: 3 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: EnforcedStyle, EnforcedStyleForEmptyBraces. +# SupportedStyles: space, no_space +# SupportedStylesForEmptyBraces: space, no_space +Layout/SpaceBeforeBlockBraces: + Exclude: + - 'lib/datagrid/filters.rb' + - 'spec/datagrid/filters/dynamic_filter_spec.rb' + - 'spec/datagrid/ordering_spec.rb' + +# Offense count: 5 +# This cop supports safe autocorrection (--autocorrect). +Layout/SpaceBeforeComma: + Exclude: + - 'lib/datagrid/drivers/mongoid.rb' + - 'lib/datagrid/filters.rb' + - 'lib/datagrid/form_builder.rb' + +# Offense count: 5 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: AllowForAlignment. +Layout/SpaceBeforeFirstArg: + Exclude: + - 'lib/datagrid/active_model.rb' + - 'lib/datagrid/columns.rb' + - 'lib/datagrid/filters/composite_filters.rb' + - 'lib/datagrid/ordering.rb' + - 'spec/datagrid/columns_spec.rb' + +# Offense count: 16 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: EnforcedStyle, EnforcedStyleForEmptyBrackets. +# SupportedStyles: space, no_space, compact +# SupportedStylesForEmptyBrackets: space, no_space +Layout/SpaceInsideArrayLiteralBrackets: + Exclude: + - 'lib/datagrid/drivers/mongoid.rb' + - 'lib/datagrid/filters/base_filter.rb' + - 'spec/datagrid/column_names_attribute_spec.rb' + - 'spec/datagrid/drivers/array_spec.rb' + - 'spec/datagrid/drivers/mongo_mapper_spec.rb' + - 'spec/datagrid/drivers/mongoid_spec.rb' + - 'spec/datagrid/drivers/sequel_spec.rb' + +# Offense count: 425 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: EnforcedStyle, EnforcedStyleForEmptyBraces, SpaceBeforeBlockParameters. +# SupportedStyles: space, no_space +# SupportedStylesForEmptyBraces: space, no_space +Layout/SpaceInsideBlockBraces: + Enabled: false + +# Offense count: 162 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: EnforcedStyle, EnforcedStyleForEmptyBraces. +# SupportedStyles: space, no_space, compact +# SupportedStylesForEmptyBraces: space, no_space +Layout/SpaceInsideHashLiteralBraces: + Enabled: false + +# Offense count: 18 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: EnforcedStyle. +# SupportedStyles: space, compact, no_space +Layout/SpaceInsideParens: + Exclude: + - 'lib/datagrid/form_builder.rb' + - 'lib/datagrid/ordering.rb' + - 'spec/datagrid/filters/enum_filter_spec.rb' + - 'spec/datagrid/filters/integer_filter_spec.rb' + - 'spec/datagrid/filters/string_filter_spec.rb' + - 'spec/datagrid/filters_spec.rb' + - 'spec/datagrid/form_builder_spec.rb' + - 'spec/datagrid/helper_spec.rb' + +# Offense count: 15 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: EnforcedStyle. +# SupportedStyles: final_newline, final_blank_line +Layout/TrailingEmptyLines: + Exclude: + - 'Rakefile' + - 'datagrid.gemspec' + - 'lib/datagrid.rb' + - 'lib/datagrid/column_names_attribute.rb' + - 'lib/datagrid/drivers/mongoid.rb' + - 'lib/datagrid/filters/base_filter.rb' + - 'lib/datagrid/filters/date_filter.rb' + - 'lib/datagrid/filters/date_time_filter.rb' + - 'lib/datagrid/filters/integer_filter.rb' + - 'lib/datagrid/helper.rb' + - 'spec/datagrid/helper_spec.rb' + - 'spec/support/configuration.rb' + - 'spec/support/mongoid.rb' + - 'spec/support/sequel.rb' + - 'spec/support/simple_report.rb' + +# Offense count: 4 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: AllowInHeredoc. +Layout/TrailingWhitespace: + Exclude: + - 'spec/datagrid/columns/column_spec.rb' + - 'spec/datagrid/filters/base_filter_spec.rb' + - 'spec/datagrid/filters/float_filter_spec.rb' + - 'spec/datagrid/utils_spec.rb' + +# Offense count: 4 +# This cop supports unsafe autocorrection (--autocorrect-all). +# Configuration parameters: AllowSafeAssignment. +Lint/AssignmentInCondition: + Exclude: + - 'lib/datagrid/columns/column.rb' + - 'lib/datagrid/filters/base_filter.rb' + - 'lib/datagrid/form_builder.rb' + - 'lib/datagrid/renderer.rb' + +# Offense count: 31 +# Configuration parameters: AllowedMethods. +# AllowedMethods: enums +Lint/ConstantDefinitionInBlock: + Exclude: + - 'spec/datagrid/active_model_spec.rb' + - 'spec/datagrid/columns/column_spec.rb' + - 'spec/datagrid/columns_spec.rb' + - 'spec/datagrid/core_spec.rb' + - 'spec/datagrid/drivers/array_spec.rb' + - 'spec/datagrid/drivers/sequel_spec.rb' + - 'spec/datagrid/filters/enum_filter_spec.rb' + - 'spec/datagrid/filters_spec.rb' + - 'spec/datagrid/helper_spec.rb' + - 'spec/datagrid/ordering_spec.rb' + - 'spec/support/active_record.rb' + +# Offense count: 1 +# This cop supports unsafe autocorrection (--autocorrect-all). +Lint/NonDeterministicRequireOrder: + Exclude: + - 'spec/spec_helper.rb' + +# Offense count: 1 +# This cop supports safe autocorrection (--autocorrect). +Lint/RedundantStringCoercion: + Exclude: + - 'lib/datagrid/form_builder.rb' + +# Offense count: 6 +# Configuration parameters: AllowComments, AllowNil. +Lint/SuppressedException: + Exclude: + - 'lib/datagrid/active_model.rb' + - 'lib/datagrid/utils.rb' + - 'spec/spec_helper.rb' + +# Offense count: 8 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: AutoCorrect, IgnoreEmptyBlocks, AllowUnusedKeywordArguments. +Lint/UnusedBlockArgument: + Exclude: + - 'lib/datagrid/filters/extended_boolean_filter.rb' + - 'spec/datagrid/columns_spec.rb' + - 'spec/datagrid/drivers/active_record_spec.rb' + - 'spec/datagrid/form_builder_spec.rb' + - 'spec/datagrid/helper_spec.rb' + - 'spec/datagrid/ordering_spec.rb' + +# Offense count: 20 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: AutoCorrect, AllowUnusedKeywordArguments, IgnoreEmptyMethods, IgnoreNotImplementedMethods. +Lint/UnusedMethodArgument: + Exclude: + - 'lib/datagrid/columns.rb' + - 'lib/datagrid/drivers/array.rb' + - 'lib/datagrid/drivers/mongo_mapper.rb' + - 'lib/datagrid/drivers/mongoid.rb' + - 'lib/datagrid/filters/base_filter.rb' + - 'lib/datagrid/filters/composite_filters.rb' + - 'lib/datagrid/form_builder.rb' + - 'spec/support/i18n_helpers.rb' + +# Offense count: 3 +# This cop supports unsafe autocorrection (--autocorrect-all). +# Configuration parameters: AutoCorrect. +Lint/UselessMethodDefinition: + Exclude: + - 'lib/datagrid/core.rb' + - 'lib/datagrid/drivers/sequel.rb' + +# Offense count: 1 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: AutoCorrect, CheckForMethodsWithNoSideEffects. +Lint/Void: + Exclude: + - 'spec/support/matchers.rb' + +# Offense count: 14 +# Configuration parameters: AllowedMethods, AllowedPatterns, CountRepeatedAttributes. +Metrics/AbcSize: + Max: 39 + +# Offense count: 64 +# Configuration parameters: CountComments, CountAsOne, AllowedMethods, AllowedPatterns. +# AllowedMethods: refine +Metrics/BlockLength: + Max: 606 + +# Offense count: 5 +# Configuration parameters: CountComments, CountAsOne. +Metrics/ClassLength: + Max: 146 + +# Offense count: 10 +# Configuration parameters: AllowedMethods, AllowedPatterns. +Metrics/CyclomaticComplexity: + Max: 14 + +# Offense count: 32 +# Configuration parameters: CountComments, CountAsOne, AllowedMethods, AllowedPatterns. +Metrics/MethodLength: + Max: 34 + +# Offense count: 3 +# Configuration parameters: CountComments, CountAsOne. +Metrics/ModuleLength: + Max: 193 + +# Offense count: 10 +# Configuration parameters: AllowedMethods, AllowedPatterns. +Metrics/PerceivedComplexity: + Max: 14 + +# Offense count: 9 +# Configuration parameters: NamePrefix, ForbiddenPrefixes, AllowedMethods, MethodDefinitionMacros. +# NamePrefix: is_, has_, have_ +# ForbiddenPrefixes: is_, has_, have_ +# AllowedMethods: is_a? +# MethodDefinitionMacros: define_method, define_singleton_method +Naming/PredicateName: + Exclude: + - 'spec/**/*' + - 'lib/datagrid/drivers/abstract_driver.rb' + - 'lib/datagrid/drivers/active_record.rb' + - 'lib/datagrid/drivers/array.rb' + - 'lib/datagrid/drivers/mongo_mapper.rb' + - 'lib/datagrid/drivers/mongoid.rb' + - 'lib/datagrid/drivers/sequel.rb' + +# Offense count: 1 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: EnforcedStyle. +# SupportedStyles: prefer_alias, prefer_alias_method +Style/Alias: + Exclude: + - 'lib/datagrid/ordering.rb' + +# Offense count: 1 +# This cop supports unsafe autocorrection (--autocorrect-all). +# Configuration parameters: EnforcedStyle. +# SupportedStyles: always, conditionals +Style/AndOr: + Exclude: + - 'spec/support/matchers.rb' + +# Offense count: 28 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: EnforcedStyle, ProceduralMethods, FunctionalMethods, AllowedMethods, AllowedPatterns, AllowBracesOnProceduralOneLiners, BracesRequiredMethods. +# SupportedStyles: line_count_based, semantic, braces_for_chaining, always_braces +# ProceduralMethods: benchmark, bm, bmbm, create, each_with_object, measure, new, realtime, tap, with_object +# FunctionalMethods: let, let!, subject, watch +# AllowedMethods: lambda, proc, it +Style/BlockDelimiters: + Exclude: + - 'spec/datagrid/columns_spec.rb' + - 'spec/datagrid/core_spec.rb' + - 'spec/datagrid/drivers/mongo_mapper_spec.rb' + - 'spec/datagrid/drivers/mongoid_spec.rb' + - 'spec/datagrid/drivers/sequel_spec.rb' + - 'spec/datagrid/filters/dynamic_filter_spec.rb' + - 'spec/datagrid/filters_spec.rb' + - 'spec/datagrid/form_builder_spec.rb' + - 'spec/datagrid/helper_spec.rb' + - 'spec/datagrid/ordering_spec.rb' + - 'spec/datagrid_spec.rb' + +# Offense count: 3 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: AllowOnConstant, AllowOnSelfClass. +Style/CaseEquality: + Exclude: + - 'lib/datagrid/filters/select_options.rb' + +# Offense count: 2 +# This cop supports unsafe autocorrection (--autocorrect-all). +# Configuration parameters: MinBranchesCount. +Style/CaseLikeIf: + Exclude: + - 'lib/datagrid/form_builder.rb' + - 'spec/support/matchers.rb' + +# Offense count: 16 +# This cop supports unsafe autocorrection (--autocorrect-all). +# Configuration parameters: EnforcedStyle. +# SupportedStyles: nested, compact +Style/ClassAndModuleChildren: + Exclude: + - 'lib/datagrid/columns/column.rb' + - 'lib/datagrid/filters/base_filter.rb' + - 'lib/datagrid/filters/boolean_filter.rb' + - 'lib/datagrid/filters/date_filter.rb' + - 'lib/datagrid/filters/date_time_filter.rb' + - 'lib/datagrid/filters/default_filter.rb' + - 'lib/datagrid/filters/dynamic_filter.rb' + - 'lib/datagrid/filters/enum_filter.rb' + - 'lib/datagrid/filters/extended_boolean_filter.rb' + - 'lib/datagrid/filters/float_filter.rb' + - 'lib/datagrid/filters/integer_filter.rb' + - 'lib/datagrid/filters/ranged_filter.rb' + - 'lib/datagrid/filters/select_options.rb' + - 'lib/datagrid/filters/string_filter.rb' + - 'lib/datagrid/scaffold.rb' + +# Offense count: 2 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: Keywords, RequireColon. +# Keywords: TODO, FIXME, OPTIMIZE, HACK, REVIEW, NOTE +Style/CommentAnnotation: + Exclude: + - 'lib/datagrid/drivers/mongo_mapper.rb' + - 'spec/spec_helper.rb' + +# Offense count: 25 +# Configuration parameters: AllowedConstants. +Style/Documentation: + Enabled: false + +# Offense count: 1 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: AutoCorrect, EnforcedStyle, AllowComments. +# SupportedStyles: empty, nil, both +Style/EmptyElse: + Exclude: + - 'lib/datagrid/ordering.rb' + +# Offense count: 1 +# This cop supports safe autocorrection (--autocorrect). +Style/EmptyLiteral: + Exclude: + - 'spec/datagrid/drivers/array_spec.rb' + +# Offense count: 2 +# This cop supports safe autocorrection (--autocorrect). +Style/Encoding: + Exclude: + - 'Rakefile' + - 'spec/datagrid/form_builder_spec.rb' + +# Offense count: 3 +# This cop supports safe autocorrection (--autocorrect). +Style/ExpandPathArguments: + Exclude: + - 'lib/datagrid.rb' + - 'spec/spec_helper.rb' + +# Offense count: 2 +# This cop supports safe autocorrection (--autocorrect). +Style/ExplicitBlockArgument: + Exclude: + - 'lib/datagrid/drivers/mongo_mapper.rb' + - 'lib/datagrid/drivers/mongoid.rb' + +# Offense count: 82 +# This cop supports unsafe autocorrection (--autocorrect-all). +# Configuration parameters: EnforcedStyle. +# SupportedStyles: always, always_true, never +Style/FrozenStringLiteralComment: + Enabled: false + +# Offense count: 3 +# Configuration parameters: AllowedVariables. +Style/GlobalVars: + Exclude: + - 'spec/datagrid/filters_spec.rb' + +# Offense count: 9 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: MinBodyLength, AllowConsecutiveConditionals. +Style/GuardClause: + Exclude: + - 'lib/datagrid/core.rb' + - 'lib/datagrid/drivers/abstract_driver.rb' + - 'lib/datagrid/filters/dynamic_filter.rb' + - 'lib/datagrid/filters/ranged_filter.rb' + - 'lib/datagrid/filters/select_options.rb' + - 'lib/datagrid/form_builder.rb' + - 'lib/datagrid/ordering.rb' + - 'spec/support/matchers.rb' + +# Offense count: 1 +# This cop supports unsafe autocorrection (--autocorrect-all). +# Configuration parameters: AllowedReceivers. +# AllowedReceivers: Thread.current +Style/HashEachMethods: + Exclude: + - 'spec/datagrid/form_builder_spec.rb' + +# Offense count: 226 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: EnforcedStyle, EnforcedShorthandSyntax, UseHashRocketsWithSymbolValues, PreferHashRocketsForNonAlnumEndingSymbols. +# SupportedStyles: ruby19, hash_rockets, no_mixed_keys, ruby19_no_mixed_keys +# SupportedShorthandSyntax: always, never, either, consistent, either_consistent +Style/HashSyntax: + Enabled: false + +# Offense count: 2 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: AllowIfModifier. +Style/IfInsideElse: + Exclude: + - 'lib/datagrid/column_names_attribute.rb' + - 'lib/datagrid/ordering.rb' + +# Offense count: 45 +# This cop supports safe autocorrection (--autocorrect). +Style/IfUnlessModifier: + Enabled: false + +# Offense count: 6 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: EnforcedStyle. +# SupportedStyles: line_count_dependent, lambda, literal +Style/Lambda: + Exclude: + - 'spec/datagrid/helper_spec.rb' + - 'spec/support/simple_report.rb' + +# Offense count: 20 +# This cop supports unsafe autocorrection (--autocorrect-all). +Style/LineEndConcatenation: + Exclude: + - 'spec/datagrid/form_builder_spec.rb' + +# Offense count: 1 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: AllowedMethods, AllowedPatterns. +Style/MethodCallWithoutArgsParentheses: + Exclude: + - 'spec/datagrid/form_builder_spec.rb' + +# Offense count: 2 +Style/MissingRespondToMissing: + Exclude: + - 'lib/datagrid/columns.rb' + - 'lib/datagrid/renderer.rb' + +# Offense count: 2 +# This cop supports safe autocorrection (--autocorrect). +Style/MultilineTernaryOperator: + Exclude: + - 'lib/datagrid/drivers/active_record.rb' + - 'lib/datagrid/filters/select_options.rb' + +# Offense count: 14 +# This cop supports unsafe autocorrection (--autocorrect-all). +# Configuration parameters: EnforcedStyle. +# SupportedStyles: literals, strict +Style/MutableConstant: + Exclude: + - 'lib/datagrid/drivers/abstract_driver.rb' + - 'lib/datagrid/filters.rb' + - 'lib/datagrid/filters/dynamic_filter.rb' + - 'lib/datagrid/filters/extended_boolean_filter.rb' + - 'lib/datagrid/utils.rb' + - 'lib/datagrid/version.rb' + +# Offense count: 2 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: EnforcedStyle. +# SupportedStyles: both, prefix, postfix +Style/NegatedIf: + Exclude: + - 'spec/support/matchers.rb' + +# Offense count: 1 +# This cop supports safe autocorrection (--autocorrect). +Style/NestedTernaryOperator: + Exclude: + - 'lib/datagrid/helper.rb' + +# Offense count: 20 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: EnforcedOctalStyle. +# SupportedOctalStyles: zero_with_o, zero_only +Style/NumericLiteralPrefix: + Exclude: + - 'spec/datagrid/filters/date_filter_spec.rb' + - 'spec/datagrid/filters/date_time_filter_spec.rb' + +# Offense count: 1 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: Strict, AllowedNumbers, AllowedPatterns. +Style/NumericLiterals: + MinDigits: 6 + +# Offense count: 4 +# This cop supports unsafe autocorrection (--autocorrect-all). +# Configuration parameters: EnforcedStyle, AllowedMethods, AllowedPatterns. +# SupportedStyles: predicate, comparison +Style/NumericPredicate: + Exclude: + - 'spec/**/*' + - 'lib/datagrid/columns.rb' + - 'lib/datagrid/utils.rb' + +# Offense count: 1 +# This cop supports safe autocorrection (--autocorrect). +Style/ParallelAssignment: + Exclude: + - 'lib/datagrid/utils.rb' + +# Offense count: 6 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: PreferredDelimiters. +Style/PercentLiteralDelimiters: + Exclude: + - 'lib/datagrid/filters/dynamic_filter.rb' + - 'spec/datagrid/columns_spec.rb' + - 'spec/datagrid/form_builder_spec.rb' + +# Offense count: 7 +# This cop supports unsafe autocorrection (--autocorrect-all). +# Configuration parameters: EnforcedStyle. +# SupportedStyles: short, verbose +Style/PreferredHashMethods: + Exclude: + - 'lib/datagrid/columns/column.rb' + - 'lib/datagrid/filters/base_filter.rb' + - 'lib/datagrid/filters/dynamic_filter.rb' + - 'lib/datagrid/filters/select_options.rb' + - 'lib/datagrid/form_builder.rb' + - 'lib/datagrid/renderer.rb' + +# Offense count: 4 +# This cop supports safe autocorrection (--autocorrect). +Style/RedundantBegin: + Exclude: + - 'lib/datagrid/utils.rb' + - 'spec/support/configuration.rb' + +# Offense count: 1 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: AllowMultipleReturnValues. +Style/RedundantReturn: + Exclude: + - 'lib/datagrid/drivers/mongoid.rb' + +# Offense count: 38 +# This cop supports safe autocorrection (--autocorrect). +Style/RedundantSelf: + Exclude: + - 'lib/datagrid/active_model.rb' + - 'lib/datagrid/columns.rb' + - 'lib/datagrid/columns/column.rb' + - 'lib/datagrid/core.rb' + - 'lib/datagrid/drivers/abstract_driver.rb' + - 'lib/datagrid/filters.rb' + - 'lib/datagrid/filters/base_filter.rb' + - 'lib/datagrid/filters/enum_filter.rb' + - 'lib/datagrid/filters/select_options.rb' + - 'lib/datagrid/form_builder.rb' + - 'lib/datagrid/ordering.rb' + - 'spec/datagrid/helper_spec.rb' + - 'spec/support/simple_report.rb' + +# Offense count: 2 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: EnforcedStyle, AllowInnerSlashes. +# SupportedStyles: slashes, percent_r, mixed +Style/RegexpLiteral: + Exclude: + - 'lib/datagrid/scaffold.rb' + +# Offense count: 4 +# This cop supports unsafe autocorrection (--autocorrect-all). +# Configuration parameters: ConvertCodeThatCanStartToReturnNil, AllowedMethods, MaxChainLength. +# AllowedMethods: present?, blank?, presence, try, try! +Style/SafeNavigation: + Exclude: + - 'lib/datagrid/column_names_attribute.rb' + - 'lib/datagrid/filters/base_filter.rb' + - 'lib/datagrid/filters/string_filter.rb' + - 'lib/datagrid/renderer.rb' + +# Offense count: 4 +# This cop supports safe autocorrection (--autocorrect). +Style/StderrPuts: + Exclude: + - 'Rakefile' + - 'spec/spec_helper.rb' + +# Offense count: 17 +# This cop supports unsafe autocorrection (--autocorrect-all). +# Configuration parameters: Mode. +Style/StringConcatenation: + Exclude: + - 'lib/datagrid/scaffold.rb' + - 'lib/tasks/datagrid_tasks.rake' + - 'spec/datagrid/form_builder_spec.rb' + +# Offense count: 1090 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: EnforcedStyle, ConsistentQuotesInMultiline. +# SupportedStyles: single_quotes, double_quotes +Style/StringLiterals: + Enabled: false + +# Offense count: 1 +# This cop supports unsafe autocorrection (--autocorrect-all). +Style/StructInheritance: + Exclude: + - 'spec/datagrid/drivers/array_spec.rb' + +# Offense count: 20 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: MinSize. +# SupportedStyles: percent, brackets +Style/SymbolArray: + EnforcedStyle: brackets + +# Offense count: 1 +# This cop supports safe autocorrection (--autocorrect). +Style/SymbolLiteral: + Exclude: + - 'spec/datagrid/columns_spec.rb' + +# Offense count: 6 +# This cop supports unsafe autocorrection (--autocorrect-all). +# Configuration parameters: AllowMethodsWithArguments, AllowedMethods, AllowedPatterns, AllowComments. +# AllowedMethods: define_method +Style/SymbolProc: + Exclude: + - 'lib/datagrid/column_names_attribute.rb' + - 'spec/datagrid/filters/enum_filter_spec.rb' + - 'spec/datagrid/helper_spec.rb' + - 'spec/support/simple_report.rb' + +# Offense count: 9 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: EnforcedStyleForMultiline. +# SupportedStylesForMultiline: comma, consistent_comma, no_comma +Style/TrailingCommaInArguments: + Exclude: + - 'lib/datagrid/column_names_attribute.rb' + - 'lib/datagrid/form_builder.rb' + - 'spec/datagrid/drivers/active_record_spec.rb' + - 'spec/datagrid/helper_spec.rb' + +# Offense count: 6 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: EnforcedStyleForMultiline. +# SupportedStylesForMultiline: comma, consistent_comma, no_comma +Style/TrailingCommaInArrayLiteral: + Exclude: + - 'datagrid.gemspec' + - 'lib/datagrid/drivers/mongoid.rb' + - 'lib/datagrid/filters/dynamic_filter.rb' + - 'spec/datagrid/drivers/array_spec.rb' + - 'spec/datagrid/helper_spec.rb' + - 'spec/spec_helper.rb' + +# Offense count: 6 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: EnforcedStyleForMultiline. +# SupportedStylesForMultiline: comma, consistent_comma, no_comma +Style/TrailingCommaInHashLiteral: + Exclude: + - 'datagrid.gemspec' + - 'lib/datagrid/drivers/mongoid.rb' + - 'lib/datagrid/form_builder.rb' + - 'lib/datagrid/scaffold.rb' + - 'spec/datagrid/filters_spec.rb' + +# Offense count: 31 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: EnforcedStyle, MinSize, WordRegex. +# SupportedStyles: percent, brackets +Style/WordArray: + Exclude: + - 'spec/datagrid/column_names_attribute_spec.rb' + - 'spec/datagrid/columns_spec.rb' + - 'spec/datagrid/core_spec.rb' + - 'spec/datagrid/drivers/array_spec.rb' + - 'spec/datagrid/drivers/mongo_mapper_spec.rb' + - 'spec/datagrid/drivers/mongoid_spec.rb' + - 'spec/datagrid/drivers/sequel_spec.rb' + - 'spec/datagrid/filters/date_filter_spec.rb' + - 'spec/datagrid/filters/extended_boolean_filter_spec.rb' + - 'spec/datagrid/filters/string_filter_spec.rb' + - 'spec/datagrid/filters_spec.rb' + - 'spec/datagrid/form_builder_spec.rb' + - 'spec/datagrid/helper_spec.rb' + - 'spec/support/simple_report.rb' + +# Offense count: 36 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: AllowHeredoc, AllowURI, URISchemes, IgnoreCopDirectives, AllowedPatterns. +# URISchemes: http, https +Layout/LineLength: + Max: 250 diff --git a/Gemfile b/Gemfile index cf03de9..909dbe7 100644 --- a/Gemfile +++ b/Gemfile @@ -3,13 +3,13 @@ source "https://rubygems.org" gemspec group :development do - gem "appraisal" gem "activerecord" + gem "appraisal" gem "bump" gem "csv" # removed from standard library in Ruby 3.4 + gem "debug" gem "nokogiri" # used to test html output gem "pry-byebug" - gem 'debug' gem "rails-dom-testing", "~> 2.2" gem "rspec" gem "sequel" @@ -20,3 +20,5 @@ group :development do gem "mongoid", "~> 9.0" end end + +gem "rubocop", "~> 1.68", group: :development diff --git a/Rakefile b/Rakefile index 7fd32b9..4de31ea 100644 --- a/Rakefile +++ b/Rakefile @@ -1,29 +1,27 @@ -# encoding: utf-8 # frozen_string_literal: true -require 'rubygems' -require 'bundler' +require "rubygems" +require "bundler" begin Bundler.setup(:default, :development) rescue Bundler::BundlerError => e - $stderr.puts e.message - $stderr.puts "Run `bundle install` to install missing gems" + warn e.message + warn "Run `bundle install` to install missing gems" exit e.status_code end -require 'rake' -require 'bundler/gem_tasks' +require "rake" +require "bundler/gem_tasks" -require 'rspec/core' -require 'rspec/core/rake_task' +require "rspec/core" +require "rspec/core/rake_task" RSpec::Core::RakeTask.new(:spec) do |spec| - spec.pattern = FileList['spec/**/*_spec.rb'] + spec.pattern = FileList["spec/**/*_spec.rb"] end RSpec::Core::RakeTask.new(:rcov) do |spec| - spec.pattern = 'spec/**/*_spec.rb' + spec.pattern = "spec/**/*_spec.rb" spec.rcov = true end task default: :spec - diff --git a/datagrid.gemspec b/datagrid.gemspec index 44299c9..662bdee 100644 --- a/datagrid.gemspec +++ b/datagrid.gemspec @@ -18,7 +18,7 @@ Gem::Specification.new do |s| "LICENSE.txt", "CHANGELOG.md", "Readme.markdown", - "datagrid.gemspec", + "datagrid.gemspec" ] s.files += `git ls-files | grep -E '^(app|lib|templates)'`.split("\n") s.homepage = "https://github.com/bogdan/datagrid" @@ -29,9 +29,8 @@ Gem::Specification.new do |s| "bug_tracker_uri" => "#{s.homepage}/issues", "documentation_uri" => "#{s.homepage}/wiki", "changelog_uri" => "#{s.homepage}/blob/master/CHANGELOG.md", - "source_code_uri" => s.homepage, + "source_code_uri" => s.homepage } s.add_dependency "railties", ">= 6.1" end - diff --git a/gemfiles/rails_6.1.gemfile b/gemfiles/rails_6.1.gemfile index d92e1f4..512aa8a 100644 --- a/gemfiles/rails_6.1.gemfile +++ b/gemfiles/rails_6.1.gemfile @@ -8,10 +8,10 @@ group :development do gem "csv" gem "nokogiri" gem "pry-byebug" + gem "rails", "~> 6.1.0" gem "rspec" gem "sequel" gem "sqlite3", "~> 1.7.0" - gem "rails", "~> 6.1.0" group :mongo do gem "bson" diff --git a/gemfiles/rails_7.0.gemfile b/gemfiles/rails_7.0.gemfile index 92a7e74..61566c8 100644 --- a/gemfiles/rails_7.0.gemfile +++ b/gemfiles/rails_7.0.gemfile @@ -8,10 +8,10 @@ group :development do gem "csv" gem "nokogiri" gem "pry-byebug" + gem "rails", "~> 7.0.0" gem "rspec" gem "sequel" gem "sqlite3", "~> 1.7.0" - gem "rails", "~> 7.0.0" group :mongo do gem "bson" diff --git a/gemfiles/rails_7.1.gemfile b/gemfiles/rails_7.1.gemfile index ab3907f..bdd7ff4 100644 --- a/gemfiles/rails_7.1.gemfile +++ b/gemfiles/rails_7.1.gemfile @@ -8,10 +8,10 @@ group :development do gem "csv" gem "nokogiri" gem "pry-byebug" + gem "rails", "~> 7.1.0" gem "rspec" gem "sequel" gem "sqlite3", "~> 1.7.0" - gem "rails", "~> 7.1.0" group :mongo do gem "bson" diff --git a/gemfiles/rails_7.2.gemfile b/gemfiles/rails_7.2.gemfile index d1385b0..753268c 100644 --- a/gemfiles/rails_7.2.gemfile +++ b/gemfiles/rails_7.2.gemfile @@ -8,10 +8,10 @@ group :development do gem "csv" gem "nokogiri" gem "pry-byebug" + gem "rails", "~> 7.2.0" gem "rspec" gem "sequel" gem "sqlite3", "~> 2.0.0" - gem "rails", "~> 7.2.0" group :mongo do gem "bson" diff --git a/lib/datagrid.rb b/lib/datagrid.rb index b8fb9aa..82abe93 100644 --- a/lib/datagrid.rb +++ b/lib/datagrid.rb @@ -3,7 +3,6 @@ require "datagrid/engine" module Datagrid - extend ActiveSupport::Autoload autoload :Core @@ -24,24 +23,19 @@ module Datagrid # @!visibility private def self.included(base) base.class_eval do - include ::Datagrid::Core include ::Datagrid::ActiveModel include ::Datagrid::Filters include ::Datagrid::Columns include ::Datagrid::ColumnNamesAttribute include ::Datagrid::Ordering - end end class ConfigurationError < StandardError; end class ArgumentError < ::ArgumentError; end class ColumnUnavailableError < StandardError; end - end require "datagrid/scaffold" -I18n.load_path << File.expand_path('../datagrid/locale/en.yml', __FILE__) - - +I18n.load_path << File.expand_path("datagrid/locale/en.yml", __dir__) diff --git a/lib/datagrid/active_model.rb b/lib/datagrid/active_model.rb index deb7184..5284711 100644 --- a/lib/datagrid/active_model.rb +++ b/lib/datagrid/active_model.rb @@ -3,15 +3,15 @@ module Datagrid module ActiveModel # @!visibility private def self.included(base) - base.extend ClassMethods + base.extend ClassMethods base.class_eval do begin - require 'active_model/naming' + require "active_model/naming" extend ::ActiveModel::Naming rescue LoadError end begin - require 'active_model/attributes_assignment' + require "active_model/attributes_assignment" extend ::ActiveModel::AttributesAssignment rescue LoadError end @@ -21,7 +21,7 @@ def self.included(base) module ClassMethods # @return [String] URL query parameter name of the grid class def param_name - self.to_s.underscore.tr('/', '_') + to_s.underscore.tr("/", "_") end end @@ -48,7 +48,7 @@ def to_model end def to_param - self.param_name + param_name end end end diff --git a/lib/datagrid/column_names_attribute.rb b/lib/datagrid/column_names_attribute.rb index ae1a344..c04027c 100644 --- a/lib/datagrid/column_names_attribute.rb +++ b/lib/datagrid/column_names_attribute.rb @@ -31,7 +31,7 @@ def column_names_filter(**options) select: :optional_columns_select, multiple: true, dummy: true, - **options, + **options ) end end @@ -45,7 +45,7 @@ def columns(*args, **options) # If no mandatory columns specified than all of them considered mandatory # @return [Array] def mandatory_columns - available_columns.select {|c| c.mandatory? } + available_columns.select { |c| c.mandatory? } end # Returns a list of enabled columns without mandatory: true option @@ -58,7 +58,7 @@ def optional_columns protected def optional_columns_select - optional_columns.map {|c| [c.header, c.name] } + optional_columns.map { |c| [c.header, c.name] } end def selected_column_names(*args) @@ -68,12 +68,10 @@ def selected_column_names(*args) column.is_a?(Datagrid::Columns::Column) ? column.name : column.to_sym end args + elsif column_names && column_names.any? + column_names + mandatory_columns.map(&:name) else - if column_names && column_names.any? - column_names + mandatory_columns.map(&:name) - else - columns_enabled_by_default.map(&:name) - end + columns_enabled_by_default.map(&:name) end end @@ -88,4 +86,3 @@ def columns_enabled_by_default end end end - diff --git a/lib/datagrid/columns.rb b/lib/datagrid/columns.rb index b8bba41..d2fd850 100644 --- a/lib/datagrid/columns.rb +++ b/lib/datagrid/columns.rb @@ -2,7 +2,6 @@ require "active_support/core_ext/class/attribute" module Datagrid - module Columns require "datagrid/columns/column" @@ -34,7 +33,7 @@ module Columns # @visibility private def self.included(base) - base.extend ClassMethods + base.extend ClassMethods base.class_eval do include Datagrid::Core @@ -47,7 +46,6 @@ def self.included(base) end module ClassMethods - # @param data [Boolean] if true returns only columns with data representation. Default: false. # @param html [Boolean] if true returns only columns with html columns. Default: false. # @param column_names [Array] list of column names if you want to limit data only to specified columns @@ -146,23 +144,25 @@ def decorate(model = nil, &block) end return self.decorator = block unless model return model unless decorator + presenter = ::Datagrid::Utils.apply_args(model, &decorator) - presenter = presenter.is_a?(Class) ? presenter.new(model) : presenter + presenter = presenter.is_a?(Class) ? presenter.new(model) : presenter block_given? ? yield(presenter) : presenter end # @!visibility private def inherited(child_class) super(child_class) - child_class.columns_array = self.columns_array.clone + child_class.columns_array = columns_array.clone end # @!visibility private def filter_columns(columns_array, *names, data: false, html: false) names.compact! - if names.size >= 1 && names.all? {|n| n.is_a?(Datagrid::Columns::Column) && n.grid_class == self.class} + if names.size >= 1 && names.all? { |n| n.is_a?(Datagrid::Columns::Column) && n.grid_class == self.class } return names end + names.map!(&:to_sym) columns_array.select do |column| (!data || column.data?) && @@ -186,13 +186,13 @@ def define_column(columns, name, query = nil, **options, &block) end # @!visibility private - def find_column_by_name(columns,name) + def find_column_by_name(columns, name) return name if name.is_a?(Datagrid::Columns::Column) + columns.find do |col| col.name.to_sym == name.to_sym end end - end # @!visibility private @@ -223,7 +223,7 @@ def row_for(asset, *column_names) # @return [Hash] A mapping where keys are column names and values are column values for the given asset def hash_for(asset) result = {} - self.data_columns.each do |column| + data_columns.each do |column| result[column.name] = data_value(column, asset) end result @@ -233,14 +233,14 @@ def hash_for(asset) # @return [Array>] with data for each row in datagrid assets without header def rows(*column_names) map_with_batches do |asset| - self.row_for(asset, *column_names) + row_for(asset, *column_names) end end # @param column_names [Array] list of column names if you want to limit data only to specified columns # @return [Array>] data for each row in datagrid assets with header. def data(*column_names) - self.rows(*column_names).unshift(self.header(*column_names)) + rows(*column_names).unshift(header(*column_names)) end # @return [Array<{Symbol => Object}>] an array of hashes representing the rows in the filtered datagrid relation @@ -273,7 +273,7 @@ def data_hash def to_csv(*column_names, **options) require "csv" CSV.generate( - headers: self.header(*column_names), + headers: header(*column_names), write_headers: true, **options ) do |csv| @@ -283,7 +283,6 @@ def to_csv(*column_names, **options) end end - # @param column_names [Array] # @return [Array] all columns selected in grid instance # @example @@ -302,13 +301,13 @@ def columns(*column_names, data: false, html: false) # @param column_names [Array] list of column names if you want to limit data only to specified columns # @return [Array] columns that can be represented in plain data(non-html) way def data_columns(*column_names, **options) - self.columns(*column_names, **options, data: true) + columns(*column_names, **options, data: true) end # @param column_names [Array] list of column names if you want to limit data only to specified columns # @return all columns that can be represented in HTML table def html_columns(*column_names, **options) - self.columns(*column_names, **options, html: true) + columns(*column_names, **options, html: true) end # Finds a column definition by name @@ -401,6 +400,7 @@ def data_value(column_name, asset) column = column_by_name(column_name) cache(column, asset, :data_value) do raise "no data value for #{column.name} column" unless column.data? + result = generic_value(column, asset) result.is_a?(Datagrid::Columns::Column::ResponseFormat) ? result.call_data : result end @@ -408,7 +408,7 @@ def data_value(column_name, asset) # @return [Object] a cell HTML value for given column name and asset and view context def html_value(column_name, context, asset) - column = column_by_name(column_name) + column = column_by_name(column_name) cache(column, asset, :html_value) do if column.html? && column.html_block value_from_html_block(context, asset, column) @@ -461,9 +461,8 @@ def cache(column, asset, type) return yield end key = cache_key(asset) - unless key - raise(Datagrid::CacheKeyError, "Datagrid Cache key is #{key.inspect} for #{asset.inspect}.") - end + raise(Datagrid::CacheKeyError, "Datagrid Cache key is #{key.inspect} for #{asset.inspect}.") unless key + @cache[column.name] ||= {} @cache[column.name][key] ||= {} @cache[column.name][key][type] ||= yield @@ -476,10 +475,10 @@ def cache_key(asset) driver.default_cache_key(asset) end rescue NotImplementedError - raise Datagrid::ConfigurationError, "#{self} is setup to use cache. But there was appropriate cache key found for #{asset.inspect}. Please set cached option to block with asset as argument and cache key as returning value to resolve the issue." + raise Datagrid::ConfigurationError, + "#{self} is setup to use cache. But there was appropriate cache key found for #{asset.inspect}. Please set cached option to block with asset as argument and cache key as returning value to resolve the issue." end - def map_with_batches(&block) result = [] each_with_batches do |asset| @@ -522,7 +521,7 @@ def initialize(grid, model) @model = model end - def method_missing(meth, *args, &blk) + def method_missing(meth, *_args) @grid.data_value(meth, @model) end end diff --git a/lib/datagrid/columns/column.rb b/lib/datagrid/columns/column.rb index 7236202..1d50c40 100644 --- a/lib/datagrid/columns/column.rb +++ b/lib/datagrid/columns/column.rb @@ -1,9 +1,7 @@ class Datagrid::Columns::Column - # Datagrid class holding an information of # how a column should be rendered in data/console/csv format and HTML format class ResponseFormat - attr_accessor :data_block, :html_block def initialize @@ -42,9 +40,7 @@ def initialize(grid_class, name, query, options = {}, &block) else self.data_block = block - if options[:html].is_a? Proc - self.html_block = options[:html] - end + self.html_block = options[:html] if options[:html].is_a? Proc end self.query = query end @@ -54,9 +50,8 @@ def data_value(model, grid) grid.data_value(name, model) end - def label - self.options[:label] + options[:label] end def header @@ -69,7 +64,7 @@ def header def order if options.has_key?(:order) && options[:order] != true - self.options[:order] + options[:order] else driver.default_order(grid_class.scope, name) end @@ -88,12 +83,13 @@ def order_by_value(model, grid) end def order_by_value? - !! options[:order_by_value] + !!options[:order_by_value] end def order_desc return nil unless order - self.options[:order_desc] + + options[:order_desc] end def html? @@ -101,11 +97,11 @@ def html? end def data? - self.data_block != nil + data_block != nil end def mandatory? - !! options[:mandatory] + !!options[:mandatory] end def mandatory_explicitly_set? @@ -128,15 +124,16 @@ def html_value(context, asset, grid) grid.html_value(name, context, asset) end - def generic_value(model, grid) grid.generic_value(self, model) end def append_preload(relation) return relation unless preload + if preload.respond_to?(:call) return relation unless preload + if preload.arity == 1 preload.call(relation) else @@ -155,7 +152,6 @@ def preload else preload end - end def driver diff --git a/lib/datagrid/configuration.rb b/lib/datagrid/configuration.rb index 0032c2b..65a1653 100644 --- a/lib/datagrid/configuration.rb +++ b/lib/datagrid/configuration.rb @@ -1,5 +1,4 @@ module Datagrid - def self.configuration @configuration ||= Configuration.new end diff --git a/lib/datagrid/core.rb b/lib/datagrid/core.rb index 4444aca..0f560a4 100644 --- a/lib/datagrid/core.rb +++ b/lib/datagrid/core.rb @@ -18,21 +18,20 @@ def self.included(base) end module ClassMethods - # @!visibility private def datagrid_attribute(name, &block) - unless datagrid_attributes.include?(name) - block ||= lambda do |value| - value - end - datagrid_attributes << name - define_method name do - instance_variable_get("@#{name}") - end + return if datagrid_attributes.include?(name) - define_method :"#{name}=" do |value| - instance_variable_set("@#{name}", instance_exec(value, &block)) - end + block ||= lambda do |value| + value + end + datagrid_attributes << name + define_method name do + instance_variable_get("@#{name}") + end + + define_method :"#{name}=" do |value| + instance_variable_set("@#{name}", instance_exec(value, &block)) end end @@ -117,9 +116,8 @@ def check_scope_defined!(message = nil) def inherited(child_class) super(child_class) - child_class.datagrid_attributes = self.datagrid_attributes.clone + child_class.datagrid_attributes = datagrid_attributes.clone end - end # @param [{String, Symbol => Object}, nil] attributes a hash of attributes to initialize the object @@ -128,21 +126,18 @@ def inherited(child_class) def initialize(attributes = nil, &block) super() - if attributes - self.attributes = attributes - end + self.attributes = attributes if attributes instance_eval(&dynamic_block) if dynamic_block - if block_given? - self.scope(&block) - end - end + return unless block_given? + scope(&block) + end # @return [Hash] grid attributes including filter values and ordering values def attributes result = {} - self.datagrid_attributes.each do |name| + datagrid_attributes.each do |name| result[name] = self[name] end result @@ -161,7 +156,7 @@ def attributes=(attributes) # @return [Object] Any datagrid attribute value def [](attribute) - self.public_send(attribute) + public_send(attribute) end # Assigns any datagrid attribute @@ -169,7 +164,7 @@ def [](attribute) # @param value [Object] Datagrid attribute value # @return [void] def []=(attribute, value) - self.public_send(:"#{attribute}=", value) + public_send(:"#{attribute}=", value) end # @return [Object] a scope relation (e.g ActiveRecord::Relation) with all applied filters @@ -270,6 +265,7 @@ def reset end protected + def sanitize_for_mass_assignment(attributes) forbidden_attributes_protection ? super(attributes) : attributes end diff --git a/lib/datagrid/drivers.rb b/lib/datagrid/drivers.rb index 6194337..3e72d3f 100644 --- a/lib/datagrid/drivers.rb +++ b/lib/datagrid/drivers.rb @@ -5,7 +5,6 @@ require "datagrid/drivers/mongo_mapper" require "datagrid/drivers/sequel" - module Datagrid # @!visibility private module Drivers diff --git a/lib/datagrid/drivers/abstract_driver.rb b/lib/datagrid/drivers/abstract_driver.rb index bf9d940..99530a8 100644 --- a/lib/datagrid/drivers/abstract_driver.rb +++ b/lib/datagrid/drivers/abstract_driver.rb @@ -2,18 +2,17 @@ module Datagrid module Drivers # @!visibility private class AbstractDriver - TIMESTAMP_CLASSES = [DateTime, Time, ActiveSupport::TimeWithZone] class_attribute :subclasses, default: [] def self.inherited(base) super(base) - self.subclasses << base + subclasses << base end def self.guess_driver(scope) - self.subclasses.find do |driver_class| + subclasses.find do |driver_class| driver_class.match?(scope) end || raise(Datagrid::ConfigurationError, "ORM Driver not found for scope: #{scope.inspect}.") end @@ -83,11 +82,9 @@ def batch_each(scope, batch_size, &block) end def append_column_queries(assets, columns) - if columns.present? - raise NotImplementedError - else - assets - end + raise NotImplementedError if columns.present? + + assets end def default_cache_key(asset) @@ -96,12 +93,8 @@ def default_cache_key(asset) def where_by_timestamp_gotcha(scope, name, value) value = Datagrid::Utils.format_date_as_timestamp(value) - if value.first - scope = greater_equal(scope, name, value.first) - end - if value.last - scope = less_equal(scope, name, value.last) - end + scope = greater_equal(scope, name, value.first) if value.first + scope = less_equal(scope, name, value.last) if value.last scope end @@ -114,6 +107,7 @@ def can_preload?(scope, association) end protected + def timestamp_class?(klass) TIMESTAMP_CLASSES.include?(klass) end diff --git a/lib/datagrid/drivers/active_record.rb b/lib/datagrid/drivers/active_record.rb index 25224e3..3135df8 100644 --- a/lib/datagrid/drivers/active_record.rb +++ b/lib/datagrid/drivers/active_record.rb @@ -2,9 +2,9 @@ module Datagrid module Drivers # @!visibility private class ActiveRecord < AbstractDriver - def self.match?(scope) return false unless defined?(::ActiveRecord) + if scope.is_a?(Class) scope.ancestors.include?(::ActiveRecord::Base) else @@ -14,6 +14,7 @@ def self.match?(scope) def to_scope(scope) return scope if scope.is_a?(::ActiveRecord::Relation) + # Model class or Active record association # ActiveRecord association class hides itself under an Array # We can only reveal it by checking if it respond to some specific @@ -32,7 +33,7 @@ def append_column_queries(assets, columns) if assets.select_values.empty? assets = assets.select(Arel.respond_to?(:star) ? assets.klass.arel_table[Arel.star] : "#{assets.quoted_table_name}.*") end - columns = columns.map {|c| "#{c.query} AS #{c.name}"} + columns = columns.map { |c| "#{c.query} AS #{c.name}" } assets = assets.select(*columns) end assets @@ -89,13 +90,14 @@ def contains(scope, field, value) def normalized_column_type(scope, field) return nil unless has_column?(scope, field) + builtin_type = scope.columns_hash[field.to_s].type { - [:string, :text, :time, :binary] => :string, - [:integer, :primary_key] => :integer, - [:float, :decimal] => :float, + %i[string text time binary] => :string, + %i[integer primary_key] => :integer, + %i[float decimal] => :float, [:date] => :date, - [:datetime, :timestamp] => :timestamp, + %i[datetime timestamp] => :timestamp, [:boolean] => :boolean }.each do |keys, value| return value if keys.include?(builtin_type) @@ -106,6 +108,7 @@ def batch_each(scope, batch_size, &block) if scope.limit_value raise Datagrid::ConfigurationError, "ActiveRecord can not use batches in combination with SQL limit" end + options = batch_size ? { batch_size: batch_size } : {} scope.find_each(**options, &block) end @@ -119,19 +122,22 @@ def default_preload(scope, value) end def can_preload?(scope, association) - !! scope.klass.reflect_on_association(association) + !!scope.klass.reflect_on_association(association) end protected def prefix_table_name(scope, field) - has_column?(scope, field) ? [scope.table_name, field].join(".") : field + has_column?(scope, field) ? [scope.table_name, field].join(".") : field end def contains_predicate - defined?(::ActiveRecord::ConnectionAdapters::PostgreSQLAdapter) && - ::ActiveRecord::Base.connection.is_a?(::ActiveRecord::ConnectionAdapters::PostgreSQLAdapter) ? - 'ilike' : 'like' + if defined?(::ActiveRecord::ConnectionAdapters::PostgreSQLAdapter) && + ::ActiveRecord::Base.connection.is_a?(::ActiveRecord::ConnectionAdapters::PostgreSQLAdapter) + "ilike" + else + "like" + end end end end diff --git a/lib/datagrid/drivers/array.rb b/lib/datagrid/drivers/array.rb index 99d320c..3d2da1d 100644 --- a/lib/datagrid/drivers/array.rb +++ b/lib/datagrid/drivers/array.rb @@ -2,7 +2,6 @@ module Datagrid module Drivers # @!visibility private class Array < AbstractDriver - def self.match?(scope) !Datagrid::Drivers::ActiveRecord.match?(scope) && ( scope.is_a?(::Array) || scope.is_a?(Enumerator) || @@ -23,6 +22,7 @@ def where(scope, attribute, value) def asc(scope, order) return scope unless order return scope if order.empty? + scope.sort_by do |object| get(object, order) end @@ -32,7 +32,7 @@ def desc(scope, order) asc(scope, order).reverse end - def default_order(scope, column_name) + def default_order(_scope, column_name) column_name end @@ -67,11 +67,11 @@ def contains(scope, field, value) end end - def column_names(scope) + def column_names(_scope) [] end - def batch_each(scope, batch_size, &block) + def batch_each(scope, _batch_size, &block) scope.each(&block) end @@ -79,7 +79,7 @@ def default_cache_key(asset) asset end - def can_preload?(scope, association) + def can_preload?(_scope, _association) false end diff --git a/lib/datagrid/drivers/mongo_mapper.rb b/lib/datagrid/drivers/mongo_mapper.rb index 6d7d55b..e36fa51 100644 --- a/lib/datagrid/drivers/mongo_mapper.rb +++ b/lib/datagrid/drivers/mongo_mapper.rb @@ -2,9 +2,9 @@ module Datagrid module Drivers # @!visibility private class MongoMapper < AbstractDriver - def self.match?(scope) return false unless defined?(::MongoMapper) + if scope.is_a?(Class) scope.ancestors.include?(::MongoMapper::Document) else @@ -33,27 +33,27 @@ def default_order(scope, column_name) end def greater_equal(scope, field, value) - scope.where(field => {"$gte" => value}) + scope.where(field => { "$gte" => value }) end def less_equal(scope, field, value) - scope.where(field => {"$lte" => value}) + scope.where(field => { "$lte" => value }) end def has_column?(scope, column_name) scope.key?(column_name) end - def is_timestamp?(scope, column_name) - #TODO implement the support + def is_timestamp?(_scope, _column_name) + # TODO: implement the support false end - def contains(scope, field, value) + def contains(_scope, field, value) scope(field => Regexp.compile(Regexp.escape(value))) end - def column_names(scope) + def column_names(_scope) [] # TODO: implement support end @@ -62,10 +62,9 @@ def batch_each(scope, batch_size, &block) loop do batch = scope.skip(current_page * batch_size).limit(batch_size).to_a return if batch.empty? - scope.skip(current_page * batch_size).limit(batch_size).each do |item| - yield(item) - end - current_page+=1 + + scope.skip(current_page * batch_size).limit(batch_size).each(&block) + current_page += 1 end end @@ -77,7 +76,7 @@ def default_preload(scope, value) raise NotImplementedError end - def can_preload?(scope, association) + def can_preload?(_scope, _association) false end end diff --git a/lib/datagrid/drivers/mongoid.rb b/lib/datagrid/drivers/mongoid.rb index 5bb30c2..c737ff4 100644 --- a/lib/datagrid/drivers/mongoid.rb +++ b/lib/datagrid/drivers/mongoid.rb @@ -2,9 +2,9 @@ module Datagrid module Drivers # @!visibility private class Mongoid < AbstractDriver - def self.match?(scope) return false unless defined?(::Mongoid) + if scope.is_a?(Class) scope.ancestors.include?(::Mongoid::Document) else @@ -21,9 +21,7 @@ def to_scope(scope) end def where(scope, attribute, value) - if value.is_a?(Range) - value = {"$gte" => value.first, "$lte" => value.last} - end + value = { "$gte" => value.first, "$lte" => value.last } if value.is_a?(Range) scope.where(attribute => value) end @@ -40,11 +38,11 @@ def default_order(scope, column_name) end def greater_equal(scope, field, value) - scope.where(field => {"$gte" => value}) + scope.where(field => { "$gte" => value }) end def less_equal(scope, field, value) - scope.where(field => {"$lte" => value}) + scope.where(field => { "$lte" => value }) end def has_column?(scope, column_name) @@ -62,8 +60,9 @@ def column_names(scope) def normalized_column_type(scope, field) type = to_scope(scope).klass.fields[field.to_s]&.type return nil unless type + { - [BigDecimal , String, Symbol, Range, Array, Hash, ] => :string, + [BigDecimal, String, Symbol, Range, Array, Hash] => :string, [::Mongoid::Boolean] => :boolean, [Date] => :date, @@ -72,11 +71,11 @@ def normalized_column_type(scope, field) [Float] => :float, - [Integer] => :integer, + [Integer] => :integer }.each do |keys, value| return value if keys.include?(type) end - return :string + :string end def batch_each(scope, batch_size, &block) @@ -84,10 +83,9 @@ def batch_each(scope, batch_size, &block) loop do batch = scope.skip(current_page * batch_size).limit(batch_size).to_a return if batch.empty? - scope.skip(current_page * batch_size).limit(batch_size).each do |item| - yield(item) - end - current_page+=1 + + scope.skip(current_page * batch_size).limit(batch_size).each(&block) + current_page += 1 end end @@ -100,10 +98,8 @@ def default_preload(scope, value) end def can_preload?(scope, association) - !! scope.klass.reflect_on_association(association) + !!scope.klass.reflect_on_association(association) end - end end end - diff --git a/lib/datagrid/drivers/sequel.rb b/lib/datagrid/drivers/sequel.rb index 4ca8716..ce603b8 100644 --- a/lib/datagrid/drivers/sequel.rb +++ b/lib/datagrid/drivers/sequel.rb @@ -2,9 +2,9 @@ module Datagrid module Drivers # @!visibility private class Sequel < AbstractDriver - def self.match?(scope) return false unless defined?(::Sequel) + if scope.is_a?(Class) scope.ancestors.include?(::Sequel::Model) else @@ -14,6 +14,7 @@ def self.match?(scope) def to_scope(scope) return scope if scope.is_a?(::Sequel::Dataset) + scope.where({}) end @@ -38,7 +39,7 @@ def reverse_order(scope) end def default_order(scope, column_name) - has_column?(scope, column_name) ? ::Sequel.lit(prefix_table_name(scope, column_name)) : nil + has_column?(scope, column_name) ? ::Sequel.lit(prefix_table_name(scope, column_name)) : nil end def greater_equal(scope, field, value) @@ -65,10 +66,11 @@ def contains(scope, field, value) def normalized_column_type(scope, field) type = column_type(scope, field) return nil unless type + { - [:string, :blob, :time] => :string, - [:integer, :primary_key] => :integer, - [:float, :decimal] => :float, + %i[string blob time] => :string, + %i[integer primary_key] => :integer, + %i[float decimal] => :float, [:date] => :date, [:datetime] => :timestamp, [:boolean] => :boolean @@ -96,14 +98,13 @@ def default_preload(scope, value) end def can_preload?(scope, association) - !! scope.model.association_reflection(association) + !!scope.model.association_reflection(association) end - protected def prefix_table_name(scope, field) - has_column?(scope, field) ? [to_scope(scope).row_proc.table_name, field].join(".") : field + has_column?(scope, field) ? [to_scope(scope).row_proc.table_name, field].join(".") : field end def column_type(scope, field) diff --git a/lib/datagrid/engine.rb b/lib/datagrid/engine.rb index 11ae96b..b37dd4e 100644 --- a/lib/datagrid/engine.rb +++ b/lib/datagrid/engine.rb @@ -1,6 +1,6 @@ require "rails/engine" -require 'datagrid/helper' -require 'datagrid/form_builder' +require "datagrid/helper" +require "datagrid/form_builder" module Datagrid # @!private @@ -15,6 +15,5 @@ def self.extend_modules Engine.extend_modules end end - end end diff --git a/lib/datagrid/filters.rb b/lib/datagrid/filters.rb index a453f1b..3283c81 100644 --- a/lib/datagrid/filters.rb +++ b/lib/datagrid/filters.rb @@ -2,7 +2,6 @@ module Datagrid module Filters - require "datagrid/filters/base_filter" require "datagrid/filters/enum_filter" require "datagrid/filters/extended_boolean_filter" @@ -22,8 +21,8 @@ module Filters datetime: Filters::DateTimeFilter, string: Filters::StringFilter, default: Filters::DefaultFilter, - xboolean: Filters::ExtendedBooleanFilter , - boolean: Filters::BooleanFilter , + xboolean: Filters::ExtendedBooleanFilter, + boolean: Filters::BooleanFilter, integer: Filters::IntegerFilter, enum: Filters::EnumFilter, float: Filters::FloatFilter, @@ -37,25 +36,23 @@ module Filters def self.included(base) base.extend ClassMethods base.class_eval do - include Datagrid::Core include Datagrid::Filters::CompositeFilters class_attribute :filters_array, default: [] - end end module ClassMethods - # @return [Datagrid::Filters::BaseFilter, nil] filter definition object by name def filter_by_name(attribute) if attribute.is_a?(Datagrid::Filters::BaseFilter) unless ancestors.include?(attribute.grid_class) raise ArgumentError, "#{attribute.grid_class}##{attribute.name} filter doen't belong to #{self.class}" end + return attribute end - self.filters.find do |filter| + filters.find do |filter| filter.name == attribute.to_sym end end @@ -129,11 +126,12 @@ def filters def inherited(child_class) super(child_class) - child_class.filters_array = self.filters_array.clone + child_class.filters_array = filters_array.clone end def filters_inspection return "no filters" if filters.empty? + filters.map do |filter| "#{filter.name}: #{filter.type}" end.join(", ") @@ -143,7 +141,7 @@ def filters_inspection # @!visibility private def initialize(*args, &block) self.filters_array = self.class.filters_array.clone - self.filters_array.each do |filter| + filters_array.each do |filter| self[filter.name] = filter.default(self) end super(*args, &block) @@ -164,7 +162,7 @@ def filter_value_as_string(name) filter = filter_by_name(name) value = filter_value(filter) if value.is_a?(Array) - value.map {|v| filter.format(v) }.join(filter.separator) + value.map { |v| filter.format(v) }.join(filter.separator) else filter.format(value) end @@ -177,7 +175,7 @@ def filter_by_name(name) # @return [Array] assets filtered only by specified filters def filter_by(*filters) - apply_filters(scope, filters.map{|f| filter_by_name(f)}) + apply_filters(scope, filters.map { |f| filter_by_name(f) }) end # @return [Array] the select options for the filter @@ -215,7 +213,7 @@ def find_select_filter(filter) filter = filter_by_name(filter) unless filter.class.included_modules.include?(::Datagrid::Filters::SelectOptions) raise ::Datagrid::ArgumentError, - "#{self.class.name}##{filter.name} with type #{FILTER_TYPES.invert[filter.class].inspect} can not have select options" + "#{self.class.name}##{filter.name} with type #{FILTER_TYPES.invert[filter.class].inspect} can not have select options" end filter end diff --git a/lib/datagrid/filters/base_filter.rb b/lib/datagrid/filters/base_filter.rb index 710d244..608e8d9 100644 --- a/lib/datagrid/filters/base_filter.rb +++ b/lib/datagrid/filters/base_filter.rb @@ -5,7 +5,6 @@ class Datagrid::FilteringError < StandardError # @!visibility private class Datagrid::Filters::BaseFilter - class_attribute :input_helper_name, instance_writer: false attr_accessor :grid_class, :options, :block, :name @@ -30,11 +29,11 @@ def apply(grid_object, scope, value) result = execute(value, scope, grid_object) return scope unless result - if result == Datagrid::Filters::DEFAULT_FILTER_BLOCK - result = default_filter(value, scope, grid_object) - end + + result = default_filter(value, scope, grid_object) if result == Datagrid::Filters::DEFAULT_FILTER_BLOCK unless grid_object.driver.match?(result) - raise Datagrid::FilteringError, "Can not apply #{name.inspect} filter: result #{result.inspect} no longer match #{grid_object.driver.class}." + raise Datagrid::FilteringError, + "Can not apply #{name.inspect} filter: result #{result.inspect} no longer match #{grid_object.driver.class}." end result @@ -43,6 +42,7 @@ def apply(grid_object, scope, value) def parse_values(value) if multiple? return nil if value.nil? + normalize_multiple_value(value).map do |v| parse(v) end @@ -66,7 +66,7 @@ def header end def default(object) - default = self.options[:default] + default = options[:default] if default.is_a?(Symbol) object.send(default) elsif default.respond_to?(:call) @@ -77,7 +77,7 @@ def default(object) end def multiple? - self.options[:multiple] + options[:multiple] end def allow_nil? @@ -101,7 +101,7 @@ def form_builder_helper_name end def self.form_builder_helper_name - :"datagrid_#{self.to_s.demodulize.underscore}" + :"datagrid_#{to_s.demodulize.underscore}" end def default_filter_block @@ -125,9 +125,7 @@ def dummy? def type Datagrid::Filters::FILTER_TYPES.each do |type, klass| - if is_a?(klass) - return type - end + return type if is_a?(klass) end raise "wtf is #{inspect}" end @@ -137,7 +135,7 @@ def enabled?(grid) end def default_html_classes - [ name, self.class.to_s.demodulize.underscore ] + [name, self.class.to_s.demodulize.underscore] end protected @@ -168,15 +166,16 @@ def normalize_multiple_value(value) end def default_separator - ',' + "," end def driver grid_class.driver end - def default_filter(value, scope, grid) + def default_filter(value, scope, _grid) return nil if dummy? + if !driver.has_column?(scope, name) && scope.respond_to?(name, true) scope.public_send(name, value) else @@ -184,4 +183,3 @@ def default_filter(value, scope, grid) end end end - diff --git a/lib/datagrid/filters/boolean_filter.rb b/lib/datagrid/filters/boolean_filter.rb index 554fad7..89aed9b 100644 --- a/lib/datagrid/filters/boolean_filter.rb +++ b/lib/datagrid/filters/boolean_filter.rb @@ -1,9 +1,7 @@ require "datagrid/utils" # @!visibility private class Datagrid::Filters::BooleanFilter < Datagrid::Filters::BaseFilter - def parse(value) Datagrid::Utils.booleanize(value) end - end diff --git a/lib/datagrid/filters/composite_filters.rb b/lib/datagrid/filters/composite_filters.rb index c81f358..3eb405a 100644 --- a/lib/datagrid/filters/composite_filters.rb +++ b/lib/datagrid/filters/composite_filters.rb @@ -2,22 +2,21 @@ module Datagrid module Filters # @!visibility private module CompositeFilters - def self.included(base) - base.extend ClassMethods + base.extend ClassMethods base.class_eval do end end # @!visibility private module ClassMethods - def date_range_filters(field, from_options = {}, to_options = {}) - Utils.warn_once('date_range_filters is deprecated in favor of range option for date filter') + Utils.warn_once("date_range_filters is deprecated in favor of range option for date filter") from_options = normalize_composite_filter_options(from_options, field) to_options = normalize_composite_filter_options(to_options, field) - filter(from_options[:name] || :"from_#{field.to_s.tr('.', '_')}", :date, **from_options) do |date, scope, grid| + filter(from_options[:name] || :"from_#{field.to_s.tr('.', '_')}", :date, + **from_options) do |date, scope, grid| grid.driver.greater_equal(scope, field, date) end filter(to_options[:name] || :"to_#{field.to_s.tr('.', '_')}", :date, **to_options) do |date, scope, grid| @@ -26,10 +25,11 @@ def date_range_filters(field, from_options = {}, to_options = {}) end def integer_range_filters(field, from_options = {}, to_options = {}) - Utils.warn_once('integer_range_filters is deprecated in favor of range option for integer filter') + Utils.warn_once("integer_range_filters is deprecated in favor of range option for integer filter") from_options = normalize_composite_filter_options(from_options, field) to_options = normalize_composite_filter_options(to_options, field) - filter(from_options[:name] || :"from_#{field.to_s.tr('.', '_')}", :integer, **from_options) do |value, scope, grid| + filter(from_options[:name] || :"from_#{field.to_s.tr('.', '_')}", :integer, + **from_options) do |value, scope, grid| grid.driver.greater_equal(scope, field, value) end filter(to_options[:name] || :"to_#{field.to_s.tr('.', '_')}", :integer, **to_options) do |value, scope, grid| @@ -37,10 +37,8 @@ def integer_range_filters(field, from_options = {}, to_options = {}) end end - def normalize_composite_filter_options(options, field) - if options.is_a?(String) || options.is_a?(Symbol) - options = {name: options} - end + def normalize_composite_filter_options(options, _field) + options = { name: options } if options.is_a?(String) || options.is_a?(Symbol) options end end diff --git a/lib/datagrid/filters/date_filter.rb b/lib/datagrid/filters/date_filter.rb index db9c1d4..f9f47c9 100644 --- a/lib/datagrid/filters/date_filter.rb +++ b/lib/datagrid/filters/date_filter.rb @@ -1,13 +1,10 @@ require "datagrid/filters/ranged_filter" class Datagrid::Filters::DateFilter < Datagrid::Filters::BaseFilter - include Datagrid::Filters::RangedFilter def apply(grid_object, scope, value) - if value.is_a?(Range) - value = value.begin&.beginning_of_day..value.end&.end_of_day - end + value = value.begin&.beginning_of_day..value.end&.end_of_day if value.is_a?(Range) super(grid_object, scope, value) end @@ -15,7 +12,6 @@ def parse(value) Datagrid::Utils.parse_date(value) end - def format(value) if formats.any? && value value.strftime(formats.first) @@ -25,9 +21,7 @@ def format(value) end def default_filter_where(scope, value) - if driver.is_timestamp?(scope, name) - value = Datagrid::Utils.format_date_as_timestamp(value) - end + value = Datagrid::Utils.format_date_as_timestamp(value) if driver.is_timestamp?(scope, name) super(scope, value) end @@ -37,4 +31,3 @@ def formats Array(Datagrid.configuration.date_formats) end end - diff --git a/lib/datagrid/filters/date_time_filter.rb b/lib/datagrid/filters/date_time_filter.rb index 50d1331..9809f32 100644 --- a/lib/datagrid/filters/date_time_filter.rb +++ b/lib/datagrid/filters/date_time_filter.rb @@ -1,7 +1,6 @@ require "datagrid/filters/ranged_filter" class Datagrid::Filters::DateTimeFilter < Datagrid::Filters::BaseFilter - include Datagrid::Filters::RangedFilter def parse(value) @@ -22,4 +21,3 @@ def formats Array(Datagrid.configuration.datetime_formats) end end - diff --git a/lib/datagrid/filters/dynamic_filter.rb b/lib/datagrid/filters/dynamic_filter.rb index f3d0d0b..c2b29d3 100644 --- a/lib/datagrid/filters/dynamic_filter.rb +++ b/lib/datagrid/filters/dynamic_filter.rb @@ -1,28 +1,27 @@ require "datagrid/filters/select_options" class Datagrid::Filters::DynamicFilter < Datagrid::Filters::BaseFilter - include Datagrid::Filters::SelectOptions - EQUAL_OPERATION = '=' - LIKE_OPERATION = '=~' - MORE_EQUAL_OPERATION = '>=' - LESS_EQUAL_OPERATION = '<=' + EQUAL_OPERATION = "=" + LIKE_OPERATION = "=~" + MORE_EQUAL_OPERATION = ">=" + LESS_EQUAL_OPERATION = "<=" DEFAULT_OPERATIONS = [ EQUAL_OPERATION, LIKE_OPERATION, MORE_EQUAL_OPERATION, - LESS_EQUAL_OPERATION, + LESS_EQUAL_OPERATION ] - AVAILABLE_OPERATIONS = %w(= =~ >= <=) + AVAILABLE_OPERATIONS = %w[= =~ >= <=] def initialize(*) super options[:select] ||= default_select options[:operations] ||= DEFAULT_OPERATIONS - unless options.has_key?(:include_blank) - options[:include_blank] = false - end + return if options.has_key?(:include_blank) + + options[:include_blank] = false end def parse_values(filter) @@ -41,36 +40,32 @@ def default_filter_where(scope, filter) date_conversion = value.is_a?(Date) && driver.is_timestamp?(scope, field) return scope if field.blank? || operation.blank? + unless operations.include?(operation) - raise Datagrid::FilteringError, "Unknown operation: #{operation.inspect}. Available operations: #{operations.join(' ')}" + raise Datagrid::FilteringError, + "Unknown operation: #{operation.inspect}. Available operations: #{operations.join(' ')}" end + case operation when EQUAL_OPERATION - if date_conversion - value = Datagrid::Utils.format_date_as_timestamp(value) - end + value = Datagrid::Utils.format_date_as_timestamp(value) if date_conversion driver.where(scope, field, value) when LIKE_OPERATION if column_type(field) == :string driver.contains(scope, field, value) else - if date_conversion - value = Datagrid::Utils.format_date_as_timestamp(value) - end + value = Datagrid::Utils.format_date_as_timestamp(value) if date_conversion driver.where(scope, field, value) end when MORE_EQUAL_OPERATION - if date_conversion - value = value.beginning_of_day - end + value = value.beginning_of_day if date_conversion driver.greater_equal(scope, field, value) when LESS_EQUAL_OPERATION - if date_conversion - value = value.end_of_day - end + value = value.end_of_day if date_conversion driver.less_equal(scope, field, value) else - raise Datagrid::FilteringError, "Unknown operation: #{operation.inspect}. Use filter block argument to implement operation" + raise Datagrid::FilteringError, + "Unknown operation: #{operation.inspect}. Use filter block argument to implement operation" end end @@ -87,11 +82,11 @@ def operations_select protected def default_select - proc {|grid| + proc { |grid| grid.driver.column_names(grid.scope).map do |name| # Mongodb/Rails problem: # '_id'.humanize returns '' - [name.gsub(/^_/, '').humanize.strip, name] + [name.gsub(/^_/, "").humanize.strip, name] end } end @@ -99,6 +94,7 @@ def default_select def type_cast(field, value) type = column_type(field) return nil if value.blank? + case type when :string value.to_s diff --git a/lib/datagrid/filters/enum_filter.rb b/lib/datagrid/filters/enum_filter.rb index 809d10c..bc65cc6 100644 --- a/lib/datagrid/filters/enum_filter.rb +++ b/lib/datagrid/filters/enum_filter.rb @@ -1,25 +1,23 @@ require "datagrid/filters/select_options" class Datagrid::Filters::EnumFilter < Datagrid::Filters::BaseFilter - include Datagrid::Filters::SelectOptions def initialize(*args) super(*args) - if checkboxes? - options[:multiple] = true - end + options[:multiple] = true if checkboxes? raise Datagrid::ConfigurationError, ":select option not specified" unless options[:select] end def parse(value) - return nil if self.strict && !select.include?(value) + return nil if strict && !select.include?(value) + value end def default_html_classes res = super - res.push('checkboxes') if checkboxes? + res.push("checkboxes") if checkboxes? res end @@ -30,5 +28,4 @@ def strict def checkboxes? options[:checkboxes] end - end diff --git a/lib/datagrid/filters/extended_boolean_filter.rb b/lib/datagrid/filters/extended_boolean_filter.rb index cdad91a..521cf5e 100644 --- a/lib/datagrid/filters/extended_boolean_filter.rb +++ b/lib/datagrid/filters/extended_boolean_filter.rb @@ -1,10 +1,9 @@ # @!visibility private class Datagrid::Filters::ExtendedBooleanFilter < Datagrid::Filters::EnumFilter - YES = "YES" NO = "NO" - TRUTH_VALUES = [true, 'true', "y", "yes"] - FALSE_VALUES = [false, 'false', "n", "no"] + TRUTH_VALUES = [true, "true", "y", "yes"] + FALSE_VALUES = [false, "false", "n", "no"] def initialize(report, attribute, options = {}, &block) options[:select] = -> { boolean_select } @@ -33,7 +32,7 @@ def parse(value) protected def boolean_select - [YES, NO].map do |key, value| + [YES, NO].map do |key, _value| [I18n.t("datagrid.filters.xboolean.#{key.downcase}"), key] end end diff --git a/lib/datagrid/filters/float_filter.rb b/lib/datagrid/filters/float_filter.rb index 85676fa..4361d60 100644 --- a/lib/datagrid/filters/float_filter.rb +++ b/lib/datagrid/filters/float_filter.rb @@ -1,9 +1,9 @@ class Datagrid::Filters::FloatFilter < Datagrid::Filters::BaseFilter - include Datagrid::Filters::RangedFilter def parse(value) return nil if value.blank? + value.to_f end end diff --git a/lib/datagrid/filters/integer_filter.rb b/lib/datagrid/filters/integer_filter.rb index e1943aa..e05a14e 100644 --- a/lib/datagrid/filters/integer_filter.rb +++ b/lib/datagrid/filters/integer_filter.rb @@ -1,17 +1,16 @@ require "datagrid/filters/ranged_filter" class Datagrid::Filters::IntegerFilter < Datagrid::Filters::BaseFilter - include Datagrid::Filters::RangedFilter def parse(value) return nil if value.blank? if defined?(ActiveRecord) && value.is_a?(ActiveRecord::Base) && - value.respond_to?(:id) && value.id.is_a?(Integer) + value.respond_to?(:id) && value.id.is_a?(Integer) return value.id end return value if value.is_a?(Range) + value.to_i end end - diff --git a/lib/datagrid/filters/ranged_filter.rb b/lib/datagrid/filters/ranged_filter.rb index 399a82e..05ac2c9 100644 --- a/lib/datagrid/filters/ranged_filter.rb +++ b/lib/datagrid/filters/ranged_filter.rb @@ -1,10 +1,9 @@ module Datagrid::Filters::RangedFilter - def initialize(grid, name, options, &block) super(grid, name, options, &block) - if range? - options[:multiple] = true - end + return unless range? + + options[:multiple] = true end def parse_values(value) @@ -30,7 +29,6 @@ def parse_values(value) else raise ArgumentError, "Can not create a date range from array of more than two: #{result.inspect}" end - end def range? @@ -40,17 +38,11 @@ def range? def default_filter_where(scope, value) if range? && value.is_a?(Array) left, right = value - if left - scope = driver.greater_equal(scope, name, left) - end - if right - scope = driver.less_equal(scope, name, right) - end + scope = driver.greater_equal(scope, name, left) if left + scope = driver.less_equal(scope, name, right) if right scope else super(scope, value) end end - - end diff --git a/lib/datagrid/filters/select_options.rb b/lib/datagrid/filters/select_options.rb index bf560e4..68ae60b 100644 --- a/lib/datagrid/filters/select_options.rb +++ b/lib/datagrid/filters/select_options.rb @@ -1,6 +1,6 @@ module Datagrid::Filters::SelectOptions def select(object) - select = self.options[:select] + select = options[:select] if select.is_a?(Symbol) object.send(select) elsif select.respond_to?(:call) @@ -15,7 +15,7 @@ def select_values(object) groups_used = grouped_choices?(options) options.map do |option| if groups_used - option[1].map {|o| option_text_and_value(o)} + option[1].map { |o| option_text_and_value(o) } else option_text_and_value(option) end @@ -23,9 +23,12 @@ def select_values(object) end def include_blank - unless prompt - options.has_key?(:include_blank) ? - Datagrid::Utils.callable(options[:include_blank]) : !multiple? + return if prompt + + if options.has_key?(:include_blank) + Datagrid::Utils.callable(options[:include_blank]) + else + !multiple? end end @@ -41,7 +44,7 @@ def prompt def option_text_and_value(option) # Options are [text, value] pairs or strings used for both. if !option.is_a?(String) && option.respond_to?(:first) && option.respond_to?(:last) - option = option.reject { |e| Hash === e } if Array === option + option = option.reject { |e| e.is_a?(Hash) } if option.is_a?(Array) [option.first, option.last] else [option, option] @@ -52,6 +55,6 @@ def option_text_and_value(option) # https://github.com/rails/rails/blob/f95c0b7e96eb36bc3efc0c5beffbb9e84ea664e4/actionview/lib/action_view/helpers/tags/select.rb#L36 # Code reuse is difficult, so it is easier to duplicate it def grouped_choices?(choices) - !choices.blank? && choices.first.respond_to?(:last) && Array === choices.first.last + !choices.blank? && choices.first.respond_to?(:last) && choices.first.last.is_a?(Array) end end diff --git a/lib/datagrid/filters/string_filter.rb b/lib/datagrid/filters/string_filter.rb index 9ea428c..35d20dd 100644 --- a/lib/datagrid/filters/string_filter.rb +++ b/lib/datagrid/filters/string_filter.rb @@ -1,5 +1,4 @@ class Datagrid::Filters::StringFilter < Datagrid::Filters::BaseFilter - include Datagrid::Filters::RangedFilter def parse(value) diff --git a/lib/datagrid/form_builder.rb b/lib/datagrid/form_builder.rb index bfdd80e..a99888f 100644 --- a/lib/datagrid/form_builder.rb +++ b/lib/datagrid/form_builder.rb @@ -10,7 +10,7 @@ module FormBuilder # * text_field for other filter types def datagrid_filter(filter_or_attribute, partials: nil, **options, &block) filter = datagrid_get_filter(filter_or_attribute) - self.send( filter.form_builder_helper_name, filter, **options, &block) + send(filter.form_builder_helper_name, filter, **options, &block) end # @param filter_or_attribute [Datagrid::Filters::BaseFilter, String, Symbol] filter object or filter name @@ -20,7 +20,7 @@ def datagrid_filter(filter_or_attribute, partials: nil, **options, &block) def datagrid_label(filter_or_attribute, text = nil, **options, &block) filter = datagrid_get_filter(filter_or_attribute) options = add_html_classes( - {**filter.label_options, **options}, + { **filter.label_options, **options }, filter.default_html_classes ) label(filter.name, text || filter.header, **options, &block) @@ -31,7 +31,7 @@ def datagrid_filter_input(attribute_or_filter, **options, &block) filter = datagrid_get_filter(attribute_or_filter) options = add_filter_options(filter, **options) type = options.delete(:type)&.to_sym - if options.has_key?(:value) && options[:value].nil? && [:"datetime-local", :date].include?(type) + if options.has_key?(:value) && options[:value].nil? && %i[datetime-local date].include?(type) # https://github.com/rails/rails/pull/53387 options[:value] = "" end @@ -40,7 +40,7 @@ def datagrid_filter_input(attribute_or_filter, **options, &block) elsif type == :date date_field filter.name, **options, &block elsif type == :textarea - text_area filter.name, value: object.filter_value_as_string(filter) , **options, &block + text_area filter.name, value: object.filter_value_as_string(filter), **options, &block elsif type == :checkbox # raise options.inspect check_box filter.name, options, options.fetch(:value, 1) @@ -55,16 +55,17 @@ def datagrid_filter_input(attribute_or_filter, **options, &block) prompt: filter.prompt, include_hidden: false }, - multiple: filter.multiple?, - **options, - &block + multiple: filter.multiple?, + **options, + &block ) else - text_field filter.name, value: object.filter_value_as_string(filter) , **options, &block + text_field filter.name, value: object.filter_value_as_string(filter), **options, &block end end protected + def datagrid_extended_boolean_filter(filter, options = {}, &block) datagrid_filter_input(filter, **options, type: :select, &block) end @@ -93,12 +94,12 @@ def datagrid_enum_filter(filter, options = {}, &block) [value, text, checked] end render_partial( - 'enum_checkboxes', + "enum_checkboxes", { elements: elements, form: self, filter: filter, - options: options, + options: options } ) else @@ -118,14 +119,12 @@ def enum_checkbox_checked?(filter, option_value) end def datagrid_integer_filter(filter, options = {}) - if filter.multiple? && object[filter.name].blank? - options[:value] = "" - end + options[:value] = "" if filter.multiple? && object[filter.name].blank? datagrid_range_filter(:integer, filter, options) end def datagrid_dynamic_filter(filter, options = {}) - input_name = "#{object_name}[#{filter.name.to_s}][]" + input_name = "#{object_name}[#{filter.name}][]" field, operation, value = object.filter_value(filter) options = add_filter_options(filter, **options) options = options.merge(name: input_name) @@ -146,7 +145,7 @@ def datagrid_dynamic_filter(filter, options = {}) include_blank: false, include_hidden: false, prompt: false, - selected: operation, + selected: operation }, add_html_classes(options, "operation") ) @@ -166,12 +165,12 @@ def dynamic_filter_select(name, variants, select_options, html_options) end end - def datagrid_range_filter(type, filter, options = {}) + def datagrid_range_filter(_type, filter, options = {}) if filter.range? options = options.merge(multiple: true) from_options = datagrid_range_filter_options(object, filter, :from, options) to_options = datagrid_range_filter_options(object, filter, :to, options) - render_partial 'range_filter', { + render_partial "range_filter", { from_options: from_options, to_options: to_options, filter: filter, form: self } else @@ -180,7 +179,7 @@ def datagrid_range_filter(type, filter, options = {}) end def datagrid_range_filter_options(object, filter, type, options) - type_method_map = {from: :first, to: :last} + type_method_map = { from: :first, to: :last } options = add_html_classes(options, type) options[:value] = filter.format(object[filter.name]&.public_send(type_method_map[type])) # In case of datagrid ranged filter @@ -219,14 +218,12 @@ def add_html_classes(options, *classes) end def partial_path(name) - if partials = self.options[:partials] + if partials = options[:partials] partial_name = File.join(partials, name) # Second argument is []: no magical namespaces to lookup added from controller - if @template.lookup_context.template_exists?(partial_name, [], true) - return partial_name - end + return partial_name if @template.lookup_context.template_exists?(partial_name, [], true) end - File.join('datagrid', name) + File.join("datagrid", name) end def render_partial(name, locals) @@ -235,8 +232,8 @@ def render_partial(name, locals) def add_filter_options(filter, **options) add_html_classes( - {**filter.input_options, **options}, - *filter.default_html_classes, + { **filter.input_options, **options }, + *filter.default_html_classes ) end diff --git a/lib/datagrid/helper.rb b/lib/datagrid/helper.rb index 2a76698..039bc13 100644 --- a/lib/datagrid/helper.rb +++ b/lib/datagrid/helper.rb @@ -2,7 +2,6 @@ module Datagrid module Helper - # @param grid [Datagrid] grid object # @param column [Datagrid::Columns::Column, String, Symbol] column name # @param model [Object] an object from grid scope @@ -62,7 +61,6 @@ def datagrid_header(grid, options = {}) datagrid_renderer.header(grid, options) end - # Renders HTML table rows using given grid definition using columns defined in it. # Allows to provide a custom layout for each for in place with a block # @@ -149,9 +147,10 @@ def datagrid_renderer end def datagrid_column_classes(grid, column) - order_class = grid.ordered_by?(column) ? ["ordered", grid.descending ? "desc" : "asc"] : nil + order_class = if grid.ordered_by?(column) + ["ordered", grid.descending ? "desc" : "asc"] + end [column.name, order_class, column.options[:class]].compact.join(" ") end end end - diff --git a/lib/datagrid/ordering.rb b/lib/datagrid/ordering.rb index 0f6cbee..83577c6 100644 --- a/lib/datagrid/ordering.rb +++ b/lib/datagrid/ordering.rb @@ -4,39 +4,32 @@ module Datagrid # Raised when grid order value is incorrect class OrderUnsupported < StandardError end - module Ordering + module Ordering # @!visibility private def self.included(base) - base.extend ClassMethods + base.extend ClassMethods base.class_eval do include Datagrid::Columns datagrid_attribute :order do |value| - if value.present? - value.to_sym - else - nil - end - + value.to_sym if value.present? end datagrid_attribute :descending do |value| Datagrid::Utils.booleanize(value) end - alias descending? descending - + alias_method :descending?, :descending end end # @!visibility private module ClassMethods def order_unsupported(name, reason) - raise Datagrid::OrderUnsupported, "Can not sort #{self.inspect} by ##{name}: #{reason}" + raise Datagrid::OrderUnsupported, "Can not sort #{inspect} by ##{name}: #{reason}" end end - # @!visibility private def assets check_order_valid! @@ -65,33 +58,31 @@ def ordered_by?(column) def apply_order(assets) return assets unless order + if order_column.order_by_value? assets = assets.sort_by do |asset| order_column.order_by_value(asset, self) end descending? ? assets.reverse : assets - else - if descending? - if order_column.order_desc - apply_asc_order(assets, order_column.order_desc) - else - apply_desc_order(assets, order_column.order) - end + elsif descending? + if order_column.order_desc + apply_asc_order(assets, order_column.order_desc) else - apply_asc_order(assets, order_column.order) + apply_desc_order(assets, order_column.order) end + else + apply_asc_order(assets, order_column.order) end end def check_order_valid! return unless order + column = column_by_name(order) - unless column - self.class.order_unsupported(order, "no column #{order} in #{self.class}") - end - unless column.supports_order? - self.class.order_unsupported(column.name, "column don't support order" ) - end + self.class.order_unsupported(order, "no column #{order} in #{self.class}") unless column + return if column.supports_order? + + self.class.order_unsupported(column.name, "column don't support order") end def apply_asc_order(assets, order) @@ -113,7 +104,8 @@ def apply_desc_order(assets, order) def reverse_order(assets) driver.reverse_order(assets) rescue NotImplementedError - self.class.order_unsupported(order_column.name, "Your ORM do not support reverse order: please specify :order_desc option manually") + self.class.order_unsupported(order_column.name, + "Your ORM do not support reverse order: please specify :order_desc option manually") end def apply_block_order(assets, order) diff --git a/lib/datagrid/renderer.rb b/lib/datagrid/renderer.rb index 3b472f0..3b23449 100644 --- a/lib/datagrid/renderer.rb +++ b/lib/datagrid/renderer.rb @@ -3,7 +3,6 @@ module Datagrid # @!visibility private class Renderer - def self.for(template) new(template) end @@ -13,9 +12,7 @@ def initialize(template) end def format_value(grid, column, asset) - if column.is_a?(String) || column.is_a?(Symbol) - column = grid.column_by_name(column) - end + column = grid.column_by_name(column) if column.is_a?(String) || column.is_a?(Symbol) value = grid.html_value(column, @template, asset) @@ -32,14 +29,14 @@ def form_for(grid, options = {}) options[:html] ||= {} options[:html][:class] ||= "datagrid-form #{@template.dom_class(grid)}" options[:as] ||= grid.param_name - _render_partial('form', options[:partials], {:grid => grid, :options => options}) + _render_partial("form", options[:partials], { grid: grid, options: options }) end def table(grid, assets, **options) options[:html] ||= {} options[:html][:class] ||= "datagrid #{@template.dom_class(grid)}" - _render_partial('table', options[:partials], + _render_partial("table", options[:partials], { grid: grid, options: options, @@ -50,8 +47,8 @@ def table(grid, assets, **options) def header(grid, options = {}) options[:order] = true unless options.has_key?(:order) - _render_partial('head', options[:partials], - { :grid => grid, :options => options }) + _render_partial("head", options[:partials], + { grid: grid, options: options }) end def rows(grid, assets = grid.assets, **options, &block) @@ -64,22 +61,20 @@ def rows(grid, assets = grid.assets, **options, &block) def row(grid, asset, **options, &block) Datagrid::Helper::HtmlRow.new(self, grid, asset, options).tap do |row| - if block_given? - return @template.capture(row, &block) - end + return @template.capture(row, &block) if block_given? end end def order_for(grid, column, options = {}) - _render_partial('order_for', options[:partials], - { :grid => grid, :column => column }) + _render_partial("order_for", options[:partials], + { grid: grid, column: column }) end def order_path(grid, column, descending, request) column = grid.column_by_name(column) query = request ? request.query_parameters : {} ActionDispatch::Http::URL.path_for( - path: request ? request.path : '/', + path: request ? request.path : "/", params: query.merge(grid.query_params(order: column.name, descending: descending)) ) end @@ -92,9 +87,9 @@ def _safe(string) def _render_partial(partial_name, partials_path, locals = {}) @template.render({ - :partial => File.join(partials_path || 'datagrid', partial_name), - :locals => locals - }) + partial: File.join(partials_path || "datagrid", partial_name), + locals: locals + }) end end @@ -110,7 +105,6 @@ module Helper # puts value # end class HtmlRow - include Enumerable attr_reader :grid, :asset, :options @@ -137,14 +131,15 @@ def each(&block) end def to_s - @renderer.send(:_render_partial, 'row', options[:partials], { - :grid => grid, - :options => options, - :asset => asset - }) + @renderer.send(:_render_partial, "row", options[:partials], { + grid: grid, + options: options, + asset: asset + }) end protected + def method_missing(method, *args, &blk) if column = @grid.column_by_name(method) get(column) diff --git a/lib/datagrid/rspec.rb b/lib/datagrid/rspec.rb index ce7ff83..6b07ea7 100644 --- a/lib/datagrid/rspec.rb +++ b/lib/datagrid/rspec.rb @@ -1,16 +1,14 @@ require "datagrid" -#TODO: refactor this experimental shit +# TODO: refactor this experimental shit shared_examples_for "Datagrid" do describe "as Datagrid" do - it "should have at least one entry if assets" do subject.assets.should_not be_empty end - described_class.columns(:data => true).each do |column| + described_class.columns(data: true).each do |column| describe "column ##{column.name}" do - it "should has value in #data_hash" do subject.data_hash.first.should have_key(column.name) end @@ -25,14 +23,11 @@ subject.assets.first.should_not be_nil end end - end described_class.filters.each do |filter| describe "filter ##{filter.name}" do - let(:filter_value) do - case Datagrid::Filters::FILTER_TYPES.invert[filter.class] when :default, :string "text" @@ -53,16 +48,15 @@ end before(:each) do - subject.attributes = {filter.name => filter_value} + subject.attributes = { filter.name => filter_value } subject.public_send(filter.name).should_not be_nil end it "should be supported" do subject.assets.should_not be_nil - #TODO: better matcher. + # TODO: better matcher. end end end - end end diff --git a/lib/datagrid/scaffold.rb b/lib/datagrid/scaffold.rb index aad238f..d6c6d23 100644 --- a/lib/datagrid/scaffold.rb +++ b/lib/datagrid/scaffold.rb @@ -2,36 +2,31 @@ # @!visibility private class Datagrid::Scaffold < Rails::Generators::NamedBase - include Rails::Generators::ResourceHelpers check_class_collision suffix: "Grid" source_root File.expand_path(__FILE__ + "/../../../templates") def create_scaffold - unless file_exists?(base_grid_file) - template "base.rb.erb", base_grid_file - end + template "base.rb.erb", base_grid_file unless file_exists?(base_grid_file) template "grid.rb.erb", "app/grids/#{grid_class_name.underscore}.rb" if file_exists?(grid_controller_file) - inject_into_file grid_controller_file, index_action, after: %r{class .*#{grid_controller_class_name}.*\n} + inject_into_file grid_controller_file, index_action, after: /class .*#{grid_controller_class_name}.*\n/ else template "controller.rb.erb", grid_controller_file end template "index.html.erb", view_file route(generate_routing_namespace("resources :#{grid_controller_short_name}")) - unless defined?(::Kaminari) || defined?(::WillPaginate) - gem 'kaminari' - end + gem "kaminari" unless defined?(::Kaminari) || defined?(::WillPaginate) in_root do { "css" => " *= require datagrid", "css.sass" => " *= require datagrid", - "css.scss" => " *= require datagrid", + "css.scss" => " *= require datagrid" }.each do |extension, string| file = "app/assets/stylesheets/application.#{extension}" if file_exists?(file) - inject_into_file file, string + "\n", {before: %r{.*require_self}} # before all + inject_into_file file, string + "\n", { before: /.*require_self/ } # before all end end end @@ -83,22 +78,23 @@ def grid_route_name end def index_action - indent(<<-RUBY) -def index - @grid = #{grid_class_name}.new(grid_params) do |scope| - scope.page(params[:page]) - end -end + indent(<<~RUBY) + def index + @grid = #{grid_class_name}.new(grid_params) do |scope| + scope.page(params[:page]) + end + end -protected + protected -def grid_params - params.fetch(:#{grid_param_name}, {}).permit! -end -RUBY + def grid_params + params.fetch(:#{grid_param_name}, {}).permit! + end + RUBY end protected + def generate_routing_namespace(code) depth = regular_class_path.length # Create 'namespace' ladder diff --git a/lib/datagrid/utils.rb b/lib/datagrid/utils.rb index 1114c85..254ab02 100644 --- a/lib/datagrid/utils.rb +++ b/lib/datagrid/utils.rb @@ -2,26 +2,19 @@ module Datagrid # @!visibility private module Utils class << self - - TRUTH = [true, 1, "1", "true", "yes", "on"] def booleanize(value) - if value.respond_to?(:downcase) - value = value.downcase - end + value = value.downcase if value.respond_to?(:downcase) TRUTH.include?(value) end def translate_from_namespace(namespace, grid_class, key) - lookups = [] namespaced_key = "#{namespace}.#{key}" grid_class.ancestors.each do |ancestor| - if ancestor.respond_to?(:model_name) - lookups << :"datagrid.#{ancestor.model_name.i18n_key}.#{namespaced_key}" - end + lookups << :"datagrid.#{ancestor.model_name.i18n_key}.#{namespaced_key}" if ancestor.respond_to?(:model_name) end lookups << :"datagrid.defaults.#{namespaced_key}" lookups << key.to_s.humanize @@ -32,6 +25,7 @@ def warn_once(message, delay = 5) @warnings ||= {} timestamp = @warnings[message] return false if timestamp && timestamp >= Time.now - delay + warn message @warnings[message] = Time.now true @@ -39,6 +33,7 @@ def warn_once(message, delay = 5) def add_html_classes(options, *classes) return options if classes.empty? + options = options.clone options[:class] ||= [] array = options[:class].is_a?(Array) @@ -52,18 +47,18 @@ def string_like?(value) end def extract_position_from_options(array, options) - before, after = options[:before], options[:after] - if before && after - raise Datagrid::ConfigurationError, "Options :before and :after can not be used together" - end + before = options[:before] + after = options[:after] + raise Datagrid::ConfigurationError, "Options :before and :after can not be used together" if before && after # Consider as before all return 0 if before == true + if before before = before.to_sym - array.index {|c| c.name.to_sym == before } + array.index { |c| c.name.to_sym == before } elsif after after = after.to_sym - array.index {|c| c.name.to_sym == after } + 1 + array.index { |c| c.name.to_sym == after } + 1 else -1 end @@ -77,16 +72,16 @@ def apply_args(*args, &block) def parse_date(value) return nil if value.blank? return value if value.is_a?(Range) + if value.is_a?(String) Array(Datagrid.configuration.date_formats).each do |format| - begin - return Date.strptime(value, format) - rescue ::ArgumentError - end + return Date.strptime(value, format) + rescue ::ArgumentError end end return Date.parse(value) if value.is_a?(String) return value.to_date if value.respond_to?(:to_date) + value rescue ::ArgumentError nil @@ -95,16 +90,16 @@ def parse_date(value) def parse_datetime(value) return nil if value.blank? return value if value.is_a?(Range) + if value.is_a?(String) Array(Datagrid.configuration.datetime_formats).each do |format| - begin - return Time.strptime(value, format) - rescue ::ArgumentError - end + return Time.strptime(value, format) + rescue ::ArgumentError end end return Time.parse(value) if value.is_a?(String) return value.to_time if value.respond_to?(:to_time) + value rescue ::ArgumentError nil @@ -132,6 +127,7 @@ def callable(value) end protected + def property_availability(grid, option, default) case option when nil diff --git a/lib/tasks/datagrid_tasks.rake b/lib/tasks/datagrid_tasks.rake index 5285bd0..27eb792 100644 --- a/lib/tasks/datagrid_tasks.rake +++ b/lib/tasks/datagrid_tasks.rake @@ -1,5 +1,4 @@ namespace :datagrid do - desc "Copy table partials into rails application" task :copy_partials do require "fileutils" diff --git a/spec/datagrid/active_model_spec.rb b/spec/datagrid/active_model_spec.rb index d0e4220..b42adbc 100644 --- a/spec/datagrid/active_model_spec.rb +++ b/spec/datagrid/active_model_spec.rb @@ -1,7 +1,6 @@ -require 'spec_helper' +require "spec_helper" describe Datagrid::ActiveModel do - class ActiveReport include Datagrid::ActiveModel end @@ -23,11 +22,10 @@ class ActiveReport describe ".param_name" do it "should make right param key from simple class name" do - expect(ActiveReport.param_name).to eq('active_report') + expect(ActiveReport.param_name).to eq("active_report") end it "should make right param key from class of module" do - expect(Grid::ActiveReport.param_name).to eq('grid_active_report') + expect(Grid::ActiveReport.param_name).to eq("grid_active_report") end end - end diff --git a/spec/datagrid/column_names_attribute_spec.rb b/spec/datagrid/column_names_attribute_spec.rb index 4a35c24..321cc5f 100644 --- a/spec/datagrid/column_names_attribute_spec.rb +++ b/spec/datagrid/column_names_attribute_spec.rb @@ -1,7 +1,6 @@ require "spec_helper" describe Datagrid::ColumnNamesAttribute do - let(:column_names_filter_options) do {} end @@ -12,37 +11,36 @@ scope { Entry } column_names_filter(**options) column(:id) - column(:name, :mandatory => true) + column(:name, mandatory: true) column(:category) end end subject { report } - let!(:entry) do - Entry.create!(:name => 'hello', :category => 'greeting') + Entry.create!(name: "hello", category: "greeting") end it "should work" do subject.column_names = [:id] expect(subject.mandatory_columns.map(&:name)).to eq([:name]) - expect(subject.optional_columns.map(&:name)).to eq([:id, :category]) - expect(subject.data).to eq([["Id", "Name"], [entry.id, "hello"]]) + expect(subject.optional_columns.map(&:name)).to eq(%i[id category]) + expect(subject.data).to eq([%w[Id Name], [entry.id, "hello"]]) columns_filter = subject.filter_by_name(:column_names) expect(columns_filter).not_to be_nil expect(columns_filter.select(subject)).to eq([["Id", :id], ["Category", :category]]) end it "should show only mandatory columns by default" do - expect(subject.row_for(entry)).to eq([ "hello" ]) - subject.column_names = ["name", "category"] - expect(subject.row_for(entry)).to eq(["hello", "greeting"]) + expect(subject.row_for(entry)).to eq(["hello"]) + subject.column_names = %w[name category] + expect(subject.row_for(entry)).to eq(%w[hello greeting]) end it "should show mandatory columns even if they are unselected" do subject.column_names = ["category"] - expect(subject.row_for(entry)).to eq(["hello", "greeting"]) - expect(subject.data).to eq([["Name", "Category"], ["hello", "greeting"]]) + expect(subject.row_for(entry)).to eq(%w[hello greeting]) + expect(subject.data).to eq([%w[Name Category], %w[hello greeting]]) end it "should find any column by name" do @@ -51,27 +49,25 @@ expect(subject.column_by_name(:category)).not_to be_nil end - context "when default option is passed to column_names_filter" do let(:column_names_filter_options) do - { :default => [:id] } + { default: [:id] } end - describe '#data' do + describe "#data" do subject { super().data } - it { should == [["Id", "Name"], [entry.id, 'hello']] } + it { should == [%w[Id Name], [entry.id, "hello"]] } end - end context "when some columns are disabled" do subject do test_report do - scope {Entry} - column(:id, :mandatory => true) + scope { Entry } + column(:id, mandatory: true) column(:name) column(:category, if: proc { false }) - column(:group, :mandatory => true, if: proc { false }) + column(:group, mandatory: true, if: proc { false }) end end diff --git a/spec/datagrid/columns/column_spec.rb b/spec/datagrid/columns/column_spec.rb index 8fc3d75..086ecbc 100644 --- a/spec/datagrid/columns/column_spec.rb +++ b/spec/datagrid/columns/column_spec.rb @@ -1,19 +1,18 @@ -require 'spec_helper' +require "spec_helper" describe Datagrid::Columns::Column do - describe ".inspect" do subject do class ColumnInspectTest include Datagrid - scope {Entry} + scope { Entry } column(:id, header: "ID") end ColumnInspectTest.column_by_name(:id) end it "shows inspect information" do - expect(subject.inspect).to eq("#\"ID\"}>") + expect(subject.inspect).to eq('#"ID"}>') end end end diff --git a/spec/datagrid/columns_spec.rb b/spec/datagrid/columns_spec.rb index bdefe02..c644800 100644 --- a/spec/datagrid/columns_spec.rb +++ b/spec/datagrid/columns_spec.rb @@ -1,7 +1,6 @@ -require 'spec_helper' +require "spec_helper" describe Datagrid::Columns do - let(:group) { Group.create!(name: "Pop") } subject do @@ -9,7 +8,6 @@ end describe "basic methods" do - let!(:entry) do Entry.create!( group: group, @@ -17,8 +15,8 @@ disabled: false, confirmed: false, category: "first", - access_level: 'admin', - pet: 'rottweiler', + access_level: "admin", + pet: "rottweiler", shipping_date: Date.new(2013, 8, 1) ) end @@ -27,19 +25,19 @@ it "should have data columns without html columns" do grid = test_report do - scope {Entry} + scope { Entry } column(:name) column(:action, html: true) do - 'dummy' + "dummy" end end expect(grid.data_columns.map(&:name)).to eq([:name]) - expect(grid.html_columns.map(&:name)).to eq([:name, :action]) + expect(grid.html_columns.map(&:name)).to eq(%i[name action]) end it "allows a column argument" do grid = test_report do - scope {Entry} + scope { Entry } column(:name) end expect(grid.data_columns(grid.column_by_name(:name)).map(&:name)).to eq([:name]) @@ -47,27 +45,26 @@ it "should build rows of data" do grid = test_report do - scope {Entry} + scope { Entry } column(:name) column(:action, html: true) do - 'dummy' + "dummy" end end expect(grid.rows).to eq([["Star"]]) end - it "should generate header without html columns" do + it "should generate header without html columns" do grid = test_report do - scope {Entry} + scope { Entry } column(:name) column(:action, html: true) do - 'dummy' + "dummy" end end expect(grid.header).to eq(["Name"]) end describe "translations" do - module ::Ns45 class TranslatedReport include Datagrid @@ -76,7 +73,7 @@ class TranslatedReport end end it "translates column-header with namespace" do - store_translations(:en, datagrid: {:"ns45/translated_report" => {columns: {name: "Navn"}}}) do + store_translations(:en, datagrid: { "ns45/translated_report": { columns: { name: "Navn" } } }) do expect(Ns45::TranslatedReport.new.header.first).to eq("Navn") end end @@ -84,11 +81,11 @@ class TranslatedReport it "translates column-header without namespace" do class Report27 include Datagrid - scope {Entry} + scope { Entry } column(:name) end - store_translations(:en, datagrid: {:"report27" => {columns: {name: "Nombre"}}}) do + store_translations(:en, datagrid: { "report27": { columns: { name: "Nombre" } } }) do expect(Report27.new.header.first).to eq("Nombre") end end @@ -96,20 +93,19 @@ class Report27 it "translates column-header in using defaults namespace" do class Report27 include Datagrid - scope {Entry} + scope { Entry } column(:name) end - store_translations(:en, datagrid: {defaults: {columns: {name: "Nombre"}}}) do + store_translations(:en, datagrid: { defaults: { columns: { name: "Nombre" } } }) do expect(Report27.new.header.first).to eq("Nombre") end end - end it "should return html_columns" do report = test_report do - scope {Entry} + scope { Entry } column(:id) column(:name, html: false) end @@ -118,7 +114,7 @@ class Report27 it "should return html_columns when column definition has 2 arguments" do report = test_report(name: "Hello") do - scope {Entry} + scope { Entry } filter(:name) column(:id) column(:name, html: false) do |model, grid| @@ -131,14 +127,14 @@ class Report27 it "should generate table data" do expect(subject.data).to eq([ - subject.header, - subject.row_for(entry) - ]) + subject.header, + subject.row_for(entry) + ]) end it "supports dynamic header" do grid = test_report do - scope {Entry} + scope { Entry } column(:id, header: proc { rand(10**9) }) end @@ -147,12 +143,12 @@ class Report27 it "should generate hash for given asset" do expect(subject.hash_for(entry)).to eq({ - group: "Pop", - name: "Star", - access_level: 'admin', - pet: 'ROTTWEILER', - shipping_date: date - }) + group: "Pop", + name: "Star", + access_level: "admin", + pet: "ROTTWEILER", + shipping_date: date + }) end it "should support csv export" do @@ -166,12 +162,11 @@ class Report27 it "should support csv export options" do expect(subject.to_csv(col_sep: ";")).to eq("Shipping date;Group;Name;Access level;Pet\n#{date};Pop;Star;admin;ROTTWEILER\n") end - end it "should support columns with model and report arguments" do report = test_report(category: "foo") do - scope {Entry.order(:category)} + scope { Entry.order(:category) } filter(:category) do |value| where("category LIKE '%#{value}%'") end @@ -203,64 +198,64 @@ class Report27 end it "should support defining a query for a column" do report = test_report do - scope {Entry} + scope { Entry } filter(:name) column(:id) - column(:sum_group_id, 'sum(group_id)') + column(:sum_group_id, "sum(group_id)") end Entry.create!(group: group) expect(report.assets.first.sum_group_id).to eq(group.id) end - it "should support post formatting for column defined with query" do - report = test_report do - scope {Group.joins(:entries).group("groups.id")} - filter(:name) - column(:entries_count, 'count(entries.id)') do |model| - format("(#{model.entries_count})") do |value| - content_tag(:span, value) - end + it "should support post formatting for column defined with query" do + report = test_report do + scope { Group.joins(:entries).group("groups.id") } + filter(:name) + column(:entries_count, "count(entries.id)") do |model| + format("(#{model.entries_count})") do |value| + content_tag(:span, value) end end - 3.times { Entry.create!(group: group) } - expect(report.rows).to eq([["(3)"]]) end - it "should support hidding columns through if and unless" do - report = test_report do - scope {Entry} - column(:id, if: :show?) - column(:name, unless: proc {|grid| !grid.show? }) - column(:category) + 3.times { Entry.create!(group: group) } + expect(report.rows).to eq([["(3)"]]) + end + it "should support hidding columns through if and unless" do + report = test_report do + scope { Entry } + column(:id, if: :show?) + column(:name, unless: proc { |grid| !grid.show? }) + column(:category) - def show? - false - end + def show? + false end - expect(report.columns(:id)).to eq([]) - expect(report.columns(:name)).to eq([]) - expect(report.available_columns.map(&:name)).to eq([:category]) end + expect(report.columns(:id)).to eq([]) + expect(report.columns(:name)).to eq([]) + expect(report.available_columns.map(&:name)).to eq([:category]) + end - it "raises when incorrect unless option is given" do - expect do - test_report do - column(:id, if: Object.new) - end - end.to raise_error(Datagrid::ConfigurationError) - end + it "raises when incorrect unless option is given" do + expect do + test_report do + column(:id, if: Object.new) + end + end.to raise_error(Datagrid::ConfigurationError) + end - it "raises when :before and :after used together" do - expect do - test_report do - column(:id) - column(:name, before: :id, after: :name) - end - end.to raise_error(Datagrid::ConfigurationError) - end + it "raises when :before and :after used together" do + expect do + test_report do + column(:id) + column(:name, before: :id, after: :name) + end + end.to raise_error(Datagrid::ConfigurationError) + end describe ".column_names attributes" do let(:grid) do - test_report(column_names: ["id", "name"]) do + test_report(column_names: %w[id name]) do scope { Entry } column(:id) column(:name) @@ -268,10 +263,10 @@ def show? end end let!(:entry) do - Entry.create!(name: 'hello') + Entry.create!(name: "hello") end it "should be suppored in header" do - expect(grid.header).to eq(["Id", "Name"]) + expect(grid.header).to eq(%w[Id Name]) end it "should be suppored in rows" do expect(grid.rows).to eq([[entry.id, "hello"]]) @@ -282,16 +277,14 @@ def show? end it "should support explicit overwrite" do - expect(grid.header(:id, :name, :category)).to eq(%w(Id Name Category)) + expect(grid.header(:id, :name, :category)).to eq(%w[Id Name Category]) end - end - context "when grid has formatted column" do it "should output correct data" do report = test_report do - scope {Entry} + scope { Entry } column(:name) do |entry| format(entry.name) do |value| "#{value}(a) { a.order(:id) }) - column(:id2, preload: ->(a) { a.order(:id) }, if: ->(a) { false }) + column(:id2, preload: ->(a) { a.order(:id) }, if: ->(_a) { false }) column(:name) end grid.column_names = [:name] @@ -619,10 +614,10 @@ class DataHashGrid end grid1 = DataHashGrid.new(order: :name) grid2 = DataHashGrid.new(order: :name, descending: true) - Entry.create!(name: 'one') - Entry.create!(name: 'two') - expect(grid1.data_hash).to eq([{name: 'one'}, {name: 'two'}]) - expect(grid2.data_hash).to eq([{name: 'two'}, {name: 'one'}]) + Entry.create!(name: "one") + Entry.create!(name: "two") + expect(grid1.data_hash).to eq([{ name: "one" }, { name: "two" }]) + expect(grid2.data_hash).to eq([{ name: "two" }, { name: "one" }]) end end end diff --git a/spec/datagrid/core_spec.rb b/spec/datagrid/core_spec.rb index b78cd6f..e5c5d47 100644 --- a/spec/datagrid/core_spec.rb +++ b/spec/datagrid/core_spec.rb @@ -1,9 +1,9 @@ -require 'spec_helper' +require "spec_helper" require "action_controller/metal/strong_parameters" describe Datagrid::Core do - describe '#original_scope' do - it 'does not wrap instance scope' do + describe "#original_scope" do + it "does not wrap instance scope" do grid = test_report do scope { Entry } end @@ -11,7 +11,7 @@ expect(grid.original_scope).to eq(Entry) end - it 'does not wrap class scope' do + it "does not wrap class scope" do klass = test_report_class do scope { Entry } end @@ -20,7 +20,7 @@ end end - context 'with 2 persisted entries' do + context "with 2 persisted entries" do before { 2.times { Entry.create } } let(:report_class) do @@ -31,8 +31,7 @@ class ScopeTestReport ScopeTestReport end - describe '#scope' do - + describe "#scope" do it "wraps scope" do grid = test_report do scope { Entry } @@ -40,7 +39,7 @@ class ScopeTestReport expect(grid.scope).to be_kind_of(ActiveRecord::Relation) end - context 'in the class' do + context "in the class" do let(:report) { report_class.new } it { expect(report.scope.to_a.size).to eq(2) } @@ -61,10 +60,10 @@ class TestGrid < ScopeTestReport end end - context 'changes scope on the fly' do + context "changes scope on the fly" do let(:report) do report_class.new.tap do |r| - r.scope { Entry.limit(1)} + r.scope { Entry.limit(1) } end end @@ -72,7 +71,7 @@ class TestGrid < ScopeTestReport it { expect(report).to be_redefined_scope } end - context 'overriding scope by initializer' do + context "overriding scope by initializer" do let(:report) { report_class.new { Entry.limit(1) } } it { expect(report).to be_redefined_scope } @@ -88,7 +87,7 @@ class TestGrid < ScopeTestReport end context "appending scope by initializer " do - let(:report) { report_class.new {|scope| scope.limit(1)} } + let(:report) { report_class.new { |scope| scope.limit(1) } } it { expect(report.scope.to_a.size).to eq(1) } it { expect(report.scope.order_values.size).to eq(1) } it { expect(report).to be_redefined_scope } @@ -100,20 +99,20 @@ class TestGrid < ScopeTestReport it "should show all attribute values" do class InspectTest include Datagrid - scope {Entry} + scope { Entry } filter(:created_at, :date, range: true) column(:name) end - grid = InspectTest.new(created_at: ['2014-01-01', '2014-08-05'], descending: true, order: 'name') - expect(grid.inspect).to eq('#') + grid = InspectTest.new(created_at: %w[2014-01-01 2014-08-05], descending: true, order: "name") + expect(grid.inspect).to eq("#") end end describe "#==" do class EqualTest include Datagrid - scope {Entry} + scope { Entry } filter(:created_at, :date) column(:name) column(:created_at) @@ -131,14 +130,14 @@ class EqualTest expect(EqualTest.new(order: :created_at)).to eq(EqualTest.new(order: "created_at")) end it "checks for redefined scope" do - expect(EqualTest.new).to_not eq(EqualTest.new {|s| s.reorder(:name)}) + expect(EqualTest.new).to_not eq(EqualTest.new { |s| s.reorder(:name) }) end end - describe 'dynamic helper' do + describe "dynamic helper" do it "should work" do grid = test_report do - scope {Entry} + scope { Entry } column(:id) dynamic do column(:name) @@ -146,7 +145,7 @@ class EqualTest end end - expect(grid.columns.map(&:name)).to eq([:id, :name, :category]) + expect(grid.columns.map(&:name)).to eq(%i[id name category]) expect(grid.class.columns.map(&:name)).to eq([:id]) expect(grid.column_by_name(:id)).not_to be_nil @@ -154,8 +153,8 @@ class EqualTest end it "has access to attributes" do - grid = test_report(attribute_name: 'value') do - scope {Entry} + grid = test_report(attribute_name: "value") do + scope { Entry } datagrid_attribute :attribute_name dynamic do value = attribute_name @@ -163,12 +162,12 @@ class EqualTest end end - expect(grid.data_value(:name, Entry.create!)).to eq('value') + expect(grid.data_value(:name, Entry.create!)).to eq("value") end it "applies before instance scope" do klass = test_report_class do - scope {Entry} + scope { Entry } dynamic do scope do |s| s.limit(1) @@ -184,8 +183,8 @@ class EqualTest end it "has access to grid attributes within scope" do - grid = test_report(name: 'one') do - scope {Entry} + grid = test_report(name: "one") do + scope { Entry } dynamic do scope do |s| s.where(name: name) @@ -193,58 +192,56 @@ class EqualTest end filter(:name, dummy: true) end - one = Entry.create!(name: 'one') - two = Entry.create!(name: 'two') + one = Entry.create!(name: "one") + two = Entry.create!(name: "two") expect(grid.assets).to include(one) expect(grid.assets).to_not include(two) end end describe "ActionController::Parameters" do - let(:params) do - ::ActionController::Parameters.new(name: 'one') + ::ActionController::Parameters.new(name: "one") end it "permites all attributes by default" do - expect { + expect do test_report(params) do scope { Entry } filter(:name) end - }.to_not raise_error + end.to_not raise_error end it "doesn't permit attributes when forbidden_attributes_protection is set" do - expect { + expect do test_report(params) do scope { Entry } self.forbidden_attributes_protection = true filter(:name) end - }.to raise_error(ActiveModel::ForbiddenAttributesError) + end.to raise_error(ActiveModel::ForbiddenAttributesError) end it "permits attributes when forbidden_attributes_protection is set and attributes are permitted" do - expect { + expect do test_report(params.permit!) do scope { Entry } self.forbidden_attributes_protection = true filter(:name) end - }.to_not raise_error + end.to_not raise_error end end - describe ".query_param" do it "works" do - grid = test_report(name: 'value') do - scope {Entry} + grid = test_report(name: "value") do + scope { Entry } filter(:name) def param_name - 'grid' + "grid" end end - expect(grid.query_params).to eq({grid: {name: 'value'}}) + expect(grid.query_params).to eq({ grid: { name: "value" } }) end end end diff --git a/spec/datagrid/drivers/active_record_spec.rb b/spec/datagrid/drivers/active_record_spec.rb index a3c418d..c41a1cf 100644 --- a/spec/datagrid/drivers/active_record_spec.rb +++ b/spec/datagrid/drivers/active_record_spec.rb @@ -1,13 +1,12 @@ -require 'spec_helper' +require "spec_helper" describe Datagrid::Drivers::ActiveRecord do - describe ".match?" do subject { described_class } - it {should be_match(Entry)} - it {should be_match(Entry.where(:id => 1))} - it {should_not be_match(MongoidEntry)} + it { should be_match(Entry) } + it { should be_match(Entry.where(id: 1)) } + it { should_not be_match(MongoidEntry) } end it "should convert any scope to AR::Relation" do @@ -17,13 +16,15 @@ end it "should support append_column_queries" do - scope = subject.append_column_queries(Entry.where({}), [Datagrid::Columns::Column.new(test_report_class, :sum_group_id, 'sum(entries.group_id)')]) + scope = subject.append_column_queries(Entry.where({}), + [Datagrid::Columns::Column.new(test_report_class, :sum_group_id, + "sum(entries.group_id)")]) expect(scope.to_sql.strip).to eq('SELECT "entries".*, sum(entries.group_id) AS sum_group_id FROM "entries"') end describe "Arel" do subject do - test_report(:order => :test, :descending => true) do + test_report(order: :test, descending: true) do scope { Entry } column(:test, order: Entry.arel_table[:group_id].count) end.assets @@ -35,45 +36,41 @@ end describe "gotcha #datagrid_where_by_timestamp" do - subject do test_report(created_at: 10.days.ago..5.days.ago) do - scope {Entry} + scope { Entry } - filter(:created_at, :date, range: true) do |value, scope, grid| + filter(:created_at, :date, range: true) do |value, scope, _grid| scope.joins(:group).datagrid_where_by_timestamp("groups.created_at", value) end end.assets end it "includes object created in proper range" do expect(subject).to include( - Entry.create!(group: Group.create!(created_at: 7.days.ago)), + Entry.create!(group: Group.create!(created_at: 7.days.ago)) ) end it "excludes object created before the range" do expect(subject).to_not include( - Entry.create!(created_at: 7.days.ago, group: Group.create!(created_at: 11.days.ago)), + Entry.create!(created_at: 7.days.ago, group: Group.create!(created_at: 11.days.ago)) ) end it "excludes object created after the range" do expect(subject).to_not include( - Entry.create!(created_at: 7.days.ago, group: Group.create!(created_at: 4.days.ago)), + Entry.create!(created_at: 7.days.ago, group: Group.create!(created_at: 4.days.ago)) ) end end describe "batches usage" do - it "should be incompatible with scope with limit" do report = test_report do - scope {Entry.limit(5)} + scope { Entry.limit(5) } self.batch_size = 20 column(:id) end expect { report.data }.to raise_error(Datagrid::ConfigurationError) end end - - end diff --git a/spec/datagrid/drivers/array_spec.rb b/spec/datagrid/drivers/array_spec.rb index 1a82a27..c0263f9 100644 --- a/spec/datagrid/drivers/array_spec.rb +++ b/spec/datagrid/drivers/array_spec.rb @@ -1,17 +1,15 @@ -require 'spec_helper' +require "spec_helper" describe Datagrid::Drivers::Array do - describe ".match?" do subject { described_class } - it {should be_match(Array.new)} - it {should be_match(ActiveRecord::Result.new([], []))} - it {should_not be_match({})} + it { should be_match([]) } + it { should be_match(ActiveRecord::Result.new([], [])) } + it { should_not be_match({}) } end describe "api" do - class ArrayGrid class User < Struct.new(:name, :age); end include Datagrid @@ -20,7 +18,7 @@ class User < Struct.new(:name, :age); end end filter(:name) - filter(:age, :integer, :range => true) + filter(:age, :integer, range: true) column(:name) column(:age) @@ -33,70 +31,66 @@ class User < Struct.new(:name, :age); end subject do ArrayGrid.new(_attributes).scope do - [ first, second, third ] + [first, second, third] end end - - describe '#assets' do + describe "#assets" do subject { super().assets } - describe '#size' do + describe "#size" do subject { super().size } - it {should == 3} + it { should == 3 } end end - describe '#rows' do + describe "#rows" do subject { super().rows } - it {should == [["Vasya", 15], ["Petya", 12], ["Vova", 13]]} + it { should == [["Vasya", 15], ["Petya", 12], ["Vova", 13]] } end - describe '#header' do + describe "#header" do subject { super().header } - it {should ==[ "Name", "Age"]} + it { should == %w[Name Age] } end - describe '#data' do + describe "#data" do subject { super().data } - it {should == [[ "Name", "Age"], ["Vasya", 15], ["Petya", 12], ["Vova", 13]]} + it { should == [%w[Name Age], ["Vasya", 15], ["Petya", 12], ["Vova", 13]] } end - describe "when some filters specified" do - let(:_attributes) { {:age => [12,14]} } + let(:_attributes) { { age: [12, 14] } } - describe '#assets' do + describe "#assets" do subject { super().assets } - it {should_not include(first)} + it { should_not include(first) } end - describe '#assets' do + describe "#assets" do subject { super().assets } - it {should include(second)} + it { should include(second) } end - describe '#assets' do + describe "#assets" do subject { super().assets } - it {should include(third)} + it { should include(third) } end end describe "when reverse ordering is specified" do - let(:_attributes) { {:order => :name, :descending => true} } + let(:_attributes) { { order: :name, descending: true } } - describe '#assets' do + describe "#assets" do subject { super().assets } - it {should == [third, first, second]} + it { should == [third, first, second] } end end - end describe "when using enumerator scope" do - it "should work fine" do grid = test_report(to_enum: true) do - scope {[]} + scope { [] } filter(:to_enum, :boolean) do |_, scope| scope.to_enum end @@ -109,11 +103,11 @@ class User < Struct.new(:name, :age); end class HashGrid include Datagrid scope do - [{name: 'Bogdan', age: 30}, {name: 'Brad', age: 32}] + [{ name: "Bogdan", age: 30 }, { name: "Brad", age: 32 }] end filter(:name) - filter(:age, :integer, :range => true) + filter(:age, :integer, range: true) column(:name) column(:age) @@ -126,9 +120,9 @@ class HashGrid end context "ordered" do - let(:_attributes) { { order: :name, descending: true }} + let(:_attributes) { { order: :name, descending: true } } - it { subject.assets.should == [ {name: 'Brad', age: 32}, {name: 'Bogdan', age: 30},] } + it { subject.assets.should == [{ name: "Brad", age: 32 }, { name: "Bogdan", age: 30 }] } end end end diff --git a/spec/datagrid/drivers/mongo_mapper_spec.rb b/spec/datagrid/drivers/mongo_mapper_spec.rb index ad6ee89..6cacf76 100644 --- a/spec/datagrid/drivers/mongo_mapper_spec.rb +++ b/spec/datagrid/drivers/mongo_mapper_spec.rb @@ -1,20 +1,16 @@ require "spec_helper" describe Datagrid::Drivers::MongoMapper, :mongomapper do - if defined?(MongoMapper) describe ".match?" do - subject { described_class } - it {should be_match(MongoMapperEntry)} + it { should be_match(MongoMapperEntry) } # MongoMapper doesn't have a scoped method, instead it has a query method which returns a Plucky::Query object - it {should be_match(MongoMapperEntry.query)} - it {should_not be_match(Entry.where(:id => 1))} - + it { should be_match(MongoMapperEntry.query) } + it { should_not be_match(Entry.where(id: 1)) } end describe "api" do - subject do MongoMapperGrid.new( defined?(_attributes) ? _attributes : {} @@ -23,79 +19,77 @@ let!(:first) do MongoMapperEntry.create!( - :group_id => 2, - :name => "Main First", - :disabled => false + group_id: 2, + name: "Main First", + disabled: false ) end let!(:second) do MongoMapperEntry.create!( - :group_id => 3, - :name => "Main Second", - :disabled => true + group_id: 3, + name: "Main Second", + disabled: true ) end - - describe '#assets' do + describe "#assets" do subject { super().assets } - it {should include(first, second)} + it { should include(first, second) } end - describe '#assets' do + describe "#assets" do subject { super().assets } - describe '#size' do + describe "#size" do subject { super().size } - it {should == 2} + it { should == 2 } end end - describe '#rows' do + describe "#rows" do subject { super().rows } - it {should == [["Main First", 2, false], ["Main Second", 3, true]]} + it { should == [["Main First", 2, false], ["Main Second", 3, true]] } end - describe '#header' do + describe "#header" do subject { super().header } - it {should ==[ "Name", "Group", "Disabled"]} + it { should == %w[Name Group Disabled] } end - describe '#data' do + describe "#data" do subject { super().data } - it {should == [[ "Name", "Group", "Disabled"], ["Main First", 2, false], ["Main Second", 3, true]]} + it { should == [["Name", "Group", "Disabled"], ["Main First", 2, false], ["Main Second", 3, true]] } end - describe "when some filters specified" do - let(:_attributes) { {group_id: [3, nil]} } + let(:_attributes) { { group_id: [3, nil] } } - describe '#assets' do + describe "#assets" do subject { super().assets } - it {should_not include(first)} + it { should_not include(first) } end - describe '#assets' do + describe "#assets" do subject { super().assets } - it {should include(second)} + it { should include(second) } end end describe "when reverse ordering is specified" do - let(:_attributes) { {:order => :name, :descending => true} } + let(:_attributes) { { order: :name, descending: true } } - describe '#rows' do + describe "#rows" do subject { super().rows } - it {should == [["Main Second", 3, true], ["Main First", 2, false]]} + it { should == [["Main Second", 3, true], ["Main First", 2, false]] } end end it "should not provide default order for non declared fields" do - expect { - test_report(:order => :test) do + expect do + test_report(order: :test) do scope { MongoMapperEntry } column(:test) - end.assets - }.to raise_error(Datagrid::OrderUnsupported) - end + end.assets + end.to raise_error(Datagrid::OrderUnsupported) end end end +end diff --git a/spec/datagrid/drivers/mongoid_spec.rb b/spec/datagrid/drivers/mongoid_spec.rb index 32108f5..b119951 100644 --- a/spec/datagrid/drivers/mongoid_spec.rb +++ b/spec/datagrid/drivers/mongoid_spec.rb @@ -1,18 +1,14 @@ require "spec_helper" describe Datagrid::Drivers::Mongoid, :mongoid do - describe ".match?" do - subject { described_class } - it {should be_match(MongoidEntry)} - it {should be_match(MongoidEntry.scoped)} - it {should_not be_match(Entry.where(:id => 1))} - + it { should be_match(MongoidEntry) } + it { should be_match(MongoidEntry.scoped) } + it { should_not be_match(Entry.where(id: 1)) } end describe "api" do - subject do MongoidGrid.new( defined?(_attributes) ? _attributes : {} @@ -21,79 +17,77 @@ let!(:first) do MongoidEntry.create!( - :group_id => 2, - :name => "Main First", - :disabled => false + group_id: 2, + name: "Main First", + disabled: false ) end let!(:second) do MongoidEntry.create!( - :group_id => 3, - :name => "Main Second", - :disabled => true + group_id: 3, + name: "Main Second", + disabled: true ) end - - describe '#assets' do + describe "#assets" do subject { super().assets } - it {should include(first, second)} + it { should include(first, second) } end - describe '#assets' do + describe "#assets" do subject { super().assets } - describe '#size' do + describe "#size" do subject { super().size } - it {should == 2} + it { should == 2 } end end - describe '#rows' do + describe "#rows" do subject { super().rows } - it {should == [["Main First", 2, false], ["Main Second", 3, true]]} + it { should == [["Main First", 2, false], ["Main Second", 3, true]] } end - describe '#header' do + describe "#header" do subject { super().header } - it {should ==[ "Name", "Group", "Disabled"]} + it { should == %w[Name Group Disabled] } end - describe '#data' do + describe "#data" do subject { super().data } - it {should == [[ "Name", "Group", "Disabled"], ["Main First", 2, false], ["Main Second", 3, true]]} + it { should == [["Name", "Group", "Disabled"], ["Main First", 2, false], ["Main Second", 3, true]] } end - describe "when some filters specified" do - let(:_attributes) { {group_id: [3, nil]} } + let(:_attributes) { { group_id: [3, nil] } } - describe '#assets' do + describe "#assets" do subject { super().assets.map(&:_id) } - it {should_not include(first.id)} + it { should_not include(first.id) } end - describe '#assets' do + describe "#assets" do subject { super().assets } - it {should include(second)} + it { should include(second) } end end describe "when reverse ordering is specified" do - let(:_attributes) { {:order => :name, :descending => true} } + let(:_attributes) { { order: :name, descending: true } } - describe '#rows' do + describe "#rows" do subject { super().rows } - it {should == [["Main Second", 3, true], ["Main First", 2, false]]} + it { should == [["Main Second", 3, true], ["Main First", 2, false]] } end end it "should not provide default order for non declared fields" do - expect { - test_report(:order => :test) do + expect do + test_report(order: :test) do scope { MongoidEntry } column(:test) end.assets - }.to raise_error(Datagrid::OrderUnsupported) + end.to raise_error(Datagrid::OrderUnsupported) end it "should support batch_size" do diff --git a/spec/datagrid/drivers/sequel_spec.rb b/spec/datagrid/drivers/sequel_spec.rb index 7e462b7..731b19d 100644 --- a/spec/datagrid/drivers/sequel_spec.rb +++ b/spec/datagrid/drivers/sequel_spec.rb @@ -1,18 +1,14 @@ -require 'spec_helper' +require "spec_helper" describe Datagrid::Drivers::Sequel do - describe ".match?" do - subject { described_class } - it {should be_match(SequelEntry)} - it {should be_match(SequelEntry.where(:id => 1))} - it {should_not be_match(Entry.where(:id => 1))} - + it { should be_match(SequelEntry) } + it { should be_match(SequelEntry.where(id: 1)) } + it { should_not be_match(Entry.where(id: 1)) } end describe "api" do - subject do SequelGrid.new( defined?(_attributes) ? _attributes : {} @@ -21,16 +17,16 @@ let!(:first) do SequelEntry.create( - :group_id => 2, - :name => "Main First", - :disabled => false + group_id: 2, + name: "Main First", + disabled: false ) end let!(:second) do SequelEntry.create( - :group_id => 3, - :name => "Main Second", - :disabled => true + group_id: 3, + name: "Main Second", + disabled: true ) end @@ -40,73 +36,72 @@ class PaginationTest scope { SequelEntry } end grid = PaginationTest.new do |scope| - scope.paginate(1,25) + scope.paginate(1, 25) end expect(grid.rows.to_a).to be_kind_of(Array) expect(grid.assets.to_a).to be_kind_of(Array) end - describe '#assets' do + describe "#assets" do subject { super().assets } - it {should include(first, second)} + it { should include(first, second) } end - describe '#assets' do + describe "#assets" do subject { super().assets } - describe '#size' do + describe "#size" do subject { super().count } - it {should == 2} + it { should == 2 } end end - describe '#rows' do + describe "#rows" do subject { super().rows } - it {should == [["Main First", 2, false], ["Main Second", 3, true]]} + it { should == [["Main First", 2, false], ["Main Second", 3, true]] } end - describe '#header' do + describe "#header" do subject { super().header } - it {should ==[ "Name", "Group", "Disabled"]} + it { should == %w[Name Group Disabled] } end - describe '#data' do + describe "#data" do subject { super().data } - it {should == [[ "Name", "Group", "Disabled"], ["Main First", 2, false], ["Main Second", 3, true]]} + it { should == [["Name", "Group", "Disabled"], ["Main First", 2, false], ["Main Second", 3, true]] } end - describe "when some filters specified" do - let(:_attributes) { {group_id: 3..100} } + let(:_attributes) { { group_id: 3..100 } } - describe '#assets' do + describe "#assets" do subject { super().assets.map(&:id) } - it {should_not include(first.id)} + it { should_not include(first.id) } end - describe '#assets' do + describe "#assets" do subject { super().assets } - it {should include(second)} + it { should include(second) } end end describe "when reverse ordering is specified" do - let(:_attributes) { {:order => :name, :descending => true} } + let(:_attributes) { { order: :name, descending: true } } - describe '#rows' do + describe "#rows" do subject { super().rows } - it {should == [["Main Second", 3, true], ["Main First", 2, false]]} + it { should == [["Main Second", 3, true], ["Main First", 2, false]] } end end it "should provide default order for non declared fields" do - expect { - test_report(:order => :test) do + expect do + test_report(order: :test) do scope { SequelEntry } column(:test) do - 'test' + "test" end end.assets - }.to raise_error(Datagrid::OrderUnsupported) + end.to raise_error(Datagrid::OrderUnsupported) end it "should support batch_size" do diff --git a/spec/datagrid/filters/base_filter_spec.rb b/spec/datagrid/filters/base_filter_spec.rb index 10acc2c..44160da 100644 --- a/spec/datagrid/filters/base_filter_spec.rb +++ b/spec/datagrid/filters/base_filter_spec.rb @@ -1,19 +1,16 @@ -require 'spec_helper' +require "spec_helper" describe Datagrid::Filters::BaseFilter do - - it "should support default option as block" do report = test_report do - scope {Entry} - filter(:name, :string, :default => :name_default) + scope { Entry } + filter(:name, :string, default: :name_default) def name_default - 'hello' + "hello" end end - expect(report.assets).to include(Entry.create!(:name => "hello")) - expect(report.assets).not_to include(Entry.create!(:name => "world")) - expect(report.assets).not_to include(Entry.create!(:name => "")) + expect(report.assets).to include(Entry.create!(name: "hello")) + expect(report.assets).not_to include(Entry.create!(name: "world")) + expect(report.assets).not_to include(Entry.create!(name: "")) end - end diff --git a/spec/datagrid/filters/composite_filters_spec.rb b/spec/datagrid/filters/composite_filters_spec.rb index 8bb10ae..b40e2a4 100644 --- a/spec/datagrid/filters/composite_filters_spec.rb +++ b/spec/datagrid/filters/composite_filters_spec.rb @@ -1,15 +1,13 @@ -require 'spec_helper' +require "spec_helper" describe Datagrid::Filters::CompositeFilters do - describe ".date_range_filters" do - it "should generate from date and to date filters" do - e1 = Entry.create!(:shipping_date => 6.days.ago) - e2 = Entry.create!(:shipping_date => 4.days.ago) - e3 = Entry.create!(:shipping_date => 1.days.ago) - assets = test_report(:from_shipping_date => 5.days.ago, :to_shipping_date => 2.day.ago) do - scope {Entry} + e1 = Entry.create!(shipping_date: 6.days.ago) + e2 = Entry.create!(shipping_date: 4.days.ago) + e3 = Entry.create!(shipping_date: 1.days.ago) + assets = test_report(from_shipping_date: 5.days.ago, to_shipping_date: 2.day.ago) do + scope { Entry } silence_warnings do date_range_filters(:shipping_date) end @@ -22,7 +20,7 @@ it "should support options" do report = test_report do silence_warnings do - date_range_filters(:shipping_date, {:default => 10.days.ago.to_date}, {:default => Date.today}) + date_range_filters(:shipping_date, { default: 10.days.ago.to_date }, { default: Date.today }) end end expect(report.from_shipping_date).to eq(10.days.ago.to_date) @@ -31,7 +29,7 @@ it "should support table name in field" do report = test_report do silence_warnings do - date_range_filters("entries.shipping_date", {:default => 10.days.ago.to_date}, {:default => Date.today}) + date_range_filters("entries.shipping_date", { default: 10.days.ago.to_date }, { default: Date.today }) end end expect(report.from_entries_shipping_date).to eq(10.days.ago.to_date) @@ -40,13 +38,12 @@ end describe ".integer_range_filters" do - it "should generate from integer and to integer filters" do - e1 = Entry.create!(:group_id => 1) - e2 = Entry.create!(:group_id => 3) - e3 = Entry.create!(:group_id => 5) - assets = test_report(:from_group_id => 2, :to_group_id => 4) do - scope {Entry} + e1 = Entry.create!(group_id: 1) + e2 = Entry.create!(group_id: 3) + e3 = Entry.create!(group_id: 5) + assets = test_report(from_group_id: 2, to_group_id: 4) do + scope { Entry } silence_warnings do integer_range_filters(:group_id) end @@ -58,7 +55,7 @@ it "should support options" do report = test_report do silence_warnings do - integer_range_filters(:group_id, {:default => 0}, {:default => 100}) + integer_range_filters(:group_id, { default: 0 }, { default: 100 }) end end expect(report.from_group_id).to eq(0) @@ -67,7 +64,7 @@ it "should table name in field name" do report = test_report do silence_warnings do - integer_range_filters("entries.group_id", {:default => 0}, {:default => 100}) + integer_range_filters("entries.group_id", { default: 0 }, { default: 100 }) end end expect(report.from_entries_group_id).to eq(0) diff --git a/spec/datagrid/filters/date_filter_spec.rb b/spec/datagrid/filters/date_filter_spec.rb index e459283..56fd5ce 100644 --- a/spec/datagrid/filters/date_filter_spec.rb +++ b/spec/datagrid/filters/date_filter_spec.rb @@ -1,8 +1,7 @@ -require 'spec_helper' +require "spec_helper" require "active_support/testing/time_helpers" describe Datagrid::Filters::DateFilter do - it "supports date range argument" do e1 = Entry.create!(created_at: 7.days.ago) e2 = Entry.create!(created_at: 4.days.ago) @@ -30,7 +29,7 @@ expect(report.assets).not_to include(e2) end - {active_record: Entry, mongoid: MongoidEntry, sequel: SequelEntry}.each do |orm, klass| + { active_record: Entry, mongoid: MongoidEntry, sequel: SequelEntry }.each do |orm, klass| describe "with orm #{orm}", orm => true do describe "date to timestamp conversion" do let(:klass) { klass } @@ -47,20 +46,20 @@ def entry_dated(date) context "when single date paramter given" do let(:_created_at) { Date.today } - it { should include(entry_dated(1.second.ago))} - it { should include(entry_dated(Date.today.end_of_day))} - it { should_not include(entry_dated(Date.today.beginning_of_day - 1.second))} - it { should_not include(entry_dated(Date.today.end_of_day + 1.second))} + it { should include(entry_dated(1.second.ago)) } + it { should include(entry_dated(Date.today.end_of_day)) } + it { should_not include(entry_dated(Date.today.beginning_of_day - 1.second)) } + it { should_not include(entry_dated(Date.today.end_of_day + 1.second)) } end context "when range date range given" do let(:_created_at) { [Date.yesterday, Date.today] } - it { should include(entry_dated(1.second.ago))} - it { should include(entry_dated(1.day.ago))} - it { should include(entry_dated(Date.today.end_of_day))} - it { should include(entry_dated(Date.yesterday.beginning_of_day))} - it { should_not include(entry_dated(Date.yesterday.beginning_of_day - 1.second))} - it { should_not include(entry_dated(Date.today.end_of_day + 1.second))} + it { should include(entry_dated(1.second.ago)) } + it { should include(entry_dated(1.day.ago)) } + it { should include(entry_dated(Date.today.end_of_day)) } + it { should include(entry_dated(Date.yesterday.beginning_of_day)) } + it { should_not include(entry_dated(Date.yesterday.beginning_of_day - 1.second)) } + it { should_not include(entry_dated(Date.today.end_of_day + 1.second)) } end end end @@ -106,7 +105,6 @@ def entry_dated(date) end it "should find something in one day interval" do - e1 = Entry.create!(created_at: 7.days.ago) e2 = Entry.create!(created_at: 4.days.ago) e3 = Entry.create!(created_at: 1.day.ago) @@ -134,10 +132,9 @@ def entry_dated(date) expect(report.assets).to include(e3) end - it "should support block" do - date = Date.new(2018, 01, 07) - time = Time.utc(2018, 01, 07, 2, 2) + date = Date.new(2018, 0o1, 0o7) + time = Time.utc(2018, 0o1, 0o7, 2, 2) report = test_report(created_at: date) do scope { Entry } filter(:created_at, :date, range: true) do |value| @@ -148,7 +145,6 @@ def entry_dated(date) expect(report.assets).to include(Entry.create!(created_at: time)) end - context "when date format is configured" do around(:each) do |example| with_date_format do @@ -158,40 +154,39 @@ def entry_dated(date) it "should have configurable date format" do report = test_report(created_at: "10/01/2013") do - scope {Entry} + scope { Entry } filter(:created_at, :date) end - expect(report.created_at).to eq(Date.new(2013,10,01)) + expect(report.created_at).to eq(Date.new(2013, 10, 0o1)) end it "should support default explicit date" do report = test_report(created_at: Date.parse("2013-10-01")) do - scope {Entry} + scope { Entry } filter(:created_at, :date) end - expect(report.created_at).to eq(Date.new(2013,10,01)) + expect(report.created_at).to eq(Date.new(2013, 10, 0o1)) end end - it "should automatically reverse Array if first more than last" do - report = test_report(created_at: ["2013-01-01", "2012-01-01"]) do - scope {Entry} + report = test_report(created_at: %w[2013-01-01 2012-01-01]) do + scope { Entry } filter(:created_at, :date, range: true) end - expect(report.created_at).to eq([Date.new(2012, 01, 01), Date.new(2013, 01, 01)]) + expect(report.created_at).to eq([Date.new(2012, 0o1, 0o1), Date.new(2013, 0o1, 0o1)]) end it "should automatically reverse Array if first more than last" do - report = test_report(created_at: ["2013-01-01", "2012-01-01"]) do - scope {Entry} + report = test_report(created_at: %w[2013-01-01 2012-01-01]) do + scope { Entry } filter(:created_at, :date, range: true) end - expect(report.created_at).to eq([Date.new(2012, 01, 01), Date.new(2013, 01, 01)]) + expect(report.created_at).to eq([Date.new(2012, 0o1, 0o1), Date.new(2013, 0o1, 0o1)]) end it "should nullify blank range" do report = test_report(created_at: [nil, nil]) do - scope {Entry} + scope { Entry } filter(:created_at, :date, range: true) end @@ -201,11 +196,10 @@ def entry_dated(date) it "should properly format date in filter_value_as_string" do with_date_format do report = test_report(created_at: "2012-01-02") do - scope {Entry} + scope { Entry } filter(:created_at, :date) end expect(report.filter_value_as_string(:created_at)).to eq("01/02/2012") end end - end diff --git a/spec/datagrid/filters/date_time_filter_spec.rb b/spec/datagrid/filters/date_time_filter_spec.rb index 41c833c..425b442 100644 --- a/spec/datagrid/filters/date_time_filter_spec.rb +++ b/spec/datagrid/filters/date_time_filter_spec.rb @@ -1,7 +1,7 @@ -require 'spec_helper' +require "spec_helper" describe Datagrid::Filters::DateTimeFilter do - {:active_record => Entry, :mongoid => MongoidEntry}.each do |orm, klass| + { active_record: Entry, mongoid: MongoidEntry }.each do |orm, klass| describe "with orm #{orm}", orm => true do describe "timestamp to timestamp conversion" do let(:klass) { klass } @@ -24,38 +24,37 @@ def entry_dated(date) context "with single datetime paramter given" do let(:_created_at) { Time.now.change(sec: 0) } it { should include(entry_dated(_created_at)) } - it { should_not include(entry_dated(_created_at - 1.second))} - it { should_not include(entry_dated(_created_at + 1.second))} + it { should_not include(entry_dated(_created_at - 1.second)) } + it { should_not include(entry_dated(_created_at + 1.second)) } end context "with range datetime range given" do let(:_created_at) { [Time.now.beginning_of_day, Time.now.end_of_day] } - it { should include(entry_dated(1.second.ago))} - it { should include(entry_dated(Date.today.to_time))} - it { should include(entry_dated(Time.now.end_of_day.to_time))} - it { should_not include(entry_dated(Date.yesterday.end_of_day))} - it { should_not include(entry_dated(Date.tomorrow.beginning_of_day))} + it { should include(entry_dated(1.second.ago)) } + it { should include(entry_dated(Date.today.to_time)) } + it { should include(entry_dated(Time.now.end_of_day.to_time)) } + it { should_not include(entry_dated(Date.yesterday.end_of_day)) } + it { should_not include(entry_dated(Date.tomorrow.beginning_of_day)) } end context "with right open range" do let(:_created_at) { Time.now.beginning_of_day..nil } - it { should include(entry_dated(1.second.ago))} - it { should include(entry_dated(Date.today.to_time))} - it { should include(entry_dated(Time.now.end_of_day.to_time))} - it { should include(entry_dated(Date.tomorrow.beginning_of_day))} - it { should_not include(entry_dated(Date.yesterday.end_of_day))} + it { should include(entry_dated(1.second.ago)) } + it { should include(entry_dated(Date.today.to_time)) } + it { should include(entry_dated(Time.now.end_of_day.to_time)) } + it { should include(entry_dated(Date.tomorrow.beginning_of_day)) } + it { should_not include(entry_dated(Date.yesterday.end_of_day)) } end context "with left open range" do let(:_created_at) { nil..Time.now.end_of_day } - it { should include(entry_dated(1.second.ago))} - it { should include(entry_dated(Date.today.to_time))} - it { should include(entry_dated(Time.now.end_of_day.to_time))} - it { should include(entry_dated(Date.yesterday.end_of_day))} - it { should_not include(entry_dated(Date.tomorrow.beginning_of_day))} + it { should include(entry_dated(1.second.ago)) } + it { should include(entry_dated(Date.today.to_time)) } + it { should include(entry_dated(Time.now.end_of_day.to_time)) } + it { should include(entry_dated(Date.yesterday.end_of_day)) } + it { should_not include(entry_dated(Date.tomorrow.beginning_of_day)) } end end - end end @@ -126,7 +125,6 @@ def entry_dated(date) expect(report.assets).to include(e3) end - it "should support block" do report = test_report(created_at: Time.now) do scope { Entry } @@ -135,10 +133,9 @@ def entry_dated(date) end end expect(report.assets).not_to include(Entry.create!(created_at: 1.day.ago)) - expect(report.assets).to include(Entry.create!(created_at: Time.now+1.day)) + expect(report.assets).to include(Entry.create!(created_at: Time.now + 1.day)) end - context "when datetime format is configured" do around(:each) do |example| with_datetime_format("%m/%d/%Y %H:%M") do @@ -148,27 +145,26 @@ def entry_dated(date) it "should have configurable datetime format" do report = test_report(created_at: "10/01/2013 01:00") do - scope {Entry} + scope { Entry } filter(:created_at, :datetime) end - expect(report.created_at).to eq(Time.new(2013,10,01,1,0)) + expect(report.created_at).to eq(Time.new(2013, 10, 0o1, 1, 0)) end it "should support default explicit datetime" do report = test_report(created_at: Time.parse("2013-10-01 01:00")) do - scope {Entry} + scope { Entry } filter(:created_at, :datetime) end - expect(report.created_at).to eq(Time.new(2013,10,01,1,0)) + expect(report.created_at).to eq(Time.new(2013, 10, 0o1, 1, 0)) end end - it "should automatically reverse Array if first more than last" do report = test_report(created_at: ["2013-01-01 01:00", "2012-01-01 01:00"]) do - scope {Entry} + scope { Entry } filter(:created_at, :datetime, range: true) end - expect(report.created_at).to eq([Time.new(2012, 01, 01, 1, 0), Time.new(2013, 01, 01, 1, 0)]) + expect(report.created_at).to eq([Time.new(2012, 0o1, 0o1, 1, 0), Time.new(2013, 0o1, 0o1, 1, 0)]) end end diff --git a/spec/datagrid/filters/dynamic_filter_spec.rb b/spec/datagrid/filters/dynamic_filter_spec.rb index da6a052..6bbfa7c 100644 --- a/spec/datagrid/filters/dynamic_filter_spec.rb +++ b/spec/datagrid/filters/dynamic_filter_spec.rb @@ -1,128 +1,128 @@ require "spec_helper" - describe Datagrid::Filters::DynamicFilter do let(:report) do test_report do - scope {Entry} + scope { Entry } filter(:condition, :dynamic) end end it "should support = operation" do report.condition = [:name, "=", "hello"] - expect(report.assets).to include(Entry.create!(:name => 'hello')) - expect(report.assets).not_to include(Entry.create!(:name => 'bye')) + expect(report.assets).to include(Entry.create!(name: "hello")) + expect(report.assets).not_to include(Entry.create!(name: "bye")) end it "should support >= operation" do report.condition = [:name, ">=", "d"] - expect(report.assets).to include(Entry.create!(:name => 'x')) - expect(report.assets).to include(Entry.create!(:name => 'd')) - expect(report.assets).not_to include(Entry.create!(:name => 'a')) + expect(report.assets).to include(Entry.create!(name: "x")) + expect(report.assets).to include(Entry.create!(name: "d")) + expect(report.assets).not_to include(Entry.create!(name: "a")) end it "should blank value" do report.condition = [:name, "=", ""] - expect(report.assets).to include(Entry.create!(:name => 'hello')) + expect(report.assets).to include(Entry.create!(name: "hello")) end it "should support =~ operation on strings" do report.condition = [:name, "=~", "ell"] - expect(report.assets).to include(Entry.create!(:name => 'hello')) - expect(report.assets).not_to include(Entry.create!(:name => 'bye')) + expect(report.assets).to include(Entry.create!(name: "hello")) + expect(report.assets).not_to include(Entry.create!(name: "bye")) end it "should support =~ operation integers" do report.condition = [:group_id, "=~", 2] - expect(report.assets).to include(Entry.create!(:group_id => 2)) - expect(report.assets).not_to include(Entry.create!(:group_id => 1)) - expect(report.assets).not_to include(Entry.create!(:group_id => 3)) + expect(report.assets).to include(Entry.create!(group_id: 2)) + expect(report.assets).not_to include(Entry.create!(group_id: 1)) + expect(report.assets).not_to include(Entry.create!(group_id: 3)) end it "should support >= operation on integer" do report.condition = [:group_id, ">=", 2] - expect(report.assets).to include(Entry.create!(:group_id => 3)) - expect(report.assets).not_to include(Entry.create!(:group_id => 1)) + expect(report.assets).to include(Entry.create!(group_id: 3)) + expect(report.assets).not_to include(Entry.create!(group_id: 1)) end it "should support <= operation on integer" do report.condition = [:group_id, "<=", 2] - expect(report.assets).to include(Entry.create!(:group_id => 1)) - expect(report.assets).not_to include(Entry.create!(:group_id => 3)) + expect(report.assets).to include(Entry.create!(group_id: 1)) + expect(report.assets).not_to include(Entry.create!(group_id: 3)) end it "should support <= operation on integer with string value" do - report.condition = [:group_id, "<=", '2'] - expect(report.assets).to include(Entry.create!(:group_id => 1)) - expect(report.assets).to include(Entry.create!(:group_id => 2)) - expect(report.assets).not_to include(Entry.create!(:group_id => 3)) + report.condition = [:group_id, "<=", "2"] + expect(report.assets).to include(Entry.create!(group_id: 1)) + expect(report.assets).to include(Entry.create!(group_id: 2)) + expect(report.assets).not_to include(Entry.create!(group_id: 3)) end it "should nullify incorrect value for integer" do - report.condition = [:group_id, "<=", 'aa'] + report.condition = [:group_id, "<=", "aa"] expect(report.condition).to eq([:group_id, "<=", nil]) end it "should nullify incorrect value for date" do - report.condition = [:shipping_date, "<=", 'aa'] + report.condition = [:shipping_date, "<=", "aa"] expect(report.condition).to eq([:shipping_date, "<=", nil]) end it "should nullify incorrect value for datetime" do - report.condition = [:created_at, "<=", 'aa'] + report.condition = [:created_at, "<=", "aa"] expect(report.condition).to eq([:created_at, "<=", nil]) end it "should support date comparation operation by timestamp column" do - report.condition = [:created_at, "<=", '1986-08-05'] - expect(report.condition).to eq([:created_at, "<=", Date.parse('1986-08-05')]) - expect(report.assets).to include(Entry.create!(:created_at => Time.parse('1986-08-04 01:01:01'))) - expect(report.assets).to include(Entry.create!(:created_at => Time.parse('1986-08-05 23:59:59'))) - expect(report.assets).to include(Entry.create!(:created_at => Time.parse('1986-08-05 00:00:00'))) - expect(report.assets).not_to include(Entry.create!(:created_at => Time.parse('1986-08-06 00:00:00'))) - expect(report.assets).not_to include(Entry.create!(:created_at => Time.parse('1986-08-06 23:59:59'))) + report.condition = [:created_at, "<=", "1986-08-05"] + expect(report.condition).to eq([:created_at, "<=", Date.parse("1986-08-05")]) + expect(report.assets).to include(Entry.create!(created_at: Time.parse("1986-08-04 01:01:01"))) + expect(report.assets).to include(Entry.create!(created_at: Time.parse("1986-08-05 23:59:59"))) + expect(report.assets).to include(Entry.create!(created_at: Time.parse("1986-08-05 00:00:00"))) + expect(report.assets).not_to include(Entry.create!(created_at: Time.parse("1986-08-06 00:00:00"))) + expect(report.assets).not_to include(Entry.create!(created_at: Time.parse("1986-08-06 23:59:59"))) end it "should support date = operation by timestamp column" do - report.condition = [:created_at, "=", '1986-08-05'] - expect(report.condition).to eq([:created_at, "=", Date.parse('1986-08-05')]) - expect(report.assets).not_to include(Entry.create!(:created_at => Time.parse('1986-08-04 23:59:59'))) - expect(report.assets).to include(Entry.create!(:created_at => Time.parse('1986-08-05 23:59:59'))) - expect(report.assets).to include(Entry.create!(:created_at => Time.parse('1986-08-05 00:00:01'))) - #TODO: investigate SQLite issue and uncomment this line - #report.assets.should include(Entry.create!(:created_at => Time.parse('1986-08-05 00:00:00'))) - expect(report.assets).not_to include(Entry.create!(:created_at => Time.parse('1986-08-06 23:59:59'))) + report.condition = [:created_at, "=", "1986-08-05"] + expect(report.condition).to eq([:created_at, "=", Date.parse("1986-08-05")]) + expect(report.assets).not_to include(Entry.create!(created_at: Time.parse("1986-08-04 23:59:59"))) + expect(report.assets).to include(Entry.create!(created_at: Time.parse("1986-08-05 23:59:59"))) + expect(report.assets).to include(Entry.create!(created_at: Time.parse("1986-08-05 00:00:01"))) + # TODO: investigate SQLite issue and uncomment this line + # report.assets.should include(Entry.create!(:created_at => Time.parse('1986-08-05 00:00:00'))) + expect(report.assets).not_to include(Entry.create!(created_at: Time.parse("1986-08-06 23:59:59"))) end it "should support date =~ operation by timestamp column" do - report.condition = [:created_at, "=~", '1986-08-05'] - expect(report.condition).to eq([:created_at, "=~", Date.parse('1986-08-05')]) - expect(report.assets).not_to include(Entry.create!(:created_at => Time.parse('1986-08-04 23:59:59'))) - expect(report.assets).to include(Entry.create!(:created_at => Time.parse('1986-08-05 23:59:59'))) - expect(report.assets).to include(Entry.create!(:created_at => Time.parse('1986-08-05 00:00:01'))) - #TODO: investigate SQLite issue and uncomment this line - #report.assets.should include(Entry.create!(:created_at => Time.parse('1986-08-05 00:00:00'))) - expect(report.assets).not_to include(Entry.create!(:created_at => Time.parse('1986-08-06 23:59:59'))) + report.condition = [:created_at, "=~", "1986-08-05"] + expect(report.condition).to eq([:created_at, "=~", Date.parse("1986-08-05")]) + expect(report.assets).not_to include(Entry.create!(created_at: Time.parse("1986-08-04 23:59:59"))) + expect(report.assets).to include(Entry.create!(created_at: Time.parse("1986-08-05 23:59:59"))) + expect(report.assets).to include(Entry.create!(created_at: Time.parse("1986-08-05 00:00:01"))) + # TODO: investigate SQLite issue and uncomment this line + # report.assets.should include(Entry.create!(:created_at => Time.parse('1986-08-05 00:00:00'))) + expect(report.assets).not_to include(Entry.create!(created_at: Time.parse("1986-08-06 23:59:59"))) end it "should support operations for invalid date" do - report.condition = [:shipping_date, "<=", '1986-08-05'] - expect(report.assets).to include(Entry.create!(:shipping_date => '1986-08-04')) - expect(report.assets).to include(Entry.create!(:shipping_date => '1986-08-05')) - expect(report.assets).not_to include(Entry.create!(:shipping_date => '1986-08-06')) + report.condition = [:shipping_date, "<=", "1986-08-05"] + expect(report.assets).to include(Entry.create!(shipping_date: "1986-08-04")) + expect(report.assets).to include(Entry.create!(shipping_date: "1986-08-05")) + expect(report.assets).not_to include(Entry.create!(shipping_date: "1986-08-06")) end it "should support operations for invalid date" do - report.condition = [:shipping_date, "<=", Date.parse('1986-08-05')] - expect(report.assets).to include(Entry.create!(:shipping_date => '1986-08-04')) - expect(report.assets).to include(Entry.create!(:shipping_date => '1986-08-05')) - expect(report.assets).not_to include(Entry.create!(:shipping_date => '1986-08-06')) + report.condition = [:shipping_date, "<=", Date.parse("1986-08-05")] + expect(report.assets).to include(Entry.create!(shipping_date: "1986-08-04")) + expect(report.assets).to include(Entry.create!(shipping_date: "1986-08-05")) + expect(report.assets).not_to include(Entry.create!(shipping_date: "1986-08-06")) end it "should support allow_nil and allow_blank options" do grid = test_report do - scope {Entry} - filter(:condition, :dynamic, :allow_nil => true, :allow_blank => true, operations: ['>=', '<=']) do |(field, operation, value), scope| + scope { Entry } + filter(:condition, :dynamic, allow_nil: true, allow_blank: true, + operations: [">=", "<="]) do |(field, operation, value), scope| if value.blank? scope.where(disabled: false) else @@ -134,16 +134,16 @@ expect(grid.assets).to_not include(Entry.create!(disabled: true)) expect(grid.assets).to include(Entry.create!(disabled: false)) - grid.condition = [:group_id, '>=', 3] + grid.condition = [:group_id, ">=", 3] expect(grid.assets).to include(Entry.create!(disabled: true, group_id: 4)) expect(grid.assets).to_not include(Entry.create!(disabled: false, group_id: 2)) end it "should support custom operations" do - entry = Entry.create!(name: 'hello') + entry = Entry.create!(name: "hello") grid = test_report do - scope {Entry} + scope { Entry } filter( :condition, :dynamic, operations: ["=", "!="] ) do |(field, operation, value), scope| @@ -166,10 +166,9 @@ end it "should raise if unknown operation" do - report.condition = [:shipping_date, "<>", '1996-08-05'] - expect{ + report.condition = [:shipping_date, "<>", "1996-08-05"] + expect do report.assets - }.to raise_error(Datagrid::FilteringError) + end.to raise_error(Datagrid::FilteringError) end - end diff --git a/spec/datagrid/filters/enum_filter_spec.rb b/spec/datagrid/filters/enum_filter_spec.rb index 5b60348..7192614 100644 --- a/spec/datagrid/filters/enum_filter_spec.rb +++ b/spec/datagrid/filters/enum_filter_spec.rb @@ -1,28 +1,27 @@ -require 'spec_helper' +require "spec_helper" describe Datagrid::Filters::EnumFilter do - it "should support select option" do report = test_report do - scope {Entry} - filter(:group_id, :enum, :select => [1,2] ) + scope { Entry } + filter(:group_id, :enum, select: [1, 2]) end - expect(report.filter_by_name(:group_id).select(report)).to eq([1,2]) + expect(report.filter_by_name(:group_id).select(report)).to eq([1, 2]) end it "should support select option as proc" do grid = test_report do - scope {Entry} - filter(:group_id, :enum, :select => proc { [1,2] }) + scope { Entry } + filter(:group_id, :enum, select: proc { [1, 2] }) end - expect(grid.filter_by_name(:group_id).select(grid)).to eq([1,2]) + expect(grid.filter_by_name(:group_id).select(grid)).to eq([1, 2]) end it "should support select option as proc with instace input" do klass = test_report do - scope {Entry} - filter(:group_id, :enum, :select => proc { |obj| obj.object_id }) - end.class + scope { Entry } + filter(:group_id, :enum, select: proc { |obj| obj.object_id }) + end.class instance = klass.new expect(klass.filter_by_name(:group_id).select(instance)).to eq(instance.object_id) end @@ -30,22 +29,20 @@ it "should initialize select option only on instanciation" do class ReportWithLazySelect include Datagrid - scope {Entry} - filter(:group_id, :enum, :select => proc { raise 'hello' }) + scope { Entry } + filter(:group_id, :enum, select: proc { raise "hello" }) end end - it "should support select given as symbol" do report = test_report do - scope {Entry} - filter(:group_id, :enum, :select => :selectable_group_ids) + scope { Entry } + filter(:group_id, :enum, select: :selectable_group_ids) def selectable_group_ids - [1,3,5] + [1, 3, 5] end end - expect(report.filter_by_name(:group_id).select(report)).to eq([1,3,5]) + expect(report.filter_by_name(:group_id).select(report)).to eq([1, 3, 5]) end - end diff --git a/spec/datagrid/filters/extended_boolean_filter_spec.rb b/spec/datagrid/filters/extended_boolean_filter_spec.rb index 22e36e5..ebff604 100644 --- a/spec/datagrid/filters/extended_boolean_filter_spec.rb +++ b/spec/datagrid/filters/extended_boolean_filter_spec.rb @@ -1,23 +1,22 @@ -require 'spec_helper' +require "spec_helper" describe Datagrid::Filters::ExtendedBooleanFilter do - it "should support select option" do grid = test_report do - scope {Entry} + scope { Entry } filter(:disabled, :xboolean) end - expect(grid.filter_by_name(:disabled).select(grid)).to eq([["Yes", "YES"], ["No", "NO"]]) + expect(grid.filter_by_name(:disabled).select(grid)).to eq([%w[Yes YES], %w[No NO]]) end it "should generate pass boolean value to filter block" do grid = test_report do - scope {Entry} + scope { Entry } filter(:disabled, :xboolean) end - disabled_entry = Entry.create!(:disabled => true) - enabled_entry = Entry.create!(:disabled => false) + disabled_entry = Entry.create!(disabled: true) + enabled_entry = Entry.create!(disabled: false) expect(grid.disabled).to be_nil expect(grid.assets).to include(disabled_entry, enabled_entry) @@ -34,7 +33,7 @@ it "should normalize true/false as YES/NO" do grid = test_report do - scope {Entry} + scope { Entry } filter(:disabled, :xboolean) end grid.disabled = true @@ -46,5 +45,4 @@ grid.disabled = "false" expect(grid.disabled).to eq("NO") end - end diff --git a/spec/datagrid/filters/float_filter_spec.rb b/spec/datagrid/filters/float_filter_spec.rb index a745355..131cdd0 100644 --- a/spec/datagrid/filters/float_filter_spec.rb +++ b/spec/datagrid/filters/float_filter_spec.rb @@ -1,11 +1,10 @@ -require 'spec_helper' +require "spec_helper" describe Datagrid::Filters::FloatFilter do - it "should support float values" do - g1 = Group.create!(:rating => 1.5) - g2 = Group.create!(:rating => 1.6) - report = test_report(:rating => 1.5) do + g1 = Group.create!(rating: 1.5) + g2 = Group.create!(rating: 1.6) + report = test_report(rating: 1.5) do scope { Group } filter(:rating, :float) end diff --git a/spec/datagrid/filters/integer_filter_spec.rb b/spec/datagrid/filters/integer_filter_spec.rb index 5d5a9f2..a7f1855 100644 --- a/spec/datagrid/filters/integer_filter_spec.rb +++ b/spec/datagrid/filters/integer_filter_spec.rb @@ -1,7 +1,6 @@ -require 'spec_helper' +require "spec_helper" describe Datagrid::Filters::IntegerFilter do - let(:entry1) { Entry.create!(group_id: 1) } let(:entry2) { Entry.create!(group_id: 2) } let(:entry3) { Entry.create!(group_id: 3) } @@ -58,7 +57,6 @@ end it "should find something in one integer interval" do - report = test_report(group_id: (4..4)) do scope { Entry } filter(:group_id, :integer, range: true) @@ -69,18 +67,16 @@ end it "should support invalid range" do - report = test_report(group_id: (7..1)) do scope { Entry } filter(:group_id, :integer, range: true) end - expect(report.group_id).to eq([1,7]) + expect(report.group_id).to eq([1, 7]) expect(report.assets).to include(entry7) expect(report.assets).to include(entry4) expect(report.assets).to include(entry1) end - it "should support block" do report = test_report(group_id: 5) do scope { Entry } @@ -92,42 +88,41 @@ expect(report.assets).to include(entry5) end - it "should not prefix table name if column is joined" do - report = test_report(rating: [4,nil]) do + report = test_report(rating: [4, nil]) do scope { Entry.joins(:group) } filter(:rating, :integer, range: true) end - expect(report.rating).to eq([4,nil]) + expect(report.rating).to eq([4, nil]) expect(report.assets).not_to include(Entry.create!(group: Group.create!(rating: 3))) expect(report.assets).to include(Entry.create!(group: Group.create!(rating: 5))) end it "should support multiple values" do report = test_report(group_id: "1,2") do - scope {Entry} + scope { Entry } filter(:group_id, :integer, multiple: true) end - expect(report.group_id).to eq([1,2]) + expect(report.group_id).to eq([1, 2]) expect(report.assets).to include(entry1) expect(report.assets).to include(entry2) expect(report.assets).not_to include(entry3) end it "should support custom separator multiple values" do report = test_report(group_id: "1|2") do - scope {Entry} - filter(:group_id, :integer, multiple: '|') + scope { Entry } + filter(:group_id, :integer, multiple: "|") end - expect(report.group_id).to eq([1,2]) + expect(report.group_id).to eq([1, 2]) expect(report.assets).to include(entry1) expect(report.assets).to include(entry2) expect(report.assets).not_to include(entry3) end it "should support multiple with allow_blank allow_nil options" do - report = test_report do - scope {Entry} - filter(:group_id, :integer, multiple: true, allow_nil: false, allow_blank: true ) + report = test_report do + scope { Entry } + filter(:group_id, :integer, multiple: true, allow_nil: false, allow_blank: true) end report.group_id = [] expect(report.assets).to_not include(entry1) @@ -143,7 +138,7 @@ it "normalizes AR object to ID" do group = Group.create! report = test_report(group_id: group) do - scope {Entry} + scope { Entry } filter(:group_id, :integer) end diff --git a/spec/datagrid/filters/string_filter_spec.rb b/spec/datagrid/filters/string_filter_spec.rb index 63b702f..8e84de3 100644 --- a/spec/datagrid/filters/string_filter_spec.rb +++ b/spec/datagrid/filters/string_filter_spec.rb @@ -1,35 +1,34 @@ require "spec_helper" describe Datagrid::Filters::StringFilter do - it "should support multiple values" do - report = test_report(:name => "one,two") do - scope {Entry} - filter(:name, :string, :multiple => true) + report = test_report(name: "one,two") do + scope { Entry } + filter(:name, :string, multiple: true) end - expect(report.assets).to include(Entry.create!( :name => "one")) - expect(report.assets).to include(Entry.create!( :name => "two")) - expect(report.assets).not_to include(Entry.create!( :name => "three")) + expect(report.assets).to include(Entry.create!(name: "one")) + expect(report.assets).to include(Entry.create!(name: "two")) + expect(report.assets).not_to include(Entry.create!(name: "three")) end it "should support custom separator multiple values" do - report = test_report(:name => "one,1|two,2") do - scope {Entry} - filter(:name, :string, :multiple => '|') + report = test_report(name: "one,1|two,2") do + scope { Entry } + filter(:name, :string, multiple: "|") end - expect(report.assets).to include(Entry.create!( :name => "one,1")) - expect(report.assets).to include(Entry.create!( :name => "two,2")) - expect(report.assets).not_to include(Entry.create!( :name => "one")) - expect(report.assets).not_to include(Entry.create!( :name => "two")) + expect(report.assets).to include(Entry.create!(name: "one,1")) + expect(report.assets).to include(Entry.create!(name: "two,2")) + expect(report.assets).not_to include(Entry.create!(name: "one")) + expect(report.assets).not_to include(Entry.create!(name: "two")) end it "supports range" do - report = test_report(:name => ['ab', 'lm']) do - scope {Entry} + report = test_report(name: %w[ab lm]) do + scope { Entry } filter(:name, :string, range: true) end - expect(report.assets).to include(Entry.create!( :name => "ac")) - expect(report.assets).to include(Entry.create!( :name => "kl")) - expect(report.assets).not_to include(Entry.create!( :name => "aa")) - expect(report.assets).not_to include(Entry.create!( :name => "mn")) + expect(report.assets).to include(Entry.create!(name: "ac")) + expect(report.assets).to include(Entry.create!(name: "kl")) + expect(report.assets).not_to include(Entry.create!(name: "aa")) + expect(report.assets).not_to include(Entry.create!(name: "mn")) end end diff --git a/spec/datagrid/filters_spec.rb b/spec/datagrid/filters_spec.rb index 9f9325a..91614dc 100644 --- a/spec/datagrid/filters_spec.rb +++ b/spec/datagrid/filters_spec.rb @@ -1,65 +1,63 @@ -require 'spec_helper' +require "spec_helper" describe Datagrid::Filters do - it "should support default option as proc" do expect(test_report do - scope {Entry} - filter(:created_at, :date, :default => proc { Date.today } ) + scope { Entry } + filter(:created_at, :date, default: proc { Date.today }) end.created_at).to eq(Date.today) end it "should stack with other filters" do - Entry.create(:name => "ZZ", :category => "first") - report = test_report(:name => "Pop", :category => "first") do + Entry.create(name: "ZZ", category: "first") + report = test_report(name: "Pop", category: "first") do scope { Entry } filter(:name) - filter(:category, :enum, :select => ["first", "second"]) + filter(:category, :enum, select: %w[first second]) end expect(report.assets).to be_empty end it "should not support array argument for not multiple filter" do report = test_report do - scope {Entry} + scope { Entry } filter(:group_id, :integer) end - expect { - report.group_id = [1,2] - }.to raise_error(Datagrid::ArgumentError) + expect do + report.group_id = [1, 2] + end.to raise_error(Datagrid::ArgumentError) end it "should filter block with 2 arguments" do report = test_report do - scope {Entry} + scope { Entry } filter(:group_id, :integer) do |value, scope| - scope.where(:group_id => value) + scope.where(group_id: value) end end - expect { - report.group_id = [1,2] - }.to raise_error(Datagrid::ArgumentError) + expect do + report.group_id = [1, 2] + end.to raise_error(Datagrid::ArgumentError) end - it "should initialize when report Scope table not exists" do class ModelWithoutTable < ActiveRecord::Base; end expect(ModelWithoutTable).not_to be_table_exists class TheReport include Datagrid - scope {ModelWithoutTable} + scope { ModelWithoutTable } filter(:name) filter(:limit) end - expect(TheReport.new(:name => 'hello')).not_to be_nil + expect(TheReport.new(name: "hello")).not_to be_nil end it "should support inheritence" do parent = Class.new do include Datagrid - scope {Entry} + scope { Entry } filter(:name) end child = Class.new(parent) do @@ -70,11 +68,10 @@ class TheReport end describe "allow_blank and allow_nil options" do - def check_performed(value, result, **options) $FILTER_PERFORMED = false - report = test_report(:name => value) do - scope {Entry} + report = test_report(name: value) do + scope { Entry } filter(:name, **options) do |_| $FILTER_PERFORMED = true self @@ -87,18 +84,18 @@ def check_performed(value, result, **options) it "should support allow_blank argument" do [nil, "", " "].each do |value| - check_performed(value, true, :allow_blank => true) + check_performed(value, true, allow_blank: true) end end it "should support allow_nil argument" do - check_performed(nil, true, :allow_nil => true) + check_performed(nil, true, allow_nil: true) end it "should support combination on allow_nil and allow_blank" do - check_performed(nil, false, :allow_nil => false, :allow_blank => true) - check_performed("", true, :allow_nil => false, :allow_blank => true) - check_performed(nil, true, :allow_nil => true, :allow_blank => false) + check_performed(nil, false, allow_nil: false, allow_blank: true) + check_performed("", true, allow_nil: false, allow_blank: true) + check_performed(nil, true, allow_nil: true, allow_blank: false) end end @@ -106,71 +103,67 @@ def check_performed(value, result, **options) it "should create default filter if scope respond to filter name method" do Entry.create! Entry.create! - grid = test_report(:limit => 1) do - scope {Entry} + grid = test_report(limit: 1) do + scope { Entry } filter(:limit) end expect(grid.assets.to_a.size).to eq(1) end - end describe "default filter as scope" do it "should create default filter if scope respond to filter name method" do Entry.create! - grid = test_report(:custom => 'skip') do - scope {Entry} + grid = test_report(custom: "skip") do + scope { Entry } filter(:custom) do |value| - if value != 'skip' - where(:custom => value) - end + where(custom: value) if value != "skip" end end expect(grid.assets).not_to be_empty end - end describe "positioning filter before another" do it "should insert the filter before the specified element" do grid = test_report do - scope {Entry} + scope { Entry } filter(:limit) - filter(:name, :before => :limit) + filter(:name, before: :limit) end - expect(grid.filters.index {|f| f.name == :name}).to eq(0) + expect(grid.filters.index { |f| f.name == :name }).to eq(0) end end describe "positioning filter after another" do it "should insert the filter before the specified element" do grid = test_report do - scope {Entry} + scope { Entry } filter(:limit) filter(:name) - filter(:group_id, :after => :limit) + filter(:group_id, after: :limit) end - expect(grid.filters.index {|f| f.name == :group_id}).to eq(1) + expect(grid.filters.index { |f| f.name == :group_id }).to eq(1) end end it "should support dummy filter" do grid = test_report do scope { Entry } - filter(:period, :date, :dummy => true, :default => proc { Date.today }) + filter(:period, :date, dummy: true, default: proc { Date.today }) end - Entry.create!(:created_at => 3.days.ago) + Entry.create!(created_at: 3.days.ago) expect(grid.assets).not_to be_empty end describe "#filter_by" do it "should allow partial filtering" do grid = test_report do - scope {Entry} + scope { Entry } filter(:id) filter(:name) end - Entry.create!(:name => 'hello') - grid.attributes = {:id => -1, :name => 'hello'} + Entry.create!(name: "hello") + grid.attributes = { id: -1, name: "hello" } expect(grid.assets).to be_empty expect(grid.filter_by(:name)).not_to be_empty end @@ -178,7 +171,7 @@ def check_performed(value, result, **options) it "supports dynamic header" do grid = test_report do - scope {Entry} + scope { Entry } filter(:id, :integer, header: proc { rand(10**9) }) end @@ -186,11 +179,10 @@ def check_performed(value, result, **options) expect(filter.header).to_not eq(filter.header) end - describe "#filter_by_name" do it "should return filter object" do r = test_report do - scope {Entry} + scope { Entry } filter(:id, :integer) end @@ -200,7 +192,6 @@ def check_performed(value, result, **options) end describe "tranlations" do - module ::Ns46 class TranslatedReport include Datagrid @@ -214,66 +205,64 @@ class InheritedReport < TranslatedReport it "translates filter with namespace" do grid = Ns46::TranslatedReport.new - store_translations(:en, datagrid: {:"ns46/translated_report" => {filters: {name: "Navn"}}}) do + store_translations(:en, datagrid: { "ns46/translated_report": { filters: { name: "Navn" } } }) do expect(grid.filters.map(&:header)).to eq(["Navn"]) end end it "translates filter using defaults namespace" do grid = Ns46::TranslatedReport.new - store_translations(:en, datagrid: {defaults: {filters: {name: "Navn"}}}) do + store_translations(:en, datagrid: { defaults: { filters: { name: "Navn" } } }) do expect(grid.filters.map(&:header)).to eq(["Navn"]) end end it "translates filter using parent report" do grid = Ns46::InheritedReport.new - store_translations(:en, datagrid: {:"ns46/translated_report" => {filters: {name: "Navn"}}}) do + store_translations(:en, datagrid: { "ns46/translated_report": { filters: { name: "Navn" } } }) do expect(grid.filters.map(&:header)).to eq(["Navn"]) end end end - describe "#select_options" do it "should return select options" do filters = { - id: [1,2], - name: [['a', 1], ['b', 2]], - category: {a: 1, b: 2}, + id: [1, 2], + name: [["a", 1], ["b", 2]], + category: { a: 1, b: 2 } } grid = test_report do - scope {Entry} + scope { Entry } filters.each do |name, options| filter(name, :enum, select: options, multiple: true) end end filters.each do |name, options| expect(grid.select_options(name)).to eq(options) - expect(grid.select_values(name)).to eq([1,2]) + expect(grid.select_values(name)).to eq([1, 2]) grid.select_all(name) - expect(grid.public_send(name)).to eq([1,2]) + expect(grid.public_send(name)).to eq([1, 2]) end end it "should raise ArgumentError for filter without options" do grid = test_report do - scope {Entry} + scope { Entry } filter(:id, :integer) end - expect { + expect do grid.select_options(:id) - }.to raise_error(Datagrid::ArgumentError) + end.to raise_error(Datagrid::ArgumentError) end end describe "#inspect" do it "should list all fitlers with types" do - module ::NsInspect class TestGrid include Datagrid - scope {Entry} + scope { Entry } filter(:id, :integer) filter(:name, :string) filter(:current_user) @@ -288,18 +277,17 @@ class TestGrid it "dislays no filters" do class TestGrid8728 include Datagrid - scope {Entry} + scope { Entry } end expect(TestGrid8728.inspect).to eq("TestGrid8728(no filters)") end end - describe ":if :unless options" do it "supports :if option" do klass = test_report_class do - scope {Entry} + scope { Entry } filter(:admin_mode, :boolean, dummy: true) filter(:id, :integer, if: :admin_mode) filter(:name, :integer, unless: :admin_mode) @@ -313,11 +301,12 @@ class TestGrid8728 expect(non_admin_filters).to include(:name) end - context 'with delegation to attribute' do - let(:role) { OpenStruct.new('admin?' => admin) } + context "with delegation to attribute" do + let(:role) { OpenStruct.new("admin?" => admin) } let(:klass) do test_report_class do attr_accessor :role + delegate :admin?, to: :role scope { Entry } @@ -328,13 +317,13 @@ class TestGrid8728 subject { klass.new(role: role).filters.map(&:name) } - context 'when condition is true' do + context "when condition is true" do let(:admin) { true } it { is_expected.to include(:id) } end - context 'when condition is false' do + context "when condition is false" do let(:admin) { false } it { is_expected.to_not include(:id) } diff --git a/spec/datagrid/form_builder_spec.rb b/spec/datagrid/form_builder_spec.rb index 6aa5826..dac013b 100644 --- a/spec/datagrid/form_builder_spec.rb +++ b/spec/datagrid/form_builder_spec.rb @@ -1,5 +1,4 @@ -# encoding: UTF-8 -require 'spec_helper' +require "spec_helper" require "action_controller" class MyFormBuilder @@ -10,18 +9,17 @@ class MyTemplate include ActionView::Helpers::FormHelper end - describe Datagrid::FormBuilder do let(:template) do action_view_template end - let(:view) { ActionView::Helpers::FormBuilder.new(:report, _grid, template, view_options)} + let(:view) { ActionView::Helpers::FormBuilder.new(:report, _grid, template, view_options) } let(:view_options) { {} } describe ".datagrid_filter" do it "should work for every filter type" do - Datagrid::Filters::FILTER_TYPES.each do |type, klass| + Datagrid::Filters::FILTER_TYPES.each do |_type, klass| expect(Datagrid::FormBuilder.instance_methods.map(&:to_sym)).to include(klass.form_builder_helper_name) end end @@ -33,218 +31,251 @@ class MyTemplate let(:_filter_options) { {} } let(:_filter_block) { nil } context "with default filter type" do - let(:_grid) { + let(:_grid) do test_report do - scope {Entry} + scope { Entry } filter(:name) end - } + end let(:_filter) { :name } - it { should equal_to_dom( - '' - )} + it { + should equal_to_dom( + '' + ) + } end context "with integer filter type" do let(:_filter) { :group_id } - let(:_grid) { + let(:_grid) do test_report do - scope {Entry} + scope { Entry } filter(:group_id, :integer) end + end + it { + should equal_to_dom( + '' + ) } - it { should equal_to_dom( - '' - )} context "when partials option is passed for filter that don't support range" do - let(:view_options) { {partials: 'anything' } } - it { should equal_to_dom( - '' - )} + let(:view_options) { { partials: "anything" } } + it { + should equal_to_dom( + '' + ) + } end end context "with date filter type" do let(:_filter) { :created_at } - let(:_grid) { + let(:_grid) do test_report do - scope {Entry} + scope { Entry } filter(:created_at, :date) end + end + it { + should equal_to_dom( + '' + ) } - it { should equal_to_dom( - '' - )} context "when special date format specified" do around(:each) do |example| - _grid.created_at = Date.parse('2012-01-02') + _grid.created_at = Date.parse("2012-01-02") with_date_format do example.run end end - it { should equal_to_dom( - '' - )} + it { + should equal_to_dom( + '' + ) + } end end context "with input_options" do context "type is date" do let(:_filter) { :created_at } - let(:_grid) { + let(:_grid) do test_report do - scope {Entry} - filter(:created_at, :date, input_options: {type: :date}) + scope { Entry } + filter(:created_at, :date, input_options: { type: :date }) end + end + it { + should equal_to_dom( + '' + ) } - it { should equal_to_dom( - '' - )} end context "type is textarea" do let(:_filter) { :name } - let(:_grid) { + let(:_grid) do test_report do - scope {Entry} - filter(:name, :string, input_options: {type: :textarea}) + scope { Entry } + filter(:name, :string, input_options: { type: :textarea }) end + end + it { + should equal_to_dom( + '