Module: PermalinkFu::ActiveRecord::ClassMethods
- Defined in:
- lib/permalink_fu/active_record.rb
Overview
This is the plugin method available on all ActiveRecord models.
Instance Method Summary collapse
-
#has_permalink(attr_names = [], permalink_field = nil, options = {}) ⇒ Object
Specifies the given field(s) as a permalink, meaning it is passed through PermalinkFu.escape and set to the permalink_field.
Instance Method Details
#has_permalink(attr_names = [], permalink_field = nil, options = {}) ⇒ Object
Specifies the given field(s) as a permalink, meaning it is passed through PermalinkFu.escape and set to the permalink_field. This is done
class Foo < ActiveRecord::Base
# stores permalink form of #title to the #permalink attribute
has_permalink :title
# stores a permalink form of "#{category}-#{title}" to the #permalink attribute
has_permalink [:category, :title]
# stores permalink form of #title to the #category_permalink attribute
has_permalink [:category, :title], :category_permalink
# add a scope
has_permalink :title, :scope => :blog_id
# add a scope and specify the permalink field name
has_permalink :title, :slug, :scope => :blog_id
# do not bother checking for a unique scope
has_permalink :title, :unique => false
# update the permalink every time the attribute(s) change
# without _changed? methods (old rails version) this will rewrite the permalink every time
has_permalink :title, :update => true
end
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
# File 'lib/permalink_fu/active_record.rb', line 40 def has_permalink(attr_names = [], permalink_field = nil, = {}) include InstanceMethods if permalink_field.is_a?(Hash) = permalink_field permalink_field = nil end cattr_accessor :permalink_options cattr_accessor :permalink_attributes cattr_accessor :permalink_field self.permalink_attributes = Array(attr_names) self.permalink_field = (permalink_field || 'permalink').to_s self. = {:unique => true}.update() if self.[:unique] before_validation :create_unique_permalink else before_validation :create_common_permalink end define_method :"#{self.permalink_field}=" do |value| write_attribute(self.permalink_field, value.blank? ? '' : PermalinkFu.escape(value)) end end |