iLeonux

Make your own rails plugin

by admin on Apr.12, 2008, under Ruby on Rails

Suppose to make a plugin named ‘acts_as_user_owned’, which will make the column ‘created_by’ as the foreign key to User model ( and updated_by ).

You can make it as the official way:
start from: ruby script/generate plugin acts_as_user_owned
or
just make a file ‘acts_as_user_owned.rb’ into lib.

Then edit vender/plugin/acts_as_user_owned/lib/acts_as_user_owned.rb (or lib/acts_as_user_owned.rb) :

1
2
3
4
5
6
7
8
module ActsAsUserOwned
  def acts_as_user_owned
    belongs_to :creator, :foreign_key => "created_by", :class_name => "User"
    belongs_to :updator, :foreign_key => "updated_by", :class_name => "User"
 
    User.class_eval "has_many: #{self.to_s.tableize}, :foreign_key => :created_by"
  end
end

To inject this method into each model, write the following two lines into vender/plugin/acts_as_user_owned/init.rb (or append to lib/acts_as_user_owned.rb):

1
2
require 'acts_as_user_owned'
ActiveRecord::Base.extend ActsAsUserOwned

Usage: just add ‘acts_as_user_owned’ to the model you want it acts as user owned.

Done, enjoy it!

No comments for this entry yet...

Leave a Reply

You must be logged in to post a comment.

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...