Where to put helper functions for rake tasks and test files in Ruby on Rails?

Tintin81 picture Tintin81 · Mar 1, 2013 · Viewed 10.5k times · Source

In my Rails application I have a file sample_data.rb inside /lib/tasks as well as a bunch of test files inside my /spec directory.

All these files often share common functionality such as:

def random_address
  [Faker::Address.street_address, Faker::Address.city].join("\n")
end

Where should I put those helper functions? Is there some sort of convention on this?

Thanks for any help!

Answer

BlackHatSamurai picture BlackHatSamurai · Mar 1, 2013

You could create a static class, with static functions. That would look something like this:

class HelperFunctions

     def self.random_address
          [Faker::Address.street_address, Faker::Address.city].join("\n")
     end

     def self.otherFunction
     end
end

Then, all you would need to do is:

  1. include your helper class in the file you want to use
  2. execute it like:

    HelperFunctions::random_address(anyParametersYouMightHave)
    

When doing this, make sure you include any dependencies in your HelperFunctions class.