Class: ActivePermalink::Generator

Inherits:
Object
  • Object
show all
Defined in:
lib/active_permalink/generator.rb

Instance Method Summary collapse

Constructor Details

#initialize(record, field, old_value, new_value, options = {}) ⇒ Generator

Returns a new instance of Generator.



3
4
5
6
7
8
9
10
11
# File 'lib/active_permalink/generator.rb', line 3

def initialize(record, field, old_value, new_value, options={})
  @record    = record
  @field     = field
  @old_value = old_value
  @new_value = new_value
  @options   = options
  @translit  = options[:transliterations]
  @scope     = options.fetch :scope, :global
end

Instance Method Details



50
51
52
# File 'lib/active_permalink/generator.rb', line 50

def build_new_permalink
  @record.build_active_permalink(slug: scope_unique_slug, scope: @scope, active: true)
end


32
33
34
35
36
37
38
39
# File 'lib/active_permalink/generator.rb', line 32

def deactivate_old_permalink
  unless @record.active_permalink.new_record?
    parameters = { slug: @old_value, active: true }
    permalink  = @record.old_permalinks.rewhere(parameters).first

    permalink.update_column(:active, false) unless permalink.nil?
  end
end


54
55
56
57
58
59
# File 'lib/active_permalink/generator.rb', line 54

def new_permalink
  deactivate_old_permalink
  @record.reload_active_permalink

  reassign_old_permalink || build_new_permalink
end


41
42
43
44
45
46
47
48
# File 'lib/active_permalink/generator.rb', line 41

def reassign_old_permalink
  permalink = @record.old_permalinks.find_by(slug: slug_from_column)

  unless permalink.nil?
    permalink.update(active: true)
    permalink
  end
end

#scope_unique_slugObject



21
22
23
24
25
26
27
28
29
30
# File 'lib/active_permalink/generator.rb', line 21

def scope_unique_slug
  unique = slug_from_column
  index  = 1

  while not Permalink.where(scope: @scope, slug: unique).count.zero?
    unique = "#{slug_from_column}-#{(index += 1)}"
  end

  unique
end

#slug_candidatesObject



13
14
15
# File 'lib/active_permalink/generator.rb', line 13

def slug_candidates
  @new_value.present? ? @new_value : @record.send(@field)
end

#slug_from_columnObject



17
18
19
# File 'lib/active_permalink/generator.rb', line 17

def slug_from_column
  @column_slug ||= slug_candidates.to_slug.normalize(transliterations: @translit).to_s
end