Building a simple calculator form in Rails 4

7k views Asked by At

I am looking to build a simple set of calculators in a Rails 4 application and I am at a bit of a loss as to how I should go about setting up my models and controllers.

In this example I have a series of calculators that will have very similar but in some cases slightly different inputs / variables and slightly different calculation methods.

My first attempt was to simply create a Calculator controller without a model but quickly became lost as to where I would handle things like form params and calculation logic.

Creating a model also made little sense to me given that the calculators require some slightly different inputs and calculation methods.

Finally, creating multiple models also seemed like an extremely messy approach here in this scenario.

So with all of that in mind I was wondering if someone could show me the Rails way as to how I should approach this problem. If it helps to have further information I am looking to build out the same approach found in the following set of spreadsheets: http://www.widerfunnel.com/proof/roi-calculators

Any help would be seriously appreciated!

1

There are 1 answers

2
Julio Betta On BEST ANSWER

You should keep in mind that Rails is not only about MVC. You can create your custom classes, and use them in a model, or a controller.

In this case, you could create a Calculator class inside app/lib and use it inside your controller. For example:

# app/lib/calculator.rb
class Calculator
  def self.sum(a, b)
    a.to_i + b.to_i
  end

  def self.subtr(a, b)
    a.to_i - b.to_i
  end
end

.

# app/controllers/calculator_controller
class CalculatorController < ApplicationController
  def index
  end

  def new
    @result = Calculator.send(params[:operation], *[params[:a], params[:b]])
    render :index
  end

end

.

# app/views/calculator/index.html.erb
<%= form_for :calculator, url: { action: :new }, method: :get do |f|   %>
  <%= number_field_tag :a, params[:a] %>
  <%= select_tag :operation, options_for_select([['+', :sum], ['-',    :subtr]], params[:operation]) %>
  <%= number_field_tag :b, params[:b] %>
  <%= f.submit 'Calculate!' %>
<% end %>

<% unless @result.nil? %>
  <p> = <%= @result %> </p>
<% end %>

This is just a very simple example on what is possible to do by creating your own classes and use them on Rails.

;)