【问题标题】:How can I localize day name with strftime in ruby Sinatra如何在 ruby​​ Sinatra 中使用 strftime 本地化日期名称
【发布时间】:2012-06-04 08:57:13
【问题描述】:

例如,在 ruby​​(sinatra 应用程序)中本地化 strftime 以在法语中使用日期名称的最佳方法是什么?

我有:

"2012-06-04".strftime("%a") # => "Mon"

我想要:

"2012-06-04".strftime("%a") # => "Lun"

谢谢!

【问题讨论】:

    标签: ruby localization sinatra strftime


    【解决方案1】:

    使用R18n internationalization 宝石。在你的情况下sinatra-r18n gem。它支持多种语言环境。

    取自sinatra example page

    set :default_locale, 'fr'
    

    这将使默认区域设置为法语。

    【讨论】:

    • 好了,终于成功了!正确的语法是 l(Time.now, '%B') # => Juin 谢谢!
    【解决方案2】:

    以下是您的问题的三个解决方案:

    1)您可以重写方法 strftime 并执行类似的操作(在正确的类中)

    class XXX #put the right name 
      DAY ={
        "Mon" => "Lun",
        "Tue" => "Mar",
        ...
        }
    
      alias :old_strftime :strftime #Keep a reference to the old method
    
      def strftime(arg)
        DAY[old_strftime(arg)] 
      end
    
    end
    

    或者:

    2) [推荐]只需在您的代码中使用上面使用的 DAY 哈希并使用

    DAY["2012-06-04".strftime("%a")]
    

    3) 继承前面提到的类(以“French”为前缀并插入上面的代码)。

    【讨论】:

    • 这会破坏strftime("something not %a")的所有使用。
    • 是的,如果他使用的不是 %a;他应该使用第二种解决方案
    猜你喜欢
    • 2016-10-28
    • 2010-10-01
    • 2015-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-02
    • 2011-08-02
    相关资源
    最近更新 更多