Topic: Refactoring a rake-task

Hey experts,

to populate my database I wrote a little rake task using Ryan's populator gem, which looks like that:

# populate.rake

namespace :db do
  desc "Erase and fill the database"
  task :populate => :environment do
    # Get the new populator gem
    require 'populator'
    ...
    do some fancy stuff
    ...
  end
end

Within that task I need to have a random int between min and max, so I would like to use a method like this

  def range_rand(min, max)
    min + rand(max - min)
  end

As I am very new to Rails, I am not sure, where to place that method to. Any hint welcome!

Thanks a lot!
Temruk

Re: Refactoring a rake-task

The method seems to belong in the Ruby class for Numeric, so since rake loads your environment, you could include in your lib directory a file called ruby_class_extensions.rb, and inside it you'd open the Ruby Numeric class and include your method in there. To call it, of course, you'd have to use Numeric.range_rand(min,max).

update: forgot to mention that it should be a class method, so def self.range_rand(min,max).... etc  end

Last edited by lazylester (2009-12-12 10:17:21)