module Eitil module DefaultScopes extend ActiveSupport::Concern included do class << self SharableDateScopes = -> (_class, column) { _class.eitil_scope :"#{column}_today", -> { where("#{column} = ?", Date.today) } _class.eitil_scope :"#{column}_past", -> { where("#{column} < ?", Date.today) } _class.eitil_scope :"#{column}_future", -> { where("#{column} > ?", Date.today) } _class.eitil_scope :"#{column}_on_date", -> (date) { where("#{column} = ?", date) } _class.eitil_scope :"#{column}_before_date", -> (date) { where("#{column} = ?", date) } _class.eitil_scope :"#{column}_after_date", -> (date) { where("#{column} = ?", date) } _class.eitil_scope :"#{column}_between_dates", -> (from, till) { where("#{column} >= ? and #{column} <= ?", from, till) } _class.eitil_scope :"#{column}_oldest_first", -> { order("#{column} ASC") } _class.eitil_scope :"#{column}_newest_first", -> { order("#{column} DESC") } } SharableNumScopes = -> (_class, column) { _class.eitil_scope :"#{column}_equal_to", -> (number) { where("#{column} = ?", number) } _class.eitil_scope :"#{column}_lower_than", -> (number) { where("#{column} = <", number) } _class.eitil_scope :"#{column}_higher_than", -> (number) { where("#{column} = >", number) } _class.eitil_scope :"#{column}_between", -> (min, max) { where("#{column} >= ? and #{column} <= ?", min, max) } _class.eitil_scope :"#{column}_ascending", -> { order("#{column} ASC") } _class.eitil_scope :"#{column}_descending", -> { order("#{column} DESC") } } def inherited(subclass) super subclass.use_eitil_scopes 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 self, column end end def create_eitil_date_scopes columns_of_type(:date)&.map do |column, object| SharableDateScopes.call self, column end end def create_eitil_integer_scopes columns_of_type(:integer)&.map do |column, object| SharableNumScopes.call self, column end end def create_eitil_float_scopes columns_of_type(:float)&.map do |column, object| SharableNumScopes.call self, column end end end end end end