Module: ActiveTools::ActiveRecord::WithPermalink::ClassMethods

Defined in:
lib/active_tools/active_record/with_permalink.rb

Instance Method Summary collapse

Instance Method Details



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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/active_tools/active_record/with_permalink.rb', line 7

def with_permalink(*args)
  options = args.extract_options!
  unless (column_name = args.first.to_sym) || options[:from].present?
    raise "WithPermalink: column_name and/or options[:from] expected!"
  end

  options[:uniq] ||= true

  cattr_accessor :with_permalink_options unless defined?(with_permalink_options)
  self.with_permalink_options ||= {}
  self.with_permalink_options[column_name] = options
  
  uniqueness_options = options[:scope] ? {:scope => Array(options[:scope])} : {}
  
  validates_presence_of column_name
  validates_uniqueness_of column_name, uniqueness_options
  validates_length_of column_name, :maximum => 255
  
  before_validation do
    self.with_permalink_options.each do |column_name, options|
      eval "        source = @_\#{column_name}_demanded\n      EOV\n      source ||= case options[:from]\n      when String, Symbol then send(options[:from])\n      when Proc then options[:from].call(self)\n      end\n      if options[:uniq]\n        self.send(\"\#{column_name}=\", generate_permalink(column_name, source, options))\n      else\n        self.send(\"\#{column_name}=\", source)\n      end\n    end\n  end\n\n  after_save do\n    instance_variable_set(:\"@_\#{column_name}_demanded\", nil)\n  end\n\n  class_eval <<-EOV\n    def \#{column_name}=(value)\n      @_\#{column_name}_demanded = value if value.present?\n      super(value)\n    end\n\n    def to_param\n      changes[\"\#{column_name}\"].try(:first)||\#{column_name}\n    end        \n  EOV\n\nend\n"