File: slug_generator.rb

package info (click to toggle)
ruby-friendly-id 5.6.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 436 kB
  • sloc: ruby: 3,248; makefile: 3
file content (38 lines) | stat: -rw-r--r-- 920 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
module FriendlyId
  # The default slug generator offers functionality to check slug candidates for
  # availability.
  class SlugGenerator
    def initialize(scope, config)
      @scope = scope
      @config = config
    end

    def available?(slug)
      if @config.uses?(::FriendlyId::Reserved) && @config.reserved_words.present? && @config.treat_reserved_as_conflict
        return false if @config.reserved_words.include?(slug)
      end

      if @config.treat_numeric_as_conflict && purely_numeric_slug?(slug)
        return false
      end

      !@scope.exists_by_friendly_id?(slug)
    end

    def generate(candidates)
      candidates.each { |c| return c if available?(c) }
      nil
    end

    private

    def purely_numeric_slug?(slug)
      return false unless slug
      begin
        Integer(slug, 10).to_s == slug.to_s
      rescue ArgumentError, TypeError
        false
      end
    end
  end
end