Agile Web Development

Build it. Launch it. Love it.

Acts as Toucher

Problem:

You have two models in your domain and one interacts with the other in various ways. You want to have a record of certain types of interactions that one model has with the other.

For example, you have a User model and a File model. You want a record of when a particular User views or edits a File.

HowTo:

First, create and run a Rails migration resembling the following:

  class ActsAsRecentlyTouchedStructure < ActiveRecord::Migration
    def self.up
      create_table :touch_records do |t|
        t.column :created_at, :datetime
        t.column :touched_id, :integer
        t.column :touched_type, :string
        t.column :toucher_id, :integer
        t.column :toucher_type, :string
      end
    end

    def self.down
      drop_table :touch_records
    end
  end

Then, suppose we are talking about the above described User/File scenario. In such a scenario, you can do something like this from within your User class:

  class User < ActiveRecord::Base
    acts_as_toucher :on => :file
  end

Then you can do this:

  @user = User.find(1)
  @file = File.find(1)
  @file2 = File.find(2)
  @user.touch_file(@file)
  @user.touch_file(@file2)
  @user.touch_file(@file)
  @my_ten_recently_touched_files = @user.touched_files(10)

It’s also possible to specify an array/list for the :on option to acts_as_toucher. For instance:

  class User < ActiveRecord::Base
    acts_as_toucher :on => [ :file, :directory ]
  end

Vitals

Home http://www.crowdedweb.com/articles/2006/08/21/acts_as_toucher-ruby-on-rails-plugin
Repository svn://rubyforge.org/var/svn/acts-as-toucher
License
Tags Tag_red
Rating (2 votes)
Owner Bosko Milekic
Created 8 September 2006

Comments

  • ctran
    8 September 2006

    Sounds a lot like acts_as_audited...

  • Avatar
    25 November 2006

    It's similar to acts_as_audited, but not the same. acts_as_audited is wired to work with a user and is used from a controller. acts_as_toucher is model-to-model.

    I threw this together quite a while ago and only found this plugin repository recently, so there may very well be another plugin similar in style floating around. :-)

Add a comment