Sha256: 97a9967f4855056d3a3ccf793e7286dafbcc77ebb459a3b126435291393c9357

Contents?: true

Size: 1.49 KB

Versions: 10

Compression:

Stored size: 1.49 KB

Contents

# 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

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
ruby-rails-extensions-2.0.1 lib/ruby-rails-extensions/extensions/boolean_scope.rb
ruby-rails-extensions-2.0.1.pre.rc.1 lib/ruby-rails-extensions/extensions/boolean_scope.rb
ruby-rails-extensions-2.0.0 lib/ruby-rails-extensions/extensions/boolean_scope.rb
ruby-rails-extensions-2.0.0.pre.rc.1 lib/ruby-rails-extensions/extensions/boolean_scope.rb
ruby-rails-extensions-1.1.1 lib/ruby-rails-extensions/extensions/boolean_scope.rb
ruby-rails-extensions-1.1.1.pre.rc.1 lib/ruby-rails-extensions/extensions/boolean_scope.rb
ruby-rails-extensions-0.2.0 lib/ruby-rails-extensions/extensions/boolean_scope.rb
ruby-rails-extensions-0.2.0.pre.rc.1 lib/ruby-rails-extensions/extensions/boolean_scope.rb
ruby-rails-extensions-1.1.0 lib/ruby-rails-extensions/extensions/boolean_scope.rb
ruby-rails-extensions-1.1.0.pre.rc.1 lib/ruby-rails-extensions/extensions/boolean_scope.rb