Larry
Larry

Reputation: 397

Refactoring out parts of a Model

I have a User model in app/models/user.rb. My User class has a lot of operations that are related to an external service, Intercom. Right now i have a bunch of methods like register_intercom_user, update_intercom_data, ping_intercom, etc. All of these are related to the User object.

I have a few options:

  1. Create a mixin with these methods (easiest option). But then i'm polluting my User namespace.
  2. Create a intercom.rb file in my lib/ dir with a def new(user). This is a pain though since it's far away from the User class and doesn't imply the coupling.
  3. Create a app/models/user/intercom.rb with a class User::Intercom; def new(user).... Seems more right since it shows a coupling to the User model, but i havent seen this pattern in other projects.

Am I not thinking of something? What's the right pattern for this?

Upvotes: 0

Views: 70

Answers (2)

IAmNaN
IAmNaN

Reputation: 10582

It sounds like you are looking for Concerns (in Rails4 or with a little config in Rails3) or Service Objects.

This article has more ideas. I'd also suggest Ryan Bates' excellent Railscasts Pro episode #398.

Upvotes: 1

Pierre-Louis Gottfrois
Pierre-Louis Gottfrois

Reputation: 17631

When dealing with external services, there are usually some kind of a gem for that. You could either do the same thing, build a tiny gem dealing with your methods and include it in your gemfile as local gem.

Or you could simply "simulate" a gem by adding code in you lib directory.

The basic idea is to imply less "coupling". You intercom module / gem should not care about your User model.

Upvotes: 0

Related Questions