Using the pluralize method in a rake task
I know this seems silly, but I would like to call some of Rails' Text Helpers in a rake task I am setting up. (Thinks like the pluralize and cycle method: http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html)
How would you go about开发者_如何学JAVA making these available in a rake task, or is it not easily possible?
It's rather messy to extend ActionView::Helpers in your rake task - that basically includes all helper methods in your Rake task.
ActionController::Base.helpers.pluralize(5, 'dog')
If you don't have a count and you just want to pluralize a word:
ActiveSupport::Inflector.pluralize('dog')
Adding ActiveSupport and ActionPack as dependencies could be heavy handed to simply have the convenience of a text helper -- unless your Rakefile is already loading Rails -- but here's an example 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
In 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
If you just want the pluralized version of the string, you can just call pluralize
on it directly without loading anything extra in your rake task:
"dog".pluralize
You could then just replace the pluralize helper with something like this:
word = "dog"
if count == 1
plural = "1 #{word}"
else
plural = "#{count} #{word}".pluralize
end
puts plural
精彩评论