Differences Between Public and Private in Ruby on Rails
Today, I wanted to touch on public methods and private methods in Ruby on Rails. I was looking into other languages and I realized some have this but done in a bit different way. I thought it may be beneficial to new developers when looking into this for Ruby on Rails.
When looking at public methods, this will be where a lot of your code will be written. If I was defining an object like a car, I may want that car to have the ability to honk. If I defined honk to return “HONK!” each time Car.honk was called, this would be an example of a public method. I would be able to call Car.honk in my application and I should have it return “HONK”. This is a very basic example of a public method. I have found that I use these in most of my applications. There are times where you may not want these to be available to your application, these are called private methods.
A private method is only used for internal purposes. These can be used to not allow a method to be called unless it is called within it’s class. A way to think about these private methods would be for you to want a method to only be available within the class. If I wanted the car to turn on the headlights when it starts but I don’t want it available as a public method. I may create it as a private method called headlights. When I create a public method called Car.Start, I could call headlights within the Car.start. It may look something like this,
This will allow headlights to only be called within the Car class. This can be very useful when you need to add parameters to any validation and you do not want it to be exposed to the rest of the application. Here is how I used it in my “Road to Rome” application,
In the create method, I require flight_params to be used to validate the information as it comes in.
In the private method, I require the params of the data that is coming in to be from the flight class and permit the parameters to be saved.
I hope this helps give you an idea of when and when not to use private classes. It can be a bit at the beginning but it can save a lot of time and headache down the line.