Skip to content

Instantly share code, notes, and snippets.

@fernyb
Created August 29, 2011 23:23
Show Gist options
  • Save fernyb/1179687 to your computer and use it in GitHub Desktop.
Save fernyb/1179687 to your computer and use it in GitHub Desktop.
extend friendly_id to have more than 1 friendly_id for each model
module FriendlyId
module ActiveRecordAdapter
def has_another_friendly_id method, options={}
if FriendlyId::on_ar3?
class_attribute :friendly_ids if !self.respond_to?(:friendly_ids)
self.friendly_ids ||= []
config = Configuration.new(self, method, options)
self.friendly_ids << config
end
end
end
end
module FriendlyId
module ActiveRecordAdapter
module SluggedModel
alias_method :orig_build_a_slug, :build_a_slug
def build_a_slug
friendly_ids.each do |config|
text = generate_slug_text_for(config).to_s
self.send("#{config.cache_column}=".to_sym, text)
end
orig_build_a_slug
end
def generate_slug_text_for config
base = self.send(config.method).to_s
if !base.nil? && !config.allow_nil?
text = SlugString.new(base).normalize_for!(config).to_s
SlugString.new(text).validate_for!(config)
end
end
end
end
end
module FriendlyId
class TaskRunner
def make_slugs
validate_uses_slugs
options = {
:include => :slug,
:limit => (ENV["LIMIT"] || 100).to_i,
:offset => 0,
:order => ENV["ORDER"] || "#{klass.table_name}.id ASC",
}.merge(task_options || {})
while records = find(:all, options) do
break if records.size == 0
records.each do |record|
record.save(:validate => false) unless record.slug?
yield(record) if block_given?
end
options[:offset] += options[:limit]
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment