Module: SimpleSlug::ModelAddition::SingletonMethods

Defined in:
lib/simple_slug/model_addition.rb

Instance Method Summary collapse

Instance Method Details

#simple_slug(*args) ⇒ Object



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
39
40
41
# File 'lib/simple_slug/model_addition.rb', line 8

def simple_slug(*args)
  class_attribute :simple_slug_options, :simple_slug_adapter, instance_writer: false
  options = args.extract_options!
  self.simple_slug_options = options.reverse_merge(
      slug_column: SimpleSlug.slug_column,
      slug_method: args,
      slug_regexp: SimpleSlug.slug_regexp,
      min_length: SimpleSlug.min_length,
      max_length: SimpleSlug.max_length,
      callback_type: SimpleSlug.callback_type,
      validation: SimpleSlug.validation
  )
  self.simple_slug_adapter = SimpleSlug::Adapter.new(self)

  include InstanceMethods
  extend ClassMethods

  send(simple_slug_options[:callback_type], :simple_slug_generate, if: :should_generate_new_slug?) if simple_slug_options[:callback_type]

  if simple_slug_options[:validation]
    validates *simple_slug_adapter.column_names,
              presence: true,
              uniqueness: {case_sensitive: true},
              exclusion: {in: SimpleSlug.excludes},
              format: {with: simple_slug_options[:slug_regexp]},
              length: {minimum: simple_slug_options[:min_length], maximum: simple_slug_options[:max_length]}.reject{|_, v| v.blank? }
  end

  if simple_slug_options[:history]
    after_save :simple_slug_reset, :simple_slug_save_history
    after_destroy :simple_slug_cleanup_history
    include InstanceHistoryMethods
  end
end