module Decidim::Scopable

A concern with the components needed when you want a model to have a scope.

The including model needs to implement the following interface:

@abstract An instance method that returns the id of the scope
@method decidim_scope_id
  @return [Integer]

@abstract An instance method that states whether scopes are enabled or not
@method scopes_enabled
  @return [Boolean]

@abstract An method that gives an associated organization
@method organization
  @return [Decidim::Organization]

Public Instance Methods

has_subscopes?() click to toggle source

Whether the resource has subscopes or not.

Returns a boolean.

# File lib/decidim/scopable.rb, line 50
def has_subscopes?
  scopes_enabled? && subscopes.any?
end
out_of_scope?(subscope) click to toggle source

Whether the passed subscope is out of the resource's scope.

Returns a boolean

# File lib/decidim/scopable.rb, line 57
def out_of_scope?(subscope)
  scope && !scope.ancestor_of?(subscope)
end
previous_scope() click to toggle source

If any, gets the previous scope of the object.

Returns a Decidim::Scope

# File lib/decidim/scopable.rb, line 65
def previous_scope
  return if versions.count <= 1

  Decidim::Scope.find_by(id: versions.last.reify.decidim_scope_id)
end
scopes_enabled?() click to toggle source

Whether the resource has scopes enabled or not.

Returns a boolean.

# File lib/decidim/scopable.rb, line 34
def scopes_enabled?
  scopes_enabled
end
subscopes() click to toggle source

Gets the children scopes of the object's scope.

If it's global, returns the organization's top scopes.

Returns an ActiveRecord::Relation.

# File lib/decidim/scopable.rb, line 43
def subscopes
  scope ? scope.children : organization.top_scopes
end

Private Instance Methods

scope_belongs_to_organization() click to toggle source

Validation to ensure that the resource is scoped within the organization's scope.

# File lib/decidim/scopable.rb, line 74
def scope_belongs_to_organization
  return if !scope || !organization

  errors.add(:scope, :invalid) unless organization.scopes.exists?(id: scope.id)
end