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
|
# File 'lib/active_tools/active_record/with_permalink.rb', line 7
def with_permalink(*args)
options = args.
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
validates_presence_of column_name
validates_uniqueness_of column_name, options[:scope] ? {:scope => Array(options[:scope])} : {}
before_validation do
self.with_permalink_options.each do |column_name, options|
eval <<-EOV
source = @_#{column_name}_demanded
EOV
source ||= case options[:from]
when String, Symbol then send(options[:from])
when Proc then options[:from].call(self)
end
if options[:uniq]
self.send("#{column_name}=", generate_permalink(column_name, source, options))
else
self.send("#{column_name}=", source)
end
end
end
after_save do
instance_variable_set(:"@_#{column_name}_demanded", nil)
end
class_eval <<-EOV
def #{column_name}=(value)
@_#{column_name}_demanded = value if value.present?
super(value)
end
def to_param
changes["#{column_name}"].try(:first)||#{column_name}
end
EOV
end
|