Created
May 17, 2012 05:05
-
-
Save practicingruby/2716553 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def object(&block) | |
| Object.new.tap { |obj| obj.singleton_class.instance_eval(&block) } | |
| end | |
| def struct(*args) | |
| Struct.new(*args) | |
| end | |
| def method(*a, &b) | |
| define_method(*a, &b) | |
| end | |
| def main(&block) | |
| block.call | |
| end | |
| ######################################### | |
| # The above enables the syntax below... # | |
| ######################################### | |
| page = object { | |
| constructor = struct(:items, :page_number) | |
| method(:new) { |*args| constructor.new(*args) } | |
| } | |
| paginator = object { | |
| method(:paginate) { |items_per_page, collection| | |
| collection.each_slice(items_per_page).map.with_index do |items, index| | |
| page.new(items, index + 1) | |
| end | |
| } | |
| } | |
| main { | |
| pages = paginator.paginate(3, [:a,:b,:c,:d,:e,:f,:g,:h,:i]) | |
| p pages.map { |page| page.items.join(",") } #=> ["a,b,c", "d,e,f", "g,h,i"] | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment