ruby-on-rails – Rails常用字符串(用于通知和错误消息等)
大约一年前,我决定确保每个具有非唯一文本的flash通知都会从模块中的方法获取文本.我这样做的最初原因是为了避免反复输入相同的字符串.如果我想改变措辞,我可以在一个地方轻松地做到这一点,并且错综复杂地反复重复相同事情的可能性会降低.
我最终得到的是: module Messages def format_error_messages(errors) errors.map {|attribute,message| "Error: #{attribute.to_s.titleize} #{message}.<br />"} end def error_message_could_not_find(object_name) "Error: Unable to find the specified " + object_name + "!" end def error_message_could_not_create(object_name) "Error: Unable to create the " + object_name + "!" end def error_message_could_not_save(object_name) "Error: Unable to save " + object_name + " to database!" end def error_message_could_not_update(object_name) "Error: Unable to update " + object_name + "!" end def error_message_could_not_destory(object_name) "Error: Unable to destroy " + object_name + "!" end def notice_message_created(object_name) object_name.capitalize + " has been created!" end def notice_message_updated(object_name) object_name.capitalize + " has been updated!" end def notice_message_destroyed(object_name) object_name.capitalize + " has been deleted!" end end 在我的控制器中,当我设置闪光灯时,我可以执行以下操作: flash [:notice] = notice_message_created(“post”) 这样所有成功创建的对象都会生成类似的消息 我现在正在重做我的一个项目并且正在完成这一切,我有这种唠叨的感觉,这不是最好的方法.我的意思是,它有效,到目前为止它对我有好处,但我从未见过其他人这样做,我开始认为这是有原因的.每次我需要一个新字符串时都必须添加一个新方法,这看起来几乎是愚蠢的.但那么我怎样才能将上下文文本插入到字符串中(就像我们正在处理的对象类型的名称一样)? 在处理常见的文本字符串时,是否存在Rails社区标准?特别是那些需要在运行时插入其他文本的人? 我一直在阅读Rails的国际化,因为将我的项目本地化为多种语言会很好,我喜欢将所有文本字符串放在漂亮的YAML文件中,这样可以一举两得.但我不知道我怎么能做到这一点,并保持我已经拥有和需要的相同功能(除非我非常错误,我不需要它,因为有更好的方法). 我对这个问题的任何想法,建议或相关阅读都很开放. 解决方法
您可以使用
Rails Internationalization API作为替代方法.然后,您可以使用要使用的字符串填充您的语言环境文件.您可以包含您想要提供的任何参数,就像教程中的示例ins部分4.2一样.
I18n.backend.store_translations :en,:thanks => 'Thanks %{name}!' I18n.translate :thanks,:name => 'Jeremy' # => 'Thanks Jeremy!' 请执行以下步骤: >访问文件config / locales / en.yml 于: 最后,一切都应该像以前一样工作,你已经摆脱了很多简单的方法,并且你可以通过包含语言环境和将语言环境文件添加到config / locales来使你的应用程序国际化. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |