# require "eitil_wrapper/records/default_sorts" # require "eitil_wrapper/railtie" to run the dynamic dispatch as an init hook during boot require "eitil_wrapper/railtie" module EitilWrapper module Records module DefaultSorts Eitil::ApplicationRecordModules << self SharableDateSorts = -> (_class, column) { _class.eitil_sort :"#{column}_oldest_first", -> { _class.order("#{column} ASC") } _class.eitil_sort :"#{column}_newest_first", -> { _class.order("#{column} DESC") } } SharableNumSorts = -> (_class, column) { _class.eitil_sort :"#{column}_ascending", -> { _class.order("#{column} ASC") } _class.eitil_sort :"#{column}_descending", -> { _class.order("#{column} DESC") } } def inherited(subclass) super return if Eitil.skip_default_sorts_for_models.include?(subclass.to_s.to_sym) # Set the proper table_names for namespaced models. Without setting this, # Rails run into problems due to the fact that the first call to the model's # constant triggers this initializer first, and only thereafter the model file # which sets the correct table_name through a macro. namespaced_class = subclass.to_s.include?('::') subclass.table_name = subclass.to_s.gsub('::', '_').downcase.pluralize if namespaced_class subclass.use_eitil_sorts rescue => e puts "default sorts failed for #{subclass} because of #{e.class} and '#{e.to_s.split(' ').first}'" end def use_eitil_sorts return if abstract_class? %i[datetime date integer float].each { |_type| send :"create_eitil_#{_type}_sorts" } end def eitil_sort(_name, _proc) define_singleton_method(_name) { _proc.call } unless respond_to? _name end def sort_columns_of_type(data_type) columns_hash.select { |column,v| v.sql_type_metadata.type == data_type } end def create_eitil_datetime_sorts columns_of_type(:datetime)&.map do |column, object| SharableDateSorts.call self, column end end def create_eitil_date_sorts columns_of_type(:date)&.map do |column, object| SharableDateSorts.call self, column end end def create_eitil_integer_sorts columns_of_type(:integer)&.map do |column, object| SharableNumSorts.call self, column end end def create_eitil_float_sorts columns_of_type(:float)&.map do |column, object| SharableNumSorts.call self, column end end end end end