Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcing rails to autoload class

I have several small classes that are in a single file in /app/models, similar to:

# /app/models/little_class.rb
class LittleClass; ...do stuff; end;
class AnotherLittleClass; ...do stuff; end;

Rails only seems geared to autoload classes in files reflecting the class name. So referencing AnotherLittleClass outside of the file raises "unitialized constant" errors as below until LittleClass is referenced:

irb(main):001:0> AnotherLittleClass 
NameError: uninitialized constant AnotherLittleClass
irb(main):02:0> LittleClass
=> LittleClass
irb(main):03:0> AnotherLittleClass
=> LittleClass2

It would be a pain and messy to split them into individual files. Is there a way to autoload these classes, so referencing AnotherLittleClass without LittleClass doesnt raise an error?

like image 825
Allyl Isocyanate Avatar asked Nov 25 '25 03:11

Allyl Isocyanate


1 Answers

You could put them into a module and use them within this namespace SomeLittleClasses::LittleClass.do_something

# /app/models/some_little_classes.rb
module SomeLittleClasses

  class LittleClass
    def self.do_something
      "Hello World!"
    end
  end

  class AnotherLittleClass
    def self.do_something
      "Hello World!"
    end
  end

end

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!