user4325086
user4325086

Reputation:

Where to put mathematical calculations in Rails?

In case you were unaware, this is a beginner's question.

Having learned a bit of Ruby, I have ventured onto Rails, but have run into a brick wall when it comes to organizing methods. I'm building something which is supposed to take the data/parameters you get when someone creates something, but instead of showing it like you would a tweet or blog post, I want to use them as variables in some mathematical calculations, the results of which I then want to show.

Now, in Ruby, I would make a method for each little math operation, to make sure they (the methods) have a single responsibility each. In Rails, though, what am I supposed to do? In case you don't understand my problem, I think it has to do with my lack of understanding of instances in Rails. Instances in Ruby can call upon the methods I make, but where do I call upon my methods (actions?) in Rails?

Upvotes: 0

Views: 2963

Answers (2)

Fer
Fer

Reputation: 3347

You should follow the MVC paradigm:

The controller should receive the parameters that the user gave via some html form.
Then that controller should instantiate an object that is doing the math calculation and then the controller should render a view to present the results to the user.

The place where the controller and the views are stored is already decided by the framework:

controllers are in app/controllers and the views in app/views/<controller_name>

Now the question is where you put the class that performs the calculations. You might think about the app/models folder, but that one is typically for the models that inherit from ActiveRecord::Base, ie, all those that are persisted in the database.

Normally the kind of class that you are implementing lives in the lib folder.

For example, you might have the following structure:

app/controllers/calculations_controller.rb

def perform_calculations
  math_calculator = MathCalculator.new params[:operation]
  @result = math_calculator.calculate
end

lib/math_calculator.rb

class MathCalculator
  def calculate
    # whatever you need to do here
  end
end

app/views/calculations/perform_calculations.html.erb

<%= @result %>

Upvotes: 2

shikha
shikha

Reputation: 669

There's nothing official, I think its helping you

http://www.caliban.org/ruby/rubyguide.shtml

Upvotes: 0

Related Questions