Skip to content

Instantly share code, notes, and snippets.

@simonc
Created May 25, 2012 10:41
Show Gist options
  • Save simonc/2787243 to your computer and use it in GitHub Desktop.
Save simonc/2787243 to your computer and use it in GitHub Desktop.

Revisions

  1. Simon COURTOIS created this gist May 25, 2012.
    11 changes: 11 additions & 0 deletions README.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,11 @@
    This is an example implementation of `find_each` with ActiveResource

    ## Dependencies:

    ### API:

    * has_scope

    ### Client:

    * rails (> 3)
    11 changes: 11 additions & 0 deletions cities_controller.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,11 @@
    # API side
    # app/controllers/cities_controller.rb

    class CitiesController
    has_scope :limit
    has_scope :offset

    def index
    @cities = apply_scopes(City).all
    end
    end
    8 changes: 8 additions & 0 deletions city.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,8 @@
    # Client side
    # app/models/city.rb

    class City < ActiveResource::Base
    self.site = "http://api.example.com"

    include Concerns::Batches
    end
    30 changes: 30 additions & 0 deletions concerns-batches.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,30 @@
    # Client side
    # app/models/concerns/batches.rb
    module Concerns
    module Batches
    extend ActiveSupport::Concern

    module ClassMethods
    def find_in_batches(options={})
    start = options.delete(:start).to_i
    batch_size = options.delete(:batch_size) || 1000

    begin
    records = find(:all, params: { offset: start, limit: batch_size })
    records_size = records.size
    start += batch_size

    yield records

    break if records_size < batch_size
    end while records.any?
    end

    def find_each(options={})
    find_in_batches(options) do |records|
    records.each { |record| yield record }
    end
    end
    end
    end
    end