require "lasha/engine" require "slim-rails" require "sassc-rails" require "pagy" require "ransack" require "aasm" require "active_link_to" module Lasha INDEX_ACTIONS = %i[new show edit destroy] class << self def index_data( controller:, namespace: nil, model: nil, actions: nil, collection:, attributes:, pagy_items: 20, scope_filters: false ) index_data_hash = { namespace: set_or_guess_namespace(namespace, controller), model: set_or_guess_model(model, collection), collection: collection, attributes: attributes, actions: set_or_guess_actions(actions, controller), scope_filters: scope_filters } validate_index_data(**index_data_hash) # Ransack index_data_hash[:ransack] = collection.ransack(controller.params[:q]) index_data_hash[:collection] = index_data_hash[:ransack].result # Pagy controller.class.send(:include, Pagy::Backend) index_data_hash[:pagy], index_data_hash[:collection] = controller.send( :pagy, index_data_hash[:collection], items: pagy_items ) index_data_hash rescue ArgumentError => e puts "******** index_data argument error report" puts "Class: #{e.class}" puts "Message: #{e.message}" puts e.backtrace end private def set_or_guess_namespace(namespace, controller) if namespace.present? namespace elsif controller.class.name.include?("::") controller.class.name.deconstantize.underscore.to_sym end end def set_or_guess_model(model, collection) if model.present? model elsif collection.present? collection.first.class end end def set_or_guess_actions(actions, controller) if actions.present? actions else INDEX_ACTIONS & controller.action_methods.to_a.map(&:to_sym) end end def validate_index_data(**index_data_hash) index_data_hash.each do |key, value| case key when :collection next if value.present? raise_args_error("Collection cannot be blank") # when :attributes when :model next if value.present? raise_args_error("Model cannot be deduced") when :actions next if (value - INDEX_ACTIONS).blank? raise_args_error("Uknown index action supplied") # when :namespace end end end def raise_args_error(message) raise ArgumentError, message end end end