Extending ActiveRecord with a Mixin

So in the last post we got to the point where a model class has been modified to be able to access associated classes in a simple way. Now we want to add this functionality to all model classes, that is, those which are a sub class of ActiveRecord::Base.

Ruby Mixins

If you have done any digging into Ruby (get a Pickaxe!), you should know the OO basics like class extensions, inheritance, class methods etc. I’m assuming this much anyway – there are thousands of Ruby OO examples and tutorials out there, you can’t avoid it.

A Mixin is a way of modifying the functionality of a class by ‘applying’ a module to it. This is how I understand the technology anyway:

  • You write a module with the methods you want ‘bolted on’ to your base class.
  • You extend your base class with that module (there are multiple ways to do this).

It is a handy work around for multiple inheritence (which Ruby does not support), as you can mixin any number of modules with a class. Again, there are hundreds of Mixin introductions available on the almighty Google, so I’m not going to explain the path to my understanding of Mixins, I’m just going to show you how I have used them.

So, on with the module writing.

module ModelExtensions

  public

  def get_associated_model_classes(type = :belongs_to)

    # no need for self here, the method is being added to the class

    # (eventually)

    aggregate_objs = self.reflect_on_all_associations(type)

    aggregate_objs.map {|m| m.klass}

    # let’s use this elegant array builder eh?

  end

end

I’ve put this code in /lib/model_extensions.rb – Rails will be able to pick this up automatically for use elsewhere.

If I have understood my Pickaxe correctly, all method calls in Ruby are ultimately messages being sent to the receiver object. Because of this, it is quite simple to extend AR::Base without declaring the class or editing any code other than the functionality you want to add. To apply our Mixin, we have to tell AR:Bass to extend itself with the contents of our module, ModelExtensions. I’ve added the following to the end of /config/environment.rb:

require ‘model_extensions’

# Lib is available to Rails as it’s in the /lib directory!

ActiveRecord::Base.send(:extend, ModelExtensions)

# Send the message to AR::Base to extend using our module

 

Ok let’s fire up the console and test the experiment.

C:\vhost\cdb>ruby script/console

Loading development environment.

>> Currency.get_associated_model_classes :has_many

=> [Spend]

This shows that the method works for all model classes (declared as an extension to AR::Base) and that it also works for different associations. Job done!

Bringing it all together

There’s a final part to this solution, involving some new class functionality and a new helper. With any luck I’ll get it online before the weekend.

9 Comments »

  1. Julian Schrader said,

    August 6, 2006 @ 3:04 pm · Edit

    Hi Keeran,

    some time ago, Mark [1] wrote about how he organizes his workflow. Your comment stated that you’re developing something similar in Rails.

    I’m a pupil and currently playing around with RoR – I wanted to code a ‚Äúworkflow‚Äù app to organize the work of the members of our pupils magazine.

    Is it possible for you to provide me with some of your code to look at as an example? It’d be very nice – thanks in advance!

    Cheers,
    Julian

    [1] http://www.markboulton.co.uk/journal/comments/sorting_my_workflow_out_part_two/

  2. keeran said,

    August 6, 2006 @ 3:25 pm · Edit

    Hi Julian,

    We will be making source code available for parts of the project, but not the application as a whole I’m afraid.

    Is there anything specific you need help with? Please feel free to ask away and I’ll help where I can!

    Keeran

  3. Julian Schrader said,

    August 6, 2006 @ 4:34 pm · Edit

    Hi Keeran,

    No, there’s no specific problem. I just like to dive into working code, make some changes here and there to get to know how it works.

    Thank you for your offer, I’ll come back ;-)

    Julian

  4. salenko said,

    May 30, 2007 @ 7:00 am · Edit

    Sorry, but I am buy pure watch for frend here – Europe Relica Watches
    Rolex… replica :)

  5. Vesegesia said,

    February 8, 2008 @ 8:17 am · Edit

    Hi!
    A wallpaper image can be in a JPEG or a GIF file format. Our goal is to provide you with the best collection of images for use as desktop backgrounds. You can download wallpapers widescr
    een
    very easy.
    Download it all)

  6. ruspetriot said,

    February 14, 2008 @ 8:36 am · Edit

    Hello! guys please tell me where can I found free pron

  7. skyloads said,

    February 25, 2008 @ 3:35 pm · Edit

    XRumer is the best program for advertisement!
    It’s have CAPTCHA recognizer, email verificator, and a lot of other functions…

    XRumer is the premier automated link-building tool. Through the use of this tool you will see a significant increase in the number of unique visitors to your site, as well as see your site jump in the search engine result pages. The tool is popular among both novices and gurus because of both its flexibility, power, and effectiveness. XRumer is extremely reliable and its fully automated workflow makes link-building a breeze.

    1. Software is able to work with lots of different types of forums and guestbooks: phpBB and PHP-Nuke with any modifications, yaBB, VBulletin, Invision Power Board, IconBoard, UltimateBB, exBB, phorum.org, wiki, different types of bulletin boards and even custom-written code.
    1. Attention: unique feature – software works around EVERY possible type of protection from automatic registration, including: – Pictocode protection (tickets, captcha), which look something like: “Enter the number you see in the box”. – E-mail activation protection. – Java-script protection.

    More info…

  8. BrrForYouu said,

    March 15, 2008 @ 8:54 am · Edit

    Dear Gentlemen!
    If you want to find your partner abroad for a serious relationship, love or
    marriage – register with our agency and be happy! By using our contact
    agency, you will have a real opportunity to achieve your aims happily and
    safely!
    We solve the problem of loneliness.To this end you only need to place the
    information on our site, filling in the questionnaire and sending a photo is
    FREE! Take the questionnaire.
    Here you will see that you can create the profile which may totally change
    your destiny!
    http://www.ladies-russia.net/MenInfo.php – Application form for YOU
    [url=http://www.ladies-russia.net/MenInfo.php]Application form for YOU[/url]

    Good Luck!
    http://www.ladies-russia.net

  9. Dymnengeday said,

    April 12, 2010 @ 4:40 am · Edit

    Hey Everybody…

    Recently I’ve navigated the internet for a Blackberry supported [url=http://www.frompo.com][b]internet search engine[/b][/url].

    MSN & the regular web type search engines unfortunately don’t work.

    Has anybody heard/seen a site like [url=http://www.frompo.com][b]Frompo.com[/b][/url] – apparently works great web phone search engine – but I thought I’d ask anyway.

    What is the best mobile phone search engine?

RSS feed for comments on this post · TrackBack URI

Leave a Comment