Topic: Help: DRYer Class Methods

I have several models that make use of the same class methods in a controller. Writing these methods into each model doesn't seem very DRY... how do I make them accessible to my controllers without rewriting them in each model?

For example, in a controller, I'd like to use the find_ascending class method for the Category and Subcategory models:

@categories = Category.find_ascending
@subcategories = Subcategory.find_ascending

I have the following class method in both the Category and Subcategory models:

# Finds all rows and orders them ascendingly
def self.find_ascending
    find(:all, :order => "position ASC")
end

What's the best practice here? Thanks.

Re: Help: DRYer Class Methods

#/lib/my_super_methods.rb
module MySuperMethods
   def self.find_ascending
     find(:all, :order => "position ASC")
  end
end

#model
class Category < ActiveRecord::Base
  extend MySuperMethods
  #or for Instance methods:
  include MySuperMethods
end

Re: Help: DRYer Class Methods

Awesome! Just needed to remove "self" from the find_ascending method and it worked like a charm. So now it reads:

module MySuperMethods
   
    # Finds all rows and orders them ascendingly
    def find_ascending
        find(:all, :order => "position ASC")
    end

end


Thanks, Duplex!

Re: Help: DRYer Class Methods

ops, yeah, did a copy/paste from your code, sorry wink