0

I'm trying to dry up some code in my Rails application that allows to set a unique id when the object is creating using a filter. I have it in multiple locations and it seems like it should be in a module instead.

Right now I have something like this in each model.

  def set_uid
    self.uid = SecureRandom.uuid
  end

I have included a new file in my /lib directory at the file uid_generator.rb and included that the module in each of the models.

//model   
include UidGenerator

module UidGenerator
  def set_uid
    self.uid = SecureRandom.uuid
  end
end

In my testing however, this yields the error

uninitialized constant MODELNAME::UidGenerator (NameError).
Paul
  • 2,021
  • 5
  • 22
  • 33

1 Answers1

3

You just need to configure the autoload paths for your rails application. Here is something might be helpful. Best way to load module/class from lib folder in Rails 3?

Community
  • 1
  • 1
Samiron
  • 5,169
  • 2
  • 28
  • 55
  • Right now I've got this path: config.autoload_paths += %W(#{config.root}/lib/modules/) – Paul Sep 14 '12 at 06:39
  • 1
    If you want to put it in lib/modules then you need to call you module "Modules::UidGenerator" for autoloading to work. – sunkencity Sep 14 '12 at 07:03
  • Thanks, I found this blog post helpful as well: http://www.williambharding.com/blog/technology/rails-3-autoload-modules-and-classes-in-production/ – Paul Sep 14 '12 at 13:33