Concerned With: Skinny Controller, Skinny Model

August 30, 2008

A small Rails technique that I've been using lately is concerned_with. I first saw Matthew Bass use it on the => 3-2-1, but I've gleaned from a couple of articles on the web that it was invented by Rick Olsen.

The purpose of concerned_with is to break up larger models up into concerns. Let's say you have a User model, and you have several macros, includes, validations, callbacks, class methods and instance methods all related to authentication, maybe sort of like this:

class User << ActiveRecord::Base
  include AuthenticationSupport
  validates_presence_of :login
  validates_uniqueness_of :login
  before_create :set_default_password
  class << self
    def authenticate(login, password)
      login == "root" && password == "too_many_secrets"
    end
  end
  def set_default_password
    self.password = "pa$$w0rd"
  end
end

As your model grows in complexity, eventually what will happens is that you will have more validations, callbacks, class methods, instance methods, etc. They will get mixed in with the authentication ones, app/models/user.rb will grow to become 500 lines of code and it will be hard to keep track of what's what. Instead, just put this into app/models/user.rb:

class User << ActiveRecord::Base
  concerned_with :authentication
end

And then throw all of that into app/models/user/authentication.rb:

class User
  include AuthenticationSupport
  validates_presence_of :login
  validates_uniqueness_of :login
  before_create :set_default_password
  class << self
    def authenticate(login, password)
      login == "root" && password == "too_many_secrets"
    end
  end
  def set_default_password
    self.password = "pa$$w0rd"
  end
end

So now your app/models/user.rb is clean and can have other stuff in there, and all the authentication related stuff gets loaded from app/model/user/authentication.rb. All you have to do to enable this is is throw this snippet into an initializer, like config/initializers/concerned_with.rb:

class << ActiveRecord::Base
  def concerned_with(*concerns)
    concerns.each do |concern|
      require_dependency "#{name.underscore}/#{concern}"
    end
  end
end

Posted in Technology | Tags Rails, Ruby

Comments Comments Feed

1. neat idea, but i cringe every time i see see it. i'm not sure why.

# Posted By bryanl on Sunday, August 31 2008 at 10:43 AM

2. maybe i cringe because that its just another way of including a module. why not just do include AuthByLocalPassword or include AuthByLDAP.

the concerned_with just looks a bit more english like i guess.

# Posted By bryanl on Sunday, August 31 2008 at 10:45 AM

3. @bryanl

It's a little cleaner than a module because by opening up the actual user class, you can use exact same syntax. If you use a module, you have to sort of re-organize things a bit:

http://gist.github.com/8199

Since there's no reason to re-use this code, there no need for it to be a module. If there are methods you plan to share across models, then making it a module makes more sense.

# Posted By Paul Barry on Sunday, August 31 2008 at 1:13 PM

4. @Paul

I guess I think of modules as encapsulated behavior, and not a way of sharing behavior. This is why "concerned_with" seems a bit extra to me.

# Posted By bryanl on Sunday, August 31 2008 at 4:04 PM

5. I'm with Paul here. Modules seem to fit more as a way of encapsulating behavior for the purpose of reusing it amongst many classes. Maybe it's a matter of taste, but I like the "concerned_with" syntax because it's still connected directly to the class that it's part of, so the functionality can remain specific to that class rather than being abstracted for inclusion by any class.

# Posted By Ethan Vizitei on Saturday, September 6 2008 at 11:51 AM

6. I'm not sure I buy into this. What value does this bring over the traditional method (using a module with include)?

# Posted By ActsAsFlinn on Wednesday, September 17 2008 at 10:00 AM

7. In my pastie, I extend the user model with authentication validations. How exactly would you do that with a module?

module UserStuffs
def self.included(base)
base.validates_presence_of :foo
end
end

Yuck.

But if you're relying on this too much, you may be in danger of bloating your models too much (and neither 'concerns' nor modules will help you out here)

See trevor's comments on http://giantrobots.thoughtbot.com/2008/5/1/skinny-controllers-skinny-models

# Posted By rick on Wednesday, September 17 2008 at 11:27 AM

8. I'm really struggling to see why this isn't significantly worse than sticking the code in a module and including it. Isn't it just obfuscation? Why make life harder for people than it already is (by forcing them to learn your new pattern, when it doesn't add anything over and above "include")?

Just because you can, it doesn't mean you should.

# Posted By Graham Ashton on Friday, September 19 2008 at 9:11 AM

9. Isn't this really just an implementation of partial classes? http://en.wikipedia.org/wiki/Partial_type

- Mark

# Posted By Mark Richman on Wednesday, September 24 2008 at 7:09 AM

10. I think this is a good idea. Don't let the above detractors discourage you. Yes it is like doing an include but I feel that this is cleaner. My only concern is performance. I'm going to work with it and see if it affects the speed too much.

@the_detractors
What is the difference between this and using named_scope, has_many, many of the lamba shortcuts, orany other shortcuts or tricks? This is just a cleaner way of only editing what you need, and finding the place to edit faster. I see no reason not to take this approach. This falls much more into the category of doing things the rails way; whereas the other way is a lot more in line with the ruby way.

# Posted By Michael Christenson II on Wednesday, September 24 2008 at 5:06 PM

11. nice discussion. I've tried a couple of methods, also those mentioned above, to split up and organize code but haven't found the one to fit-all.
I think its more important to stick to self given conventions throughout one app which leads in any way to a cleaner layout and better handling.

# Posted By Schorsch on Wednesday, September 24 2008 at 7:38 PM

12. Saying "skinny model" is a little misleading. The class still has the same amount of behavior, it's just split across multiple files.

# Posted By Dan Manges on Wednesday, September 24 2008 at 10:07 PM

13. > Saying "skinny model" is a little misleading...

Fine then, how about "minced model"

# Posted By Andrew Vit on Thursday, September 25 2008 at 12:52 AM

14. I do something similar but module-based (meaning it can be shared between different models) here:
http://henrik.nyh.se/2008/09/augmentations

# Posted By Henrik N on Thursday, September 25 2008 at 4:41 AM

15. Oh, and Augmentations handles stuff like validations (like Rick mentions in comment #7) nicely.

# Posted By Henrik N on Thursday, September 25 2008 at 4:45 AM

16. Wouldn't this also serve to break up your unit tests into more manageable and understandable chunks?

# Posted By Larry on Friday, September 26 2008 at 9:47 AM

17. I winced when I first saw this, but then something clicked.

You are not taking out methods (etc.) just for the sake of cleaning up your model. You aren't making a skinny model just to say that you have skinny models. You are taking out functionality that _doesn't belong_ in the the model in the first place. An ActiveRecord model should handle only ActiveRecord stuff. The idea is that authentication, to follow the example from the article, has nothing to do with the ActiveRecord User model. This is just a separation of concerns (hence the concerned_with name). For the same reason that it is not good to do an AR find inside a view, or to have search logic inside a controller, it is not a good idea to put authentication stuff in a model. And its worth noting that you are not wanting to just hide some methods and stuff (though that is nice), you want to extract a class; there's an extra class hidden inside your model and you are taking it out. A module cannot do this.

This is a great refactoring tool. Thank you.

# Posted By Fabio on Monday, September 29 2008 at 11:28 PM

18. I don't like how its all lumped into the models directory. I like how with Rails you know just where to go to find stuff. With this approach I don't know (without opening the file and looking carefully) whether something is a model or not.

Why not store these in a "concerns" directory?

# Posted By Sean on Thursday, October 2 2008 at 4:39 PM

19. This is a great pattern and makes my user model much nicer.

Thanks!

# Posted By Sascha Konietzke on Monday, October 13 2008 at 11:10 AM

20. Would there be any reason to not use this pattern for controllers as well?

My application controller grew bigger and bigger. Could I just open ActionController::Base and add the concerned_with functionality?

# Posted By Sascha Konietzke on Monday, October 13 2008 at 12:07 PM

21. As much as I love a good Internet argument...

This is an interesting idea for covering up a bad design with a tube of lipstick. A user is a thing. Authentication is a behaviour. A user authenticates:

class User < ActiveRecord::Base
authenticates
end

module Authenticates
def self.included(base)
base.extend ClassMethods
base.send :include, InstanceMethods
end

module ClassMethods
def authenticates(options = {})
...
end
...
end

module InstanceMethods
...
end
end

It's not a rails v. ruby thing. This is a pattern that is repeated over and over in rails and there is already a place where these things go: vendor/plugins

If you find yourself extending or changing the platform, especially one as well thought out and rich as rails, you should first assume that the problem lies with your design and not with some deficiency in the platform.

If you refactor your design, not just for authentication but for any sort of behaviour, you not only get code which is easy to understand, easy to test and easy to reuse. If you load your models down with all sorts of implied behaviour then you get fat code which can't be easily tested and which can't be easy reused. That is what skinny models means. Its why we have: acts_as_list, will_paginate and thousands of other behavioural plugins. You might even find you don't need to write any code at all because there may be a plugin to do it already.

What if you wanted to authenticate both robots and users? Authenticate with OpenID. Authenticate with XML for an API? If you implement it as a behaviour then everything that uses that plugin gets this capability for free, fully tested and free of known bugs.

# Posted By Erik Petersen on Tuesday, October 28 2008 at 10:14 PM

22. Thank you !

# Posted By diziler on Saturday, November 14 2009 at 10:56 AM

23. brian atwood maniac pumps the perfect wear-with-everything color. These wardrobe staples have 5" stiletto heels and hidden 1 1/2" seamless platforms. These Brian Atwood 'Loca' studded pumps are so ravishing, that I'd totally be willing to pop an aspirin before wearing them. And I really lovebrian atwood mesh sandals and Brian Atwood Asymmetric Patent Pumps.brian atwood nude patent leather katie lee pumps. Bold shoes like these sculptural purple suede Brian Atwood 'Lola' pumps make an outfit. purple suede Brian Atwood 'Lola' pumpswith a heel that measures approximately 140mm / 5.5 inches with a 30mm / 1 inch concealed platform. Brian Atwood pumps have a closed toe, cutout detail at arch with elasticated straps and a leather sole.
Herve Leger Dress shop specialises in superior Herve Leger Dress, provides hundreds of discount and fashion Herve Leger Dress, sexy Herve Leger Dress, Herve Leger Skirt, disount Herve Leger Dress-a professional Herve Leger Shop.

# Posted By Brian Atwood maniac pumps on Saturday, August 28 2010 at 2:43 AM

24. Wonderful brian atwood shoes for your style. BRIAN ATWOOD High-heeled sandals Purple is in stock in our store only one size in 36.5 EU. Elegant purple color, you will like it.And these Pink Brian Atwood Maniac Patent Platform Pumps not only romantic and gorgeous too! It's patent leather leave us sunshine warmness and sexy! When I original saw these brian atwood loca studded pumps in a metallic version, a while ago, I likeable them OK, but now I am going unhinged for the lavender version!
And we also provide fabulous Christian Louboutin Shoes with 70% off and original quality and free shipping.Christian Louboutin Shoes online shop-Welcome to the best Christian Louboutin Shoes shop, we offer the fabulous Christian Louboutin Boots, Christian Louboutin Pumps, Christian Louboutin Sandals and other Christian Louboutin Shoes. Browse the variety of Christian Louboutin discount Shoes that at wholesale price but with high quality, you can find your favorite boots, Pumps and Sandals here.

# Posted By Brian Atwood loca studded pumps on Saturday, August 28 2010 at 2:44 AM

25. A grand wedding on the beach may be the common dream of most single girls. The bright sunshine, the blue sky and the open sea can satisfy all the demands of the romantic girls. Of course, everything will be perfect with a beach wedding dresses.
Every woman deserve the most beautiful wedding dresses at her special day!The most beautiful smile in the word is belong to the brides when she find her wedding dresses!Love is the time when you slows down in front of the shops selling wedding dresses.
Make the day of your engagement a special one with a A-line or princess wedding dresses!Step like a goddess in tea- length ball gowns,formal ball gowns,victorian ball gowns,debutante ball gowns,prom ball gowns, contemporary ball gownsand vintage ball gowns available in chiffon, organza, silk and satin only at weddingdressesnow.com.
Congratulations! Your little daughter is getting married! But being the mother of the bride (or MOB) is not an easy role. Once upon a time mothers of the bride did most of the wedding planning, and thus got to have their own dreams realized. First of all, choose one from the perfect mother of the bride dresses for yourself here and to be the most elegant mother of bride!
Flower girl dresses must be the perfect accessory for the bride's dress. The flower girls look like the bells ring in the wedding announcements as they toll down the aisle one by one or hand in hand. If you are having flower girls at your wedding, take a look at these beautiful selection of Flower girl dresses from http://www.weddingdressesin.com.

# Posted By A line wedding dresses on Saturday, August 28 2010 at 2:45 AM

26. 10828041930PMCabal gold | Cabal alz | Cabal money | cheap Cabal Alz |

# Posted By sad on Saturday, August 28 2010 at 8:18 AM

27. Shop popular stores to find juicy couture women's

fashions on sale - all in one place. Find it all here: JC handbags, shoes, tracksuits,

clothing, and more!mac cosmetics
mac makeup
christian louboutin shoes
christian louboutin
links of londonWhat a perfect thing, it attracted

all the attention, the miraculous birth of boundless charm. It is worthy of

appreciation and ownership.

# Posted By 59.32.56.46 on Monday, August 30 2010 at 9:35 AM

28. http://www.nfl-jersey.usMichael Vick (born June 26, 1980) is a professional http://www.nfl-jersey.us American football quarterback for the http://www.nfl-jersey.us Philadelphia Eagles of the http://www.nfl-jersey.us National Football League. As quarterback, Michael Vicks memorabilia and his replica jerseys-- http://www.nfl-jersey.us - Michael Vick jerseys have become one of the bestsellers for the NFL. The apparel and collectibles industry remains one of the largest revenue producing sectors of any sport, including the NFL. As fans flock to find their favorite gear, many seem to be lining up for anything pertaining to http://www.nfl-jersey.us Michael Vick and his tremendous contribution to the Atlanta Falcons and the National Football League. Michael Vick's athleticism and made-for-highlights play made his number “7” jersey one of the best selling jerseys not only in football but across all sports.Anyone attending an Atlanta Falcons home game saw a sea of that famous Vick jersey and even non-Falcons fans purchased http://www.nfl-jersey.us Michael Vick jerseys. That is until his legal woes precipitated his league suspension and discontinuation of the sale of http://www.nfl-jersey.us Michael Vick jerseys - the end of a lucrative deal not only for Michael Vick but also for the League. A quick check of merchandise offered by NFL.com reveals that although Michael Vick is serving suspensions, their jerseys are still available, http://www.nfl-jersey.us Michael Vick jerseys characteristics are heavier fabric with all sewn-on graphics matching those worn by the actual players. http://www.nfl-jersey.us Michael Vick jerseys are 100% nylon diamond back mesh body, Nylon dazzle sleeves and yoke, Team logo and player number shown at the chest.Player's name shown at the upper back on a sewn down nameplate with his number in the center ,player's number featured at both shoulders, Flat knit ribbed collar with NFL® Equipment patch sewn at the point in the front.

# Posted By Michael Vick Jerseys on Tuesday, August 31 2010 at 8:22 AM

29. Michael Vick's athleticism and made-for-highlights play made his number “7” jersey one of the best selling jerseys not only in football but across all sports.Anyone attending an Atlanta Falcons home game saw a sea of that famous Vick jersey and even non-Falcons fans purchased Michael Vick jerseys - the end of a lucrative deal not only for Michael Vick but also for the League. A quick check of merchandise offered by NFL.com reveals that although Michael Vick is serving suspensions, their jerseys are still available, Michael Vick jerseys are 100% nylon diamond back mesh body, Nylon dazzle sleeves and yoke, Team logo and player number shown at the chest.Player's name shown at the upper back on a sewn down nameplate with his number in the center ,player's number featured at both shoulders, Flat knit ribbed collar with NFL® Equipment patch sewn at the point in the front.

# Posted By skye on Tuesday, August 31 2010 at 8:23 AM

30.
(born April 29, 1983, in ) is an for the of the . He was drafted by the 11th overall in the . He played at .Cutler earned a selection with the Broncos in 2008, Within hours after the announcement from the Chicago Bears of the trade for quarterback Jay Cutler,the Jay Cutler jerseys become a fashionable jerseys arounld the world, Bears fans are thrilled, are the good gift to Bears fans. worn on the field by the favorite NFL players. are from NFL Equipment for a winning look on game day was engineered and constructed to duplicate the individual team and skill position utilizing similar fabrics and applications from the Pro Cut version. The features of are the nylon,body constructed of heavy-duty polyester mesh blend with nylon dazzle sleeves, reinforced v-neck with sewn-on NFL Equipment patch ,extended split drop tail replicates Pro Cut jersey silhouette,Reebok logoscreen-printed on each sleeve,reebok-NFL Equipment jock tag on front lower left bottom ,officially licensed by the NFL.

# Posted By Jay Cutler Jerseys on Wednesday, September 1 2010 at 8:48 AM

31. (born April 29, 1983, in ) is an for the of the . He was drafted by the 11th overall in the . He played at .Cutler earned a selection with the Broncos in 2008, Within hours after the announcement from the Chicago Bears of the trade for quarterback Jay Cutler,the Jay Cutler jerseys become a fashionable jerseys arounld the world, Bears fans are thrilled, are the good gift to Bears fans. worn on the field by the favorite NFL players. are from NFL Equipment for a winning look on game day was engineered and constructed to duplicate the individual team and skill position utilizing similar fabrics and applications from the Pro Cut version. The features of are the nylon,body constructed of heavy-duty polyester mesh blend with nylon dazzle sleeves, reinforced v-neck with sewn-on NFL Equipment patch ,extended split drop tail replicates Pro Cut jersey silhouette,Reebok logoscreen-printed on each sleeve,reebok-NFL Equipment jock tag on front lower left bottom ,officially licensed by the NFL.

# Posted By Jay Cutler Jerseys on Wednesday, September 1 2010 at 8:49 AM

32. ) is an of the 11th overall in the at selection with the Broncos in 2008, Within hours after the announcement from the Chicago Bears of the trade for quarterback Jay Cutler,the Jay Cutler jerseys become a fashionable jerseys arounld the world, Bears fans are thrilled, worn on the field by the favorite NFL players are the nylon,body constructed of heavy-duty polyester mesh blend with nylon dazzle sleeves, reinforced v-neck with sewn-on NFL Equipment patch ,extended split drop tail replicates Pro Cut jersey silhouette,Reebok logoscreen-printed on each sleeve,reebok-NFL Equipment jock tag on front lower left bottom ,officially licensed by the NFL.

# Posted By skye on Wednesday, September 1 2010 at 8:54 AM

33. This valuable editorial was very useful to read, I savored it completely. I'm about now to email it to my collegues to permit them examine this too. Thank you really.

Leicester Bank
Loans Unsecured Bad Credit

# Posted By Loan Hsbc on Wednesday, September 1 2010 at 12:21 PM

34. This valuable editorial was very useful to read, I savored it completely. I'm about now to email it to my collegues to permit them examine this too. Thank you really.

Loan Natwest
Personal Unsecured Loans Bad Credit
Loans Sainsburys
Loans Aa

# Posted By Loans Guarantor on Wednesday, September 1 2010 at 12:22 PM

35. I have been through the whole content of this blog which is very informative and knowledgeable stuff, so I would like to visit again.

Loans Egg
Loans Abbey
Alliance Loan
Unsecured Loans Guaranteed
Loans Very Bad Credit

# Posted By Loans Asda on Wednesday, September 1 2010 at 12:24 PM

36. I truly liked your incredible content. Please keep up the good work. Thank you very much!!!!

Leeds Loan
Loans for Bad Credit Rating
Loans Guaranteed Approval
Liverpool Loan
Loan Decision Online
Loans Best Deals
Loans Belfast
Loans Guaranteed Acceptance
Loans Edinburgh
Loans Low Credit Score
Unsecured Loans Company
Loans Quick Decision

# Posted By Leeds Loan on Wednesday, September 1 2010 at 12:26 PM

37. I am very interested in your article, I think your articles are so interesting that I need more information, go is berkaya and I will always support you. I say many thanks to you.

Unsecured Personal Loans Online
Unsecured Personal Loans Poor Credit
Loans Refused Credit
Orange Loans
Sky Loans
Cheap Unsecured Loans Bad Credit
Fast Unsecured Loans Bad Credit
Loans Bad Credit Ccjs
Loans Bad Credit Instant Decision
Loans Compare the Market
Loans Gocompare
Loans Money Supermarket
loans No Guarantor
Loans Northen Ireland
Loans Poor Credit Score
Loans Rbs
Loans Really Bad Credit
Loans Same Day Pay Out
Loans with Bad Credit History
Loans with Guarantor
Loans with No Fees
National Dept Support Centre
Quotation Please
Unsecured Loans Calculator
Unsecured Personal Loans Fair Credit

# Posted By Unsecured Personal Loans Instant Decision on Wednesday, September 1 2010 at 12:27 PM

38. Find ugg and Australian sheepskin boots, learn the history behind the Ugg boot, and when and what to wear with Cheap ugg boots, as well as cleaning and caring forAuthentic Ugg boots,Cheap ugg cardy boots,20%-40% high discount

# Posted By p on Wednesday, September 1 2010 at 2:06 PM

39. If you are a soccer fan so this is a right place for you to shop your soccer nfl jerseys. nfl store is the vital element uniform. Whatever your budget isnew nfl jerseys , through our wide selection we guarantee we have the right apparel for you. We guarantee the lowest prices in the market; nfl jerseys replica if you get a quote from our competitors with a lower price we will match it for you.

# Posted By fewrewree on Wednesday, September 1 2010 at 7:18 PM

40. linda
Gucci Designer handbags are not rightful simple leather lacoste Gucci Outlet men embroidered carrier items imperative for the jurisdiction of girlie items drink in toiletries, make-up and authorize UGG Boots. No girlfriend! An authentic designer MBT Shoes speaks volumes about you and implies that you are a witch of style, seasoning and UGG Boot. However, you power serve as assurance that having an authentic nike dunk is facade your carry through. You Cheap Gucci substitute wonderment if you passion to crack into MBT Discount savvy a blasting move shift you have your pocket dunk shoes and house till you dispatch to that unknown pace when you be credulous saved enough to buy your confess authentic designer bag.

# Posted By nike dunk on Thursday, September 2 2010 at 2:06 AM

41. Recently retired QB Kurt Warner is about to be honored with the immortalization of his jersey number -- but not by an NFL team.
The Arena Football League's Iowa Barnstormers will retire Warner's No. 13 this Friday. He will be on hand for the game as an announcer for the NFL Network.
"We think it's great for the Barnstormer fans to have him back," Barnstormers owner Jeff Lamberti told the Des Moines Register.
"He is clearly the most famous Iowa Barnstormer and most famous guy coming out of arena football. He's great for our league, and we're thrilled that he wants to broadcast our game."
Kurt Warner played three seasons for the Barnstormers and threw 183 TD passes for them before getting his shot in the NFL.
As part of a promotion for the game, the Barnstormers are lowering some ticket prices to $13 in honor of Warner.

# Posted By Kurt Warner on Thursday, September 2 2010 at 6:04 AM

42. As we all know, earrings are jewelry attached to the ear through a piercing in the earlobe or some other external part of the ear. Earrings are women's favorite. Proper Tiffany Bangles earrings can not only make a female look more beautiful, but also have the function of accommodating defects. Tiffany Cuff LinksSo it is necessary to know about how to wear earrings properly. Therefore, before you wear , you must take many factors into consideration, such as environment, your temperament, face shape, hairstyle, and your costume to reach the best effect.Wear Tiffany Accessories according to your face shape This will make your face look less plump. If you are long-faced, then you'd better choose Tiffany Sets hoop earrings or big earrings to make your face look more fetching. If you have a square-shape face, then dapper stud earrings, long drop earrings or exaggerated earrings can make you look livelier My discount silver tiffany
necklace
Blog.

# Posted By silver tiffany necklace on Thursday, September 2 2010 at 7:05 AM

43. louis vuitton
louis vuitton handbags
louis vuitton handbag
louis vuitton bags
louis vuitton bag
replica handbags

# Posted By ss on Thursday, September 2 2010 at 7:33 AM

Add a Comment

(If you leave this blank, your IP address will be displayed instead)

(Optional, will not be displayed on the site)