Class: ActivePermalink::Generator
- Inherits:
-
Object
- Object
- ActivePermalink::Generator
- Defined in:
- lib/active_permalink/generator.rb
Instance Method Summary collapse
- #build_new_permalink ⇒ Object
- #deactivate_old_permalink ⇒ Object
-
#initialize(record, field, old_value, new_value, options = {}) ⇒ Generator
constructor
A new instance of Generator.
- #new_permalink ⇒ Object
- #reassign_old_permalink ⇒ Object
- #scope_unique_slug ⇒ Object
- #slug_candidates ⇒ Object
- #slug_from_column ⇒ Object
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 |
# File 'lib/active_permalink/generator.rb', line 3 def initialize(record, field, old_value, new_value, = {}) @record = record @field = field @old_value = old_value @new_value = new_value @options = @scope = .fetch :scope, :global end |
Instance Method Details
#build_new_permalink ⇒ Object
48 49 50 51 |
# File 'lib/active_permalink/generator.rb', line 48 def build_new_permalink parameters = { slug: scope_unique_slug, scope: @scope, active: true } @record.build_active_permalink(parameters) end |
#deactivate_old_permalink ⇒ Object
31 32 33 34 35 36 37 38 |
# File 'lib/active_permalink/generator.rb', line 31 def deactivate_old_permalink return if @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 |
#new_permalink ⇒ Object
53 54 55 56 57 58 |
# File 'lib/active_permalink/generator.rb', line 53 def new_permalink deactivate_old_permalink @record.reload_active_permalink reassign_old_permalink || build_new_permalink end |
#reassign_old_permalink ⇒ Object
40 41 42 43 44 45 46 |
# File 'lib/active_permalink/generator.rb', line 40 def reassign_old_permalink permalink = @record.old_permalinks.find_by(slug: slug_from_column) return if permalink.nil? permalink.update(active: true) permalink end |
#scope_unique_slug ⇒ Object
20 21 22 23 24 25 26 27 28 29 |
# File 'lib/active_permalink/generator.rb', line 20 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_candidates ⇒ Object
12 13 14 |
# File 'lib/active_permalink/generator.rb', line 12 def slug_candidates @new_value.present? ? @new_value : @record.send(@field) end |
#slug_from_column ⇒ Object
16 17 18 |
# File 'lib/active_permalink/generator.rb', line 16 def slug_from_column @column_slug ||= slug_candidates.to_s.to_url end |