【问题标题】:Using the pluralize method in a rake task在 rake 任务中使用复数方法
【发布时间】:2009-12-30 23:45:28
【问题描述】:

我知道这看起来很愚蠢,但我想在我正在设置的 rake 任务中调用 Rails 的一些文本助手。 (想像复数和循环的方法:http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html

您将如何在 rake 任务中提供这些功能,或者这不容易实现?

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    在您的 rake 任务中扩展 ActionView::Helpers 相当麻烦 - 这基本上包括您的 Rake 任务中的 所有 辅助方法。

    ActionController::Base.helpers.pluralize(5, 'dog')

    如果你没有计数,而你只想复数一个单词:

    ActiveSupport::Inflector.pluralize('dog')

    【讨论】:

      【解决方案2】:

      添加 ActiveSupport 和 ActionPack 作为依赖项可能会很麻烦,因为它只是为了方便使用文本助手——除非你的 Rakefile 已经在加载 Rails——但这里有一个 Rakefile 示例:

      require 'rubygems'
      require 'activesupport'
      require 'actionpack'
      require 'action_view/helpers'
      
      extend ActionView::Helpers
      
      task :plural do
        puts "I have #{pluralize(5, "dog")}"
        puts "You have #{pluralize(1, "dog")}"
      end
      

      【讨论】:

        【解决方案3】:

        在 Rails 3 中:

        require 'active_support/inflections'
        require 'action_view/helpers'
        extend ActionView::Helpers
        
        task :plural do
          puts "I have #{pluralize(5, "dog")}"
          puts "You have #{pluralize(1, "dog")}"
        end
        

        【讨论】:

          【解决方案4】:

          如果你只想要字符串的复数形式,你可以直接在它上面调用pluralize,而不需要在你的rake任务中加载任何额外的东西:

          "dog".pluralize
          

          然后你可以用这样的东西替换复数助手:

          word = "dog"
          if count == 1
            plural = "1 #{word}"
          else
            plural = "#{count} #{word}".pluralize
          end
          puts plural
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2012-06-04
            • 2011-10-07
            • 1970-01-01
            • 2015-08-17
            • 2011-07-14
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多