Building a simple calculator form in Rails 4

I am looking to create a simple set of calculators in a Rails 4 application and I am a bit at a loss for how I need to set 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 just create a calculator controller without a model, but quickly got lost as to where I would handle things like form parameters and calculation logic.

Building the model also didn't make any sense to me, given that calculators require slightly different inputs and calculation methods.

Finally, creating multiple models also seemed extremely messy in this scenario.

So with all this in mind, I was wondering if someone could show me Rails how I should approach this problem. If it helps for more information, I would like to develop the same approach found in the following set of spreadsheets: http://www.widerfunnel.com/proof/roi-calculators

Any help would be seriously appreciated!

+3


source to share


1 answer


You must remember that Rails is not only MVC. You can create your own classes and use them in a model or controller.

In this case, you can create a calculator class inside the application / 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 of what you can do by creating your own classes and using them in Rails.

;)

+6


source







All Articles