Including a Ruby class from a separate file
Modules serve a dual purpose as a holder for functions and as a namespace. Keeping classes in modules is perfectly acceptable. To put a class in a separate file, just define the class as usual and then in the file where you wish to use the class, simply put require 'name_of_file_with_class'
at the top. For instance, if I defined class Foo
in foo.rb
, in bar.rb
I would have the line require 'foo'
.
If you are using Rails, this include often happens automagically
Edit: clarification of file layout
#file: foo.rb
class Foo
def initialize
puts "foo"
end
end
...
#file: bar.rb
require 'foo'
Foo.new
If you are in Rails, put these classes in lib/
and use the naming convention for the files of lowercase underscored version of the class name, e.g. Foo
-> foo.rb
, FooBar
-> foo_bar.rb
, etc.
As of ruby version 1.9 you can use require_relative
, to require files relatively to the file you are editing.
Comments
-
user94154 almost 2 years
For a while I had been including an entire class inside of a Ruby module. Apparently this is not what I am supposed to do. It appears that the point of a module is to store functions which can then be included as methods in a new class.
I don't want this. I have a class that I want to keep in a separate file which I can access from other files. How can I do this?
Thanks.
-
Dirk about 11 yearsThis post clarifies the require_relative expression in case you are running into problems with the above example when on Ruby >=1.9.2 Ruby require_relative example
-
-
user94154 almost 15 yearsthanks, very helpful. could you clarify that last sentence? it seems you may have had a typo(?). If class foo is stored in bar.rb, i require 'foo' in bazcontroller.rb? Then foo.new is usable in bazcontroller.rb?
-
boutta almost 12 yearsMaybe it would be nice to add some info on 'require_relative' for Ruby 1.9 since the code doesn't work for this version.
-
DorkRawk over 11 years@boutta Thank you for the 1.9 clarification, this fixed my issue.
-
mj_ over 4 yearsAnswer saved the say for me. I had a class "SendGridHelper" in a file called "app/lib/sendgrid_helper.rb" I had to change the file name to "app/lib/send_grid_helper.rb".