app/models/effective/effective_datatable/options.rb in effective_datatables-2.10.0 vs app/models/effective/effective_datatable/options.rb in effective_datatables-2.11.0

- old
+ new

@@ -3,15 +3,20 @@ module Effective module EffectiveDatatable module Options def initialize_datatable_options - @table_columns = _initialize_datatable_options(@table_columns) + @table_columns = _initialize_datatable_options(@table_columns, the_collection) end + def initialize_attributes(args) + _initialize_attributes(args) + end + def initialize_scope_options @scopes = _initialize_scope_options(@scopes) + _initialize_current_scope_attribute end def initialize_chart_options @charts = _initialize_chart_options(@charts) end @@ -20,10 +25,22 @@ collection_class.connection.quote_column_name(name) rescue name end protected + def _initialize_attributes(args) + args.compact.each do |arg| + if arg.respond_to?(:permit) # ActionController::Parameters / Rails 5 + arg = arg.permit(*permitted_params).to_h() # We permit only the scopes params + end + + raise "#{self.class.name}.new() can only be initialized with a Hash like arguments" unless arg.kind_of?(Hash) + + arg.each { |k, v| self.attributes[k] = v.presence } + end + end + # The scope DSL is # scope :start_date, default_value, options: {} # # The value might already be assigned, but if not, we have to assign the default to attributes @@ -48,14 +65,33 @@ options[:filter][:input_html][:value] = value options[:filter][:selected] = value end end + def _initialize_current_scope_attribute + attributes[:current_scope] ||= klass_scopes.find { |name, options| options[:klass_scope] && options[:default] }.try(:first) + + if attributes[:current_scope].present? + attributes[:current_scope] = attributes[:current_scope].to_sym + attributes[:current_scope] = nil unless klass_scopes.keys.include?(attributes[:current_scope]) + end + + if attributes[:current_scope].present? + klass_scopes.each { |name, _| attributes[name] = (name == attributes[:current_scope]) } + end + end + def _initialize_chart_options(charts) charts end - def _initialize_datatable_options(cols) + def _initialize_datatable_options(cols, collection) + # We set some memoized helper values + @collection_class = (collection.respond_to?(:klass) ? collection.klass : self.class) + @active_record_collection = (collection.ancestors.include?(ActiveRecord::Base) rescue false) + @array_collection = (collection.kind_of?(Array) && collection.first.kind_of?(Array)) + + # And then parse all the colums sql_table = (collection.table rescue nil) # Here we identify all belongs_to associations and build up a Hash like: # {user: {foreign_key: 'user_id', klass: User}, order: {foreign_key: 'order_id', klass: Effective::Order}} belong_tos = (collection.klass.reflect_on_all_associations(:belongs_to) rescue []).inject({}) do |retval, bt|