# frozen_string_literal: true module RubyRailsExtensions module Extensions module BooleanScope if defined?(ActiveSupport::Concern) extend ActiveSupport::Concern class_methods do # Calls `boolean_scope` for each boolean column def add_boolean_scopes return unless table_exists? columns.each do |column| next unless column.type == :boolean # @!method not_#{column.name}? # @return [Boolean] # @!method column.name # @!scope class # @return [ActiveRecord::Relation<>] # @!method not_#{column.name} # @!scope class # @return [ActiveRecord::Relation<>] boolean_scope(column.name) end end # Defines 2 scopes and 1 ? method # # @param column_name [Symbol, String] The boolean column name # @param negative [Symbol, String] opposite of the column name # defaults to the column name with "not_" as a prefix # # @return [void] # def boolean_scope(column_name, negative = "not_#{column_name}") scope(:"#{column_name}", -> { where(column_name => true) }) scope(:"#{negative}", -> { where(column_name => false) }) define_method("#{negative}?") do !__send__("#{column_name}?") end end end end end end end