Skip to content

Instantly share code, notes, and snippets.

@practicingruby
Created May 17, 2012 05:05
Show Gist options
  • Select an option

  • Save practicingruby/2716553 to your computer and use it in GitHub Desktop.

Select an option

Save practicingruby/2716553 to your computer and use it in GitHub Desktop.
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