Alina
Alina

Reputation: 2261

Ruby on Rails, calling a very big method from a model

I have a very big function in my model and I want to store it somewhere else in order to keep my model dry. I read that storing methods in ApplicationHelper and then calling them from a model is a bad idea. What is a good idea then? I want to have a separate file with my big methods and call them from a model.

Upvotes: 2

Views: 147

Answers (2)

Maximilian Stroh
Maximilian Stroh

Reputation: 1086

Use a Concern. https://gist.github.com/1014971

It's simple. In app/models/concerns create a file your_functionality.rb as follows:

module YourFunctionality
  extend ActiveSupport::Concern

  def your_fat_method
    # insert...
  end
end

And in your model simply:

include YourFunctionality

Upvotes: 0

Jesse Wolgamott
Jesse Wolgamott

Reputation: 40277

You can create a "plain old ruby object (PORO)" to do your work for you. let's say you had a method that calculates the amount overdue for a user.

So, you can create app/services/calculates_overages.rb

class CalculatesOverages
  def initialize(user)
    @user = user
  end

  def calculate
    # your method goes here
  end
end

Then, you can:

class User < ActiveRecord::Base
  def overage_amount
    CaluclatesOverage.new(self).calculate
  end
end

Or, in a controller you could:

def show
  @amount = CaluclatesOverage.new(current_user).calculate
end

The app/services directory could also be app/models, or the lib directory. There's no set convention for this (yet).

Upvotes: 2

Related Questions