- Read Tutorial
- Watch Guide Video
Since model files can be a little confusing for beginners, I'm going to create a model class that is not attached to ActiveRecord
. This is a little unconventional and not done in live projects, but I'm doing this to help you better understand model files.
To start, go to your models
folder inside your app
directory and create a model file called counter.rb
. In this file, create a class called Counter
and a method called self.calculate_percent_complete(completed_tasks, total_tasks)
. This self
method allows you to call this method from any part of the application just by using the dot notation. If you also notice, the method name is long. This is because a rule of thumb in Ruby is to make your method's functionality as explicit as possible in the name, even if it means a much longer name for your method. The reason for this practice is that the name of the method should be self-explanatory, and should not need a comment explaining its functionality, even if it's seen by a new developer.
So, the complete code is
class Counter def self.calculate_percent_complete(completed_tasks, total_tasks) completed_tasks.to_f / total_tasks.to_f * 100 end end
Inside the method, I'm first converting completed_tasks
variable into a float, which means, it will add decimal (.0) at the end of it for easier calculation. Likewise, I'm going to convert total_tasks
to the float data type.
To see how this works, let's open a rails console session with the command rails c
. Next, you can call this method directly from the console with this code,
Counter.calculate_percent_complete(8,10)
The two parameters are completed_tasks
and total_tasks
, and what this means, is we have completed 8 out of 10 tasks, and the result should be 80 percent.
You can pass other values to test if you like.
The obvious advantage with these models is that they make the code much easier to understand without cluttering the controller file.