module Eitil module DefaultScopes extend ActiveSupport::Concern included do SharableDateScopes = -> (column) { eitil_scope :"#{column}_today", -> { where("#{column} = ?", Date.today) } eitil_scope :"#{column}_past", -> { where("#{column} < ?", Date.today) } eitil_scope :"#{column}_future", -> { where("#{column} > ?", Date.today) } eitil_scope :"#{column}_on_date", -> (date) { where("#{column} = ?", date) } eitil_scope :"#{column}_before_date", -> (date) { where("#{column} = ?", date) } eitil_scope :"#{column}_after_date", -> (date) { where("#{column} = ?", date) } eitil_scope :"#{column}_between_dates", -> (from, till) { where("#{column} >= ? and #{column} <= ?", from, till) } eitil_scope :"#{column}_oldest_first", -> { order("#{column} ASC") } eitil_scope :"#{column}_newest_first", -> { order("#{column} DESC") } } SharableNumScopes = -> (column) { eitil_scope :"#{column}_equal_to", -> (number) { where("#{column} = ?", number) } eitil_scope :"#{column}_lower_than", -> (number) { where("#{column} = <", number) } eitil_scope :"#{column}_higher_than", -> (number) { where("#{column} = >", number) } eitil_scope :"#{column}_between", -> (min, max) { where("#{column} >= ? and #{column} <= ?", min, max) } eitil_scope :"#{column}_ascending", -> { order("#{column} ASC") } eitil_scope :"#{column}_descending", -> { order("#{column} DESC") } } class << self private def self.inherited(subclass) use_eitil_scopes super end def use_eitil_scopes return if abstract_class? %i[boolean datetime date integer float].each { |_type| send :"create_eitil_#{_type}_scopes" } end def eitil_scope(_name, _proc) scope _name, _proc unless respond_to? _name end def columns_of_type(data_type) columns_hash.select { |column,v| v.sql_type_metadata.type == data_type } end def create_eitil_boolean_scopes columns_of_type(:boolean)&.map do |column, object| eitil_scope :"#{column}_true", -> { where(column => true) } eitil_scope :"#{column}_false", -> { where(column => [false, nil]) } end end def create_eitil_datetime_scopes columns_of_type(:datetime)&.map do |column, object| SharableDateScopes.call column end end def create_eitil_date_scopes columns_of_type(:date)&.map do |column, object| SharableDateScopes.call column end end def create_eitil_integer_scopes columns_of_type(:integer)&.map do |column, object| SharableNumScopes.call column end end def create_eitil_float_scopes columns_of_type(:float)&.map do |column, object| SharableNumScopes.call column end end end end end end