Discussion Forums
- Topic List
- Most Recent Posts
- Sign In for more options
Hy,
I'm more or less new to rails and I'm trying to make a plugin that gives some extra methods to the model. These methods will be different, here is an example of how it would be used in the model:
class Image < ActiveRecord::Base # these are the default options for the find method tottys_paginate :comments, {:conditions => 'bla bla', :from => 'comments AS c'} tottys_paginate :images, {:conditions => 'bla bla', :order => 'bla bla', :from => 'images AS i'}
def example
# these conditions are only for this query and will be merged with the default options, setted before.
comments = self.comments_tpaginate({:conditions => 'bla bla', :select => 'c.id, c.created_at...'})
images = self.images_tpaginate({:conditions => 'bla bla', :select => 'i.id, i.created_at...'})
end end
how can i make the structure of the plugin in order to work this way?
i made this plugin until like this but i dont know how to have separate default options for comments and for images and then merge them when i call the eval methods(comments_tpaginate OR images_tpaginate)
module TottysPaginate
def self.included(base)
base.send :extend, ClassMethods
end
module ClassMethods
def tottys_paginate(target, default_options)
empty_options = { :select => '',
:conditions => '',
:from => '',
:order => '',
:limit => '',
:offset => ''}
@default_options = empty_options.update(default_options) if default_options.is_a?(Hash)
ActiveRecord::Base.send :include, TottysPaginate::InstanceMethods
class_eval < !o[:count_conditions].blank? ? o[:count_conditions] : ( !o[:select_conditions].blank? ? o[:select_conditions] : o[:conditions]),
# count from OR select from OR from
:from => !o[:count_from].blank? ? o[:count_from] : (!o[:select_from].blank? ? o[:select_from] : o[:from]))
end
# if we pass the offset, will be use that offset
o[:offset] = !o[:offset].blank? ? o[:offset] : o[:limit].to_i * ( o[:current_page].to_i - 1 )
# convert current_page to a number
if(o[:current_page]) then o[:current_page] = o[:current_page].to_i end
# select items
o[:data] = self.class.find(:all,
:select => o[:select],
# select conditions OR conditions
:conditions => !o[:select_conditions].blank? ? o[:select_conditions] : o[:conditions],
# select from OR from
:from => !o[:select_from].blank? ? o[:select_from] : o[:from],
:limit => o[:limit],
:offset => o[:offset],
:order => o[:order])
o
end
end end
ActiveRecord::Base.send :include, TottysPaginate
My advice would be to try Mislav's will_paginate plugin http://github.com/mislav/will_paginate
