Community for developers to learn, share their programming knowledge. Register!
Create First Ruby on Rails Project

Creating a Simple Calculator with Ruby on Rails


In this article, you can get training on creating a simple calculator application using Ruby on Rails. Whether you are a developer looking to sharpen your skills or someone interested in building practical applications, this guide will walk you through each step of the process. Let's dive in and make coding a fun and rewarding experience!

Setting Up Your Development Environment

Before we start coding, it's essential to set up your development environment properly. Make sure you have the following prerequisites installed on your machine:

gem install rails

Additionally, having a code editor like Visual Studio Code or Sublime Text will enhance your coding experience. You can also install Git for version control, which is a best practice in software development.

Creating a New Rails Application

Once your environment is set up, you can create a new Rails application. Open your terminal and run the following command:

rails new simple_calculator

Navigate into your new application's directory:

cd simple_calculator

This command generates a basic Rails application structure, including folders for models, views, and controllers. With your application scaffold ready, it's time to create the components needed for our calculator.

Building the Calculator Model

In Rails, a model represents the data and business logic of your application. For our calculator, we'll create a model that can handle basic operations like addition, subtraction, multiplication, and division.

Generate a model named Calculator:

rails generate model Calculator operation:string operand1:decimal operand2:decimal result:decimal

This command creates a migration file in the db/migrate directory. Open the generated migration file and ensure it looks like this:

class CreateCalculators < ActiveRecord::Migration[6.0]
  def change
    create_table :calculators do |t|
      t.string :operation
      t.decimal :operand1
      t.decimal :operand2
      t.decimal :result

      t.timestamps
    end
  end
end

Run the migration to create the database table:

rails db:migrate

Now, you have a model that can store the operation type, operands, and result.

Creating the Calculator Controller

Next, let's create a controller to handle user interactions. The controller will process input data and render the appropriate views. Generate a controller named CalculatorsController:

rails generate controller Calculators

Now, open app/controllers/calculators_controller.rb and define the following actions:

class CalculatorsController < ApplicationController
  def new
    @calculator = Calculator.new
  end

  def create
    @calculator = Calculator.new(calculator_params)
    @calculator.result = perform_calculation(@calculator)

    if @calculator.save
      redirect_to @calculator
    else
      render :new
    end
  end

  def show
    @calculator = Calculator.find(params[:id])
  end

  private

  def calculator_params
    params.require(:calculator).permit(:operation, :operand1, :operand2)
  end

  def perform_calculation(calculator)
    case calculator.operation
    when 'addition'
      calculator.operand1 + calculator.operand2
    when 'subtraction'
      calculator.operand1 - calculator.operand2
    when 'multiplication'
      calculator.operand1 * calculator.operand2
    when 'division'
      calculator.operand1 / calculator.operand2
    else
      0
    end
  end
end

This code provides a structure for creating a new calculation, saving it, and showing the result.

Designing the Calculator Views

Next, we’ll create the views for our calculator. Start by creating a view for the new calculation form. Create a file named new.html.erb in app/views/calculators/ and add the following code:

<h1>Simple Calculator</h1>

<%= form_with model: @calculator do |form| %>
  <div>
    <%= form.label :operand1 %>
    <%= form.number_field :operand1 %>
  </div>
  <div>
    <%= form.label :operation %>
    <%= form.select :operation, [['Addition', 'addition'], ['Subtraction', 'subtraction'], ['Multiplication', 'multiplication'], ['Division', 'division']] %>
  </div>
  <div>
    <%= form.label :operand2 %>
    <%= form.number_field :operand2 %>
  </div>
  <div>
    <%= form.submit 'Calculate' %>
  </div>
<% end %>

Now, create a show.html.erb file in the same directory to display the result:

<h1>Calculation Result</h1>

<p>Operand 1: <%= @calculator.operand1 %></p>
<p>Operation: <%= @calculator.operation %></p>
<p>Operand 2: <%= @calculator.operand2 %></p>
<p>Result: <%= @calculator.result %></p>

<%= link_to 'New Calculation', new_calculator_path %>

This setup will allow users to input values and see results neatly.

Implementing Calculator Functionality

At this point, we have set up the model, controller, and views. It’s time to implement the core functionality of the calculator. The perform_calculation method in the controller handles the logic for performing calculations based on the operation selected by the user.

When a user submits the form, the create action triggers, calculating the result and saving it in the database. The show action then retrieves and displays the result.

Testing Your Calculator Application

Testing is crucial for ensuring your application works correctly. Rails comes with built-in testing tools. To test your calculator, you can use RSpec or Minitest (which comes by default).

Here’s a simple test using Minitest that checks the addition functionality. Create a file named calculator_test.rb in test/models/:

require "test_helper"

class CalculatorTest < ActiveSupport::TestCase
  test "should calculate addition" do
    calculator = Calculator.new(operation: 'addition', operand1: 5, operand2: 3)
    assert_equal 8, calculator.result = calculator.perform_calculation(calculator)
  end
end

Run your tests with the following command:

rails test

This will ensure your calculator functions as expected.

Deploying Your Calculator to a Server

Once your application is working smoothly, you may want to deploy it to a server. Popular choices for deploying Rails applications include Heroku and AWS. For Heroku, you can follow these steps:

heroku login
heroku create simple-calculator
git add .
git commit -m "Deploying simple calculator"
git push heroku master

After the deployment, run any migrations on Heroku:

heroku run rails db:migrate

Your calculator will now be live and accessible via the web!

Summary

In this article, you learned how to create a simple calculator application using Ruby on Rails. We covered setting up your development environment, creating a new Rails application, building the model, creating the controller, designing views, implementing functionality, testing, and deploying your application. This project not only enhances your Rails skills but also gives you a practical application to showcase in your portfolio.

Last Update: 13 Jan, 2025

Topics:
Ruby on Rails