Levi Hackwith
Levi Hackwith

Reputation: 9332

When is it Appropriate to use Custom Classes in a Rails Application?

This is a complicated question with many possible answers, so I'll break down my situation into simple bullet points to help narrow down the solution:

My Rails App Has the Following 'Objects'

  1. Author
  2. Feed
  3. Update
  4. FeedTypes

The Objects are Related Like So:

  1. Authors can have 1 or more Feeds
  2. Feeds can have one or more Updates
  3. A Feed has one feedType

Example Setup:

My problem and My Questions:

Problem:

I need to parse the above-mentioned feed and store each tweet in the updates table. To parse the feed, I was thinking of writing a custom Feed class which would get inherited by TwitterFeed, FacebookFeed, TumblrFeed, etc.

However, I'm not sure if this is the 'Best Practice' for solving this kind of problem.

Questions:

  1. When is it appropriate to develop a custom class to perform an action in RoR (as opposed to going through the Model or Controller)?
  2. If this situation does not call for a custom class, which element should I apply the parsing logic to? The model or the controller?
  3. If this is an appropriate situation for a custom class, where in my rails application should I store it (in other words, what's the right 'convention')?

Upvotes: 2

Views: 761

Answers (2)

dangerousdave
dangerousdave

Reputation: 6408

Don't shy away from using a custom class if it's appropriate. If you need another a class, then add one, the fact you are using rails is not relevant to that decision.

Upvotes: 1

randomguy
randomguy

Reputation: 12242

You are probably going to have a background task invoked from time-to-time to check all the feeds, fetch new updates and store those in database. This task is completely separate from controllers and it should be possible to invoke it without any controller logic.

Your abstraction looks fine. You can further have something like XmlFeed < Feed if several feeds share a common XML structure.

1) Controllers should talk to database/models and pass relevant data to the view to render. Everything else should be either in a model, helper or library.

2) Are you asking where the parsing logic belongs to? In MVC, I think this would belong under the Model and/or a helper class, but definitely not the controller.. it's not its responsibility.

3) Classes holding data go into app/models. Classes that have nothing to do with holding data, go into the lib directory.

Upvotes: 1

Related Questions