2

I'm in the following situation:

I'm building a site in rails. I have two classes with the name User. One is an ActiveRecord, the other is a custom class that I'd like to use for seeding my database. Question:

Can I refer to the ActiveRecord class named User from within my custom class named User?

Peter Berg
  • 6,006
  • 8
  • 37
  • 51

2 Answers2

7

Two classes with the same name will cause weird behavior, actually it will be only one class that will contain methods from both files, this can cause tons of issues.

You should namespace your seeder class inside a module, for instance :

module Seeder
  class User
  end
end

Then use Seeder::User when you need to use this class.

Intrepidd
  • 19,772
  • 6
  • 55
  • 63
  • 8
    And `::User` when referring to the global user class from within `Seeder` – Stefan Oct 16 '13 at 16:27
  • Great. `::User` is the answer I was looking for. I actually already had my second User class set up this way, but that's really good to know about how having two classes in the same namespace works. – Peter Berg Oct 16 '13 at 16:50
0

You're using a file called User.rb to seed the db and you're using Rails? Why not just use db/seeds.rb?

Then you can just seed your db with rake db:seed

Within seeds.rb you could do something like this:

(1..10).each do |i|
  User.create(name: "name_#{i}")
end
AdamT
  • 6,405
  • 10
  • 49
  • 75
  • I could, but the seeding process is complicated and I'd rather separate the pieces of it into their own self-contained files/classes – Peter Berg Oct 16 '13 at 16:47