Peter Giacomo Lombardo
Peter Giacomo Lombardo

Reputation: 712

How to make Ruby Modules Dynamic?

I have four models, User, Profile, Badge, and Membership, that have almost identical previous and next methods. The following example is from my User model.

def next
  self.class.find :first, 
                  :conditions => [ "created_at > ? AND user_id = ?",
                                   self.created_at, self.user_id ], 
                  :order => "created_at ASC"
end

def previous
  self.class.find :first, 
                  :conditions => [ "created_at < ? AND user_id = ?",
                                   self.created_at, self.user_id ], 
                  :order => "created_at DESC"
end

Instead of having the essentially same methods repeated four times once for each model, I'm attempting to put these methods into an external module Extensions::Utility so that each model can include Extensions::Utility.

What is the best way to implement this method so that it supports dynamic substitution of user for other models?

My environment is Ruby/Rails 3.0.6.

Upvotes: 2

Views: 305

Answers (2)

sawa
sawa

Reputation: 168269

Tilo's answer has a point. I changed the method next to nekst.

module Extensions
  module Utility
    def id; "#{self.class.downcase}_id" end

    def nekst
      self.class.find :first, 
                      :conditions => [ "created_at > ? AND #{id} = ?",
                                       self.created_at, self.send(id) ], 
                      :order => "created_at ASC"
    end

    def previous
      self.class.find :first, 
                      :conditions => [ "created_at < ? AND #{id} = ?",
                                       self.created_at, self.send(id) ], 
                      :order => "created_at DESC"
    end
  end
end

Upvotes: 2

Tilo
Tilo

Reputation: 33752

Be aware that "next" is a keyword in the Ruby language!!

I would recommend not to define any methods with names that are part of the Ruby language..

Upvotes: 2

Related Questions