Module: ConcernsOnRails::Models::Sluggable::ClassMethods

Includes:
Support::ColumnGuard
Defined in:
lib/concerns_on_rails/models/sluggable.rb

Overview

class methods A real module (not class_methods do) so the macro and its private helpers aren't constrained by Metrics/BlockLength (the Stateable precedent). ActiveSupport::Concern auto-extends ClassMethods.

Instance Method Summary collapse

Methods included from Support::ColumnGuard

#column_migration_hint, #ensure_columns!, #ensure_columns_on!, #schema_reachable?

Instance Method Details

#sluggable_by(field, history: false, scope: nil, reserved_words: nil, finders: false) ⇒ Object

Define sluggable field, with optional friendly_id features. Example:

sluggable_by :wonderful_name
sluggable_by :title, history: true            # old slugs keep resolving (needs a friendly_id_slugs table)
sluggable_by :title, scope: :account_id       # slugs unique per scope column
sluggable_by :title, reserved_words: %w[new]  # block these slugs (a UUID is appended instead)
sluggable_by :title, finders: true            # Model.find accepts a slug directly


68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/concerns_on_rails/models/sluggable.rb', line 68

def sluggable_by(field, history: false, scope: nil, reserved_words: nil, finders: false)
  self.sluggable_field = field.to_sym
  # Validate the slug column too (a missing one used to fail at first save
  # with an opaque friendly_id error); an association scope: is exempt.
  scope_column = scope && reflect_on_association(scope.to_sym) ? nil : scope
  ensure_columns!("ConcernsOnRails::Models::Sluggable",
                  [sluggable_field, friendly_id_config.slug_column, scope_column].compact,
                  types: { friendly_id_config.slug_column.to_sym => "string:uniq" })
  return unless history || scope || reserved_words || finders

  reconfigure_friendly_id(history: history, scope: scope,
                          reserved_words: reserved_words, finders: finders)
end