How to extend DataMapper :: Resource using a custom method

I have the following code:

module DataMapper
  module Resource

   @@page_size = 25

   attr_accessor :current_page  
   attr_accessor :next_page
   attr_accessor :prev_page

  def first_page?
    @prev_page
  end

  def last_page?
    @next_page      
 end

  def self.paginate(page)
    if(page && page.to_i > 0)
      @current_page = page.to_i - 1
    else
      @current_page = 0
    end

    entites = self.all(:offset => @current_page  * @@page_size, :limit => @@page_size + 1)

    if @current_page > 0
      @prev_page = @current_page
    end

    if entites.size == @@page_size + 1
      entites.pop
      @next_page = (@current_page || 1) + 2
    end

    entites
  end
end

end

Then I have a #paginate call:

@photos = Photo.paginate(params[:page])

And getting the following error:

application error
NoMethodError at /dashboard/photos/
undefined method `paginate' for Photo:Class

In Active record, this concept is great for me ... I use JRuby for notification. What am I doing wrong?

+3
source share
1 answer

Andrew

You can represent DataMapper :: Resource as an instance (row) and DataMapper :: Model as a class (table). Now, to change the default features at the resource or model level, you can either add inclusions or extensions to your model.

#paginate . #page, , .

module Pagination
  module ClassMethods
    def paginate(page)
      # ...
    end
  end
  module InstanceMethods
    def page
      # ...
    end
  end
end

, #paginate , :

DataMapper::Model.append_extensions(Pagination::ClassMethods)

, :

DataMapper::Model.append_inclusions(Pagination::InstanceMethods)

, !

+12

Source: https://habr.com/ru/post/1759379/


All Articles