Name Those Classes Properly

Although it may not seem intuitive, Rails is very picky when it comes to how you name your files, specifically  when adding new classes within your app folder.

Let’s say you have a class that looks like this:

class MySuperCatHelper

   def meow
      puts "Meow!!"
   end

end

You’ve saved this class in the app/helpers directory in a file called my_supercat_helper.rb. Naturally, you want this class to be available to your MySuperCat controller where you wish to add the following code:

cat = MySuperCatHelper.new
cat.meow

But for some reason, you’re getting an error about an uninitialized constant when using the above code in your MySuperCat controller.

Why is that?

The issue is subtle, and due to the opinionated nature of Rails. In order to be directly accessable without a special require statement, your class must live in a file that is named such that each new capital letter in the class, translates to an underscore in an all-lowercase filename.

So rather than naming the file with the MySuperCatHelper my_supercat_helper.rb, you must name it my_super_cat_helper.rb.

Notice the difference?

So be careful when naming your Rails files. Naming them properly will enable you to easily access your custom classes throughout your application, without having to clutter your code with require statements.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: