Class: MR::PagedQuery

Inherits:
Query
  • Object
show all
Defined in:
lib/mr/query.rb

Defined Under Namespace

Modules: PageNumber, PageOffset, PageSize

Instance Attribute Summary collapse

Attributes inherited from Query

#model_class, #relation

Instance Method Summary collapse

Methods inherited from Query

#count, #count!, #first, #first!, #paged, #results, #results!

Constructor Details

#initialize(query, page_num = nil, page_size = nil) ⇒ PagedQuery

Returns a new instance of PagedQuery.



71
72
73
74
75
76
77
78
79
# File 'lib/mr/query.rb', line 71

def initialize(query, page_num = nil, page_size = nil)
  @page_num    = PageNumber.new(page_num)
  @page_size   = PageSize.new(page_size)
  @page_offset = PageOffset.new(@page_num, @page_size)

  @unpaged_relation = query.relation.dup
  relation = query.relation.offset(@page_offset).limit(@page_size)
  super query.model_class, relation
end

Instance Attribute Details

#page_numObject (readonly)

Returns the value of attribute page_num.



69
70
71
# File 'lib/mr/query.rb', line 69

def page_num
  @page_num
end

#page_offsetObject (readonly)

Returns the value of attribute page_offset.



69
70
71
# File 'lib/mr/query.rb', line 69

def page_offset
  @page_offset
end

#page_sizeObject (readonly)

Returns the value of attribute page_size.



69
70
71
# File 'lib/mr/query.rb', line 69

def page_size
  @page_size
end

Instance Method Details

#has_next_page?Boolean

Returns:

  • (Boolean)


92
93
94
# File 'lib/mr/query.rb', line 92

def has_next_page?
  @has_next_page ||= (self.page_offset + self.page_size) < self.total_count
end

#is_last_page?Boolean

Returns:

  • (Boolean)


96
97
98
# File 'lib/mr/query.rb', line 96

def is_last_page?
  !self.has_next_page?
end

#total_countObject



81
82
83
# File 'lib/mr/query.rb', line 81

def total_count
  @total_count ||= total_count!
end

#total_count!Object

This isn’t done in the ‘initialize` because it runs a query (which is expensive) and should only be done when it’s needed. If it’s never used then, running it in the ‘initialize` would be wasteful.



88
89
90
# File 'lib/mr/query.rb', line 88

def total_count!
  @total_count = total_count_relation.count
end