Module: ActiveRecordRelationExtensions::ClassMethods

Defined in:
lib/active_record_relation_extensions.rb

Overview

Adds the ‘if` method to ActiveRecord::Relation

Instance Method Summary collapse

Instance Method Details

#if(if_condition, scope) ⇒ ActiveRecord::Relation

‘if` applies the given scope only if the condition is true.

Parameters:

  • if_condition (Boolean)

    whether to apply the scope

  • scope (Proc)

    a callable object representing the scope

Returns:

  • (ActiveRecord::Relation)

    the modified or original relation



13
14
15
16
17
18
19
# File 'lib/active_record_relation_extensions.rb', line 13

def if(if_condition, scope)
  return self unless if_condition

  raise "Invalid Scope. Must provide a lambda '-> { your_scope(arg) }'" unless scope.is_a?(Proc)

  merge(scope)
end

#unless(unless_condition, scope) ⇒ ActiveRecord::Relation

‘if` applies the given scope only if the condition is true.

Parameters:

  • if_condition (Boolean)

    whether to apply the scope

  • scope (Proc)

    a callable object representing the scope

Returns:

  • (ActiveRecord::Relation)

    the modified or original relation



26
27
28
29
30
31
32
# File 'lib/active_record_relation_extensions.rb', line 26

def unless(unless_condition, scope)
  return self if unless_condition

  raise "Invalid Scope. Must provide a lambda '-> { your_scope(arg) }'" unless scope.is_a?(Proc)

  merge(scope)
end