Skip to content

Instantly share code, notes, and snippets.

@svenfuchs
Forked from clemens/gist:3351
Created July 31, 2008 11:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save svenfuchs/3436 to your computer and use it in GitHub Desktop.
Save svenfuchs/3436 to your computer and use it in GitHub Desktop.
def translate(locale, key, options = {})
# ...
entry = lookup(locale, key, scope) || resolve(locale, key, default, options) || raise(I18n::MissingTranslationData.new(locale, key, options))
# ...
end
def localize(locale, object, format = :default)
raise ArgumentError, "Object must be a Date, DateTime or Time object. #{object.inspect} given." unless object.respond_to?(:strftime)
if Symbol == format
type = object.respond_to?(:sec) ? 'time' : 'date'
format = :"#{type}.formats.#{format}"
end
format = resolve locale, object, format, :raise => true
format.gsub!(/%a/, translate(locale, :"date.abbr_day_names")[object.wday])
format.gsub!(/%A/, translate(locale, :"date.day_names")[object.wday])
format.gsub!(/%b/, translate(locale, :"date.abbr_month_names")[object.mon])
format.gsub!(/%B/, translate(locale, :"date.month_names")[object.mon])
format.gsub!(/%p/, translate(locale, :"time.#{object.hour < 12 ? :am : :pm}")) if object.respond_to? :hour
object.strftime(format)
end
# rename #default to #resolve
def resolve(locale, object, subject, options = {})
case subject
when String then subject
when Symbol then translate locale, subject, options
when Proc then subject.call object
when Array then subject.each do |subject|
result = resolve(locale, object, subject, options.dup) and return result
end
end
rescue MissingTranslationData => e
raise e if options[:raise]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment