Module: Mongoid::LocalizedSlug

Extended by:
ActiveSupport::Concern
Defined in:
lib/mongoid/localized_slug.rb,
lib/mongoid/localized_slug/version.rb

Overview

The Slug module helps you generate a URL slug or permalink based on one or more fields in a Mongoid model.

Defined Under Namespace

Modules: ClassMethods, Criterion

Constant Summary collapse

VERSION =
'0.1.10'

Instance Method Summary collapse

Instance Method Details

#build_slugtrue

Builds a new slug.

Returns:

  • (true)


157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
# File 'lib/mongoid/localized_slug.rb', line 157

def build_slug
  if self.respond_to?("#{slugged_attribute}_translations")
    translations = self.send("#{slugged_attribute}_translations")
  else
    translations = { I18n.locale.to_s => self.send(slugged_attribute) }
  end
  slugs = []
  trans_hash = {}
  translations.each do |lang, text|
    if text.present?
      trans_hash[lang] = find_unique_slug_for(text)
      slugs << trans_hash[lang]
    end
  end
  self.send("#{slug_name}_translations=", trans_hash)
  self.send("#{slug_name}=", slugs.uniq)
  true
end

#find_unique_slug_for(desired_slug) ⇒ String

Finds a unique slug, were specified string used to generate a slug.

Returned slug will the same as the specified string when there are no duplicates.

Parameters:

  • Desired (String)

    slug

Returns:

  • (String)

    A unique slug



183
184
185
# File 'lib/mongoid/localized_slug.rb', line 183

def find_unique_slug_for(desired_slug)
  self.class.find_unique_slug_for desired_slug, :model => self
end

#slug_should_be_rebuilt?Boolean

Returns Whether the slug requires to be rebuilt.

Returns:

  • (Boolean)

    Whether the slug requires to be rebuilt



188
189
190
# File 'lib/mongoid/localized_slug.rb', line 188

def slug_should_be_rebuilt?
  new_record? or slug_changed? or slugged_attribute_changed?
end

#slugged_attribute_changed?Boolean

Returns:

  • (Boolean)


192
193
194
# File 'lib/mongoid/localized_slug.rb', line 192

def slugged_attribute_changed?
  attribute_changed? slugged_attribute
end

#to_paramString

to this record.

Returns:

  • (String)

    A string which Action Pack uses for constructing an URL



198
199
200
201
202
203
204
205
206
207
208
# File 'lib/mongoid/localized_slug.rb', line 198

def to_param
  if slug.empty?
    build_slug
    save
  end
  locale = I18n.locale.to_s
  slug_translations.each do |lang, localized_slug|
    return localized_slug || super if lang == locale
  end
  (slug.is_a?(Array) ? slug.first : slug) || super
end