Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
I18n that include pluralization rules for spanish within Rails - http://www.viget.com/extend/rails-internationalization-and-tu/
module I18n
module Backend
class SnippetBackend < Simple
protected
def init_translations
load_translations(*I18n.load_path.flatten)
load_translations_from_database
@initialized = true
end
def load_translations_from_database
data = { :en => {}, :es => {} }
Snippet.all.each do |snippet|
path = snippet.name.split(".")
key = path.pop
en = data[:en]
es = data[:es]
path.each do |group|
en[group] ||= {}
en = en[group]
es[group] ||= {}
es = es[group]
end
en[key] = snippet.english
es[key] = snippet.spanish
end
data.each { |locale, d| merge_translations(locale, d) }
end
end
end
end
require 'translation_buddy'
# Add new inflection rules using the following format
# (all these examples are active by default):
# ActiveSupport::Inflector.inflections do |inflect|
# inflect.plural /^(ox)$/i, '\1en'
# inflect.singular /^(ox)en/i, '\1'
# inflect.irregular 'person', 'people'
# inflect.uncountable %w( fish sheep )
# end
ActiveSupport::Inflector.inflections(:es) do |inflect|
inflect.plural /$/, 's'
inflect.plural /([^aeioué])$/, '\1es'
inflect.plural /([aeiou]s)$/, '\1'
inflect.plural /z$/, 'ces'
inflect.plural /á([sn])$/, 'a\1es'
inflect.plural /í([sn])$/, 'i\1es'
inflect.plural /ó([sn])$/, 'o\1es'
inflect.plural /ú([sn])$/, 'u\1es'
inflect.plural(/^(\w+)\s(.+)$/, lambda { |match|
head, tail = match.split(/\s+/, 2)
"#{head.pluralize} #{tail}"
})
inflect.singular /s$/, ''
inflect.singular /es$/, ''
inflect.singular(/^(\w+)\s(.+)$/, lambda { |match|
head, tail = match.split(/\s+/, 2)
"#{head.singularize} #{tail}"
})
inflect.irregular('papá', 'papás')
inflect.irregular('mamá', 'mamás')
inflect.irregular('sofá', 'sofás')
end
# TranslationBuddy
# These are all the hacks I had to do to make multi-language pluralization work.
module ActiveRecord
module Reflection
class AssociationReflection
private
def derive_class_name
class_name = name.to_s.camelize
class_name = class_name.singularize(I18n.default_locale) if [ :has_many, :has_and_belongs_to_many ].include?(macro)
class_name
end
end
end
class Base
class << self
def human_name(options = {})
defaults = self_and_descendants_from_active_record.map do |klass|
:"#{klass.name.underscore}"
end
# changed humanize to titleize
defaults << self.name.titleize
I18n.translate(defaults.shift, {:scope => [:activerecord, :models], :count => 1, :default => defaults}.merge(options))
end
private
# Guesses the table name, but does not decorate it with prefix and suffix information.
def undecorated_table_name(class_name = base_class.name)
table_name = class_name.to_s.demodulize.underscore
table_name = table_name.tableize if pluralize_table_names
table_name
end
end
end
end
module ActiveSupport
class ModelName
def initialize(name)
super
@singular = underscore.tr('/', '_').freeze
@plural = @singular.pluralize(I18n.default_locale).freeze
@cache_key = tableize.freeze
@partial_path = "#{@cache_key}/#{demodulize.underscore}".freeze
end
end
module CoreExtensions #:nodoc:
module String #:nodoc:
# String inflections define new methods on the String class to transform names for different purposes.
# For instance, you can figure out the name of a database from the name of a class.
#
# "ScaleScore".tableize # => "scale_scores"
module Inflections
# Returns the plural form of the word in the string.
#
# "post".pluralize # => "posts"
# "octopus".pluralize # => "octopi"
# "sheep".pluralize # => "sheep"
# "words".pluralize # => "words"
# "the blue mailman".pluralize # => "the blue mailmen"
# "CamelOctopus".pluralize # => "CamelOctopi"
def pluralize(locale = nil)
Inflector.pluralize(self, locale)
end
def singularize(locale = nil)
Inflector.singularize(self, locale)
end
end
end
end
module Inflector
# Yields a singleton instance of Inflector::Inflections so you can specify additional
# inflector rules.
#
# Example:
# ActiveSupport::Inflector.inflections do |inflect|
# inflect.uncountable "rails"
# end
def inflections(locale = nil)
locale ||= I18n.locale
locale_class = if locale.to_s == I18n.default_locale.to_s
ActiveSupport::Inflector::Inflections
else
ActiveSupport::Inflector.const_get("Inflections_#{locale}") rescue nil
end
if locale_class.nil?
ActiveSupport::Inflector.module_eval %{
class ActiveSupport::Inflector::Inflections_#{locale} < ActiveSupport::Inflector::Inflections
end
}
locale_class = ActiveSupport::Inflector.const_get("Inflections_#{locale}")
end
if block_given?
yield locale_class.instance
else
locale_class.instance
end
end
# Returns the plural form of the word in the string.
#
# Examples:
# "post".pluralize # => "posts"
# "octopus".pluralize # => "octopi"
# "sheep".pluralize # => "sheep"
# "words".pluralize # => "words"
# "CamelOctopus".pluralize # => "CamelOctopi"
def pluralize(word, locale = nil)
locale ||= I18n.locale
result = word.to_s.dup
if word.empty? || inflections(locale).uncountables.include?(result.downcase)
result
else
inflections(locale).plurals.each do |(rule, replacement)|
if replacement.respond_to?(:call)
break if result.gsub!(rule, &replacement)
else
break if result.gsub!(rule, replacement)
end
end
result
end
end
# The reverse of +pluralize+, returns the singular form of a word in a string.
#
# Examples:
# "posts".singularize # => "post"
# "octopi".singularize # => "octopus"
# "sheep".singluarize # => "sheep"
# "word".singularize # => "word"
# "CamelOctopi".singularize # => "CamelOctopus"
def singularize(word, locale = nil)
locale ||= I18n.locale
result = word.to_s.dup
if inflections.uncountables.include?(result.downcase)
result
else
inflections(locale).singulars.each do |(rule, replacement)|
if replacement.respond_to?(:call)
break if result.gsub!(rule, &replacement)
else
break if result.gsub!(rule, replacement)
end
end
result
end
end
# Create the name of a table like Rails does for models to table names. This method
# uses the +pluralize+ method on the last word in the string.
#
# Examples
# "RawScaledScorer".tableize # => "raw_scaled_scorers"
# "egg_and_ham".tableize # => "egg_and_hams"
# "fancyCategory".tableize # => "fancy_categories"
def tableize(class_name)
pluralize(underscore(class_name), I18n.default_locale)
end
end
end
module ActionController
module PolymorphicRoutes
def build_named_route_call(records, namespace, inflection, options = {})
unless records.is_a?(Array)
record = extract_record(records)
route = ''
else
record = records.pop
route = records.inject("") do |string, parent|
if parent.is_a?(Symbol) || parent.is_a?(String)
string << "#{parent}_"
else
string << "#{RecordIdentifier.__send__("plural_class_name", parent)}".singularize
string << "_"
end
end
end
if record.is_a?(Symbol) || record.is_a?(String)
route << "#{record}_"
else
route << "#{RecordIdentifier.__send__("plural_class_name", record)}"
route = route.singularize(I18n.default_locale) if inflection == :singular
route << "_"
end
action_prefix(options) + namespace + route + routing_type(options).to_s
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment