在rake任务中使用pluralize方法
问题描述:
我知道这看起来很愚蠢,但我想在我设置的一个rake任务中调用一些Rails的文本助手。 (认为像复数和循环方法:http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html)在rake任务中使用pluralize方法
你会如何去使这些可用的耙任务,或者是不容易的可能吗?
答
这是相当凌乱在你的rake任务延长的ActionView ::帮手 - 这主要包括在耙所有辅助方法任务。
ActionController::Base.helpers.pluralize(5, 'dog')
如果你没有一个计数,你只是想一个单词变复数:
ActiveSupport::Inflector.pluralize('dog')
答
添加的ActiveSupport和ActionPack的作为依赖可能是重手简单地有一个文本助手的便利 - 除非你的Rake文件已加载Rails的 - 但这里有一个例子Rake文件:
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
答
在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
答
如果你只是想串的多元化的版本,你可以调用它的pluralize
的情况下直接在你的rake任务加载额外的东西:
"dog".pluralize
然后,您可以只用像这样替换以复数帮手:
word = "dog"
if count == 1
plural = "1 #{word}"
else
plural = "#{count} #{word}".pluralize
end
puts plural
非常感谢你:) – 2009-12-31 01:15:02