user1134991
user1134991

Reputation: 3103

Requiring single module file to namespace multiple classes in multiple files

I am interested in defining multiple classes across multiple files that belong to the same module. Module CktCheck should have include the class Sdevv. Here is the code:

module CktCheck
  require 'Sdevv.rb'
end

In the Sdevv.rb file, I have:

class Sdevv
...
...
end

I want to instantiate an instance of class Sdevv, by using these lines

require("CktCheck.rb")
cktcheck_file = CktCheck::Sdevv.new("CktCheck.sdevv")

However, the following exception is raised:

./isBeginDevLine.rb:6:in `<main>': uninitialized constant CktCheck::Sdevv (NameError)`

Any Ideas?

Upvotes: 1

Views: 2048

Answers (3)

J&#246;rg W Mittag
J&#246;rg W Mittag

Reputation: 369458

Inside Sdevv.rb, you forgot to define class Sdevv inside the CktCheck module. Therefore, it is defined at the top-level.

You need to either reference it from the top-level simply as Sdevv instead of CktCheck::Sdevv or, if you want it to be defined inside the CktCheck module, then you, well, have to define it inside the CktCheck module:

module CktCheck
  class Sdevv
    # …
  end
end

Upvotes: 0

Matt Gibson
Matt Gibson

Reputation: 14949

Have you tried include instead of require?

Also, you could just open the module in the other file to have the class added:

# In Sdevv.rb:

module CktCheck
  class Sdevv
  ...
  ...
  end
end

# Then, when you need it:
require("CktCheck")
require("Sdevv")

Upvotes: 1

Ranbir Singh
Ranbir Singh

Reputation: 13

I don't think that that having a separate module file is good idea. Idea behind 'modules' is to

  1. group similar things of same sort by keeping them in same 'namespace'(i.e module name)
  2. avoid name collision when the 'name' that you used, happens to be used in other namespaces(other modules).

Its is fine to have 1 file per class and define all your new classes in a same module by reopening the that module.

#In first_thing.rb
module SameThings
  class FirstThing
  ....
  end
end

#In second_thing.rb
module SameThings
  class SecondThing
  .....
  end
end

now where ever you need to use FirstThing or SecondThing  
require 'first_thing'   or 
require 'second_thing'   

Upvotes: 0

Related Questions