Class: Array
- Inherits:
-
Object
- Object
- Array
- Defined in:
- lib/leaf/core_ext.rb,
lib/leaf/array.rb
Overview
helper to check for method existance in ruby 1.8- and 1.9-compatible way because ‘methods`, `instance_methods` and others return strings in 1.8 and symbols in 1.9
['foo', 'bar'].include_method?(:foo) # => true
Direct Known Subclasses
Instance Method Summary collapse
- #include_method?(name) ⇒ Boolean
-
#paginate(options = {}) ⇒ Object
Paginates a static array (extracting a subset of it).
Instance Method Details
#include_method?(name) ⇒ Boolean
9 10 11 12 |
# File 'lib/leaf/core_ext.rb', line 9 def include_method?(name) name = name.to_sym !!(find { |item| item.to_sym == name }) end |
#paginate(options = {}) ⇒ Object
Paginates a static array (extracting a subset of it). The result is a Leaf::Collection instance, which is an array with a few more properties about its paginated state.
Parameters:
-
:page
- current page, defaults to 1 -
:per_page
- limit of items per page, defaults to 30 -
:total_entries
- total number of items in the array, defaults toarray.length
(obviously)
Example:
arr = ['a', 'b', 'c', 'd', 'e']
paged = arr.paginate(:per_page => 2) #-> ['a', 'b']
paged.total_entries #-> 5
arr.paginate(:page => 2, :per_page => 2) #-> ['c', 'd']
arr.paginate(:page => 3, :per_page => 2) #-> ['e']
This method was originally suggested by Desi McAdam
23 24 25 26 27 28 29 30 |
# File 'lib/leaf/array.rb', line 23 def paginate( = {}) raise ArgumentError, "parameter hash expected (got #{.inspect})" unless Hash === Leaf::Collection.create [:page] || 1, [:per_page] || 30, [:total_entries] || self.length do |pager| pager.replace self[pager.offset, pager.per_page].to_a end end |