代码之家  ›  专栏  ›  技术社区  ›  Scott Swezey

在rake任务中使用复数方法

  •  4
  • Scott Swezey  · 技术社区  · 15 年前

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

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

    4 回复  |  直到 11 年前
        1
  •  9
  •   Jaco Pretorius    11 年前

    在rake任务中扩展actionView::helpers相当麻烦,基本上包括 全部的 rake任务中的helper方法。

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

    如果你没有一个数,你只想把一个词复数:

    ActiveSupport::Inflector.pluralize('dog')

        2
  •  3
  •   Lytol    15 年前

    将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
  •  3
  •   John Gibb    14 年前

    轨道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
  •  1
  •   cschulte22 airportyh    13 年前

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

    "dog".pluralize
    

    然后您可以用如下内容替换复数助手:

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