Module: Acts::Permalink::ClassMethods
- Defined in:
- lib/acts_as_permalink.rb
Instance Method Summary collapse
- #acts_as_permalink(options = {}) ⇒ Object
-
#generate_permalink_for(obj) ⇒ Object
Returns the unique permalink string for the passed in object.
Instance Method Details
#acts_as_permalink(options = {}) ⇒ Object
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# File 'lib/acts_as_permalink.rb', line 10 def acts_as_permalink(={}) # Read and scrub option for the column which will save the permalink self.base_class.instance_variable_set('@permalink_column_name', [:to].try(:to_sym) || :permalink) # Read and scrub the option for the column or function which will generate the permalink self.base_class.instance_variable_set('@permalink_source', ([:from].try(:to_sym) || :title)) # Read and validate the maximum length of the permalink max_length = [:max_length].to_i rescue 0 max_length = 60 unless max_length && max_length > 0 self.base_class.instance_variable_set('@permalink_length', max_length) if Rails.version >= "3" before_validation :update_permalink, :on => :create else before_validation_on_create :update_permalink end validates_uniqueness_of @permalink_column_name attr_readonly @permalink_column_name include Acts::Permalink::InstanceMethods extend Acts::Permalink::SingletonMethods end |
#generate_permalink_for(obj) ⇒ Object
Returns the unique permalink string for the passed in object.
36 37 38 39 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 |
# File 'lib/acts_as_permalink.rb', line 36 def generate_permalink_for(obj) # Find the source for the permalink text = obj.send(obj.class.base_class.instance_variable_get('@permalink_source')) # If it is blank then generate a random link if text.blank? text = obj.class.base_class.to_s.downcase + rand(10000).to_s # If it is not blank, scrub else text = text.downcase.strip # make the string lowercase and scrub white space on either side text = text.gsub(/[^a-z0-9\w]/, "_") # make any character that is not nupermic or alphabetic into an underscore text = text.sub(/_+$/, "").sub(/^_+/, "") # remove underscores on either end, caused by non-simplified characters text = text[0...obj.class.base_class.instance_variable_get('@permalink_length')] # trim to length end # Attempt to find the object by the permalink if obj.class.base_class.send("find_by_#{obj.class.base_class.instance_variable_get('@permalink_column_name')}", text) num = 1 # If we find the object we know there is a collision, so just add a number to the end until there is no collision while obj.class.base_class.send("find_by_#{obj.class.base_class.instance_variable_get('@permalink_column_name')}", text + num.to_s) num += 1 end text = text + num.to_s end text end |