diff --git a/lib/active_file/base.rb b/lib/active_file/base.rb index 60fd1ed2..83b0b0b5 100644 --- a/lib/active_file/base.rb +++ b/lib/active_file/base.rb @@ -49,7 +49,7 @@ def actual_root_path end protected :actual_root_path - [:find, :find_by_id, :all, :where, :method_missing].each do |method| + [:find, :find_by_id, :all, :where, :method_missing, :find_each].each do |method| define_method(method) do |*args, &block| reload unless data_loaded return super(*args, &block) diff --git a/lib/active_hash/base.rb b/lib/active_hash/base.rb index c94fa153..ab437621 100644 --- a/lib/active_hash/base.rb +++ b/lib/active_hash/base.rb @@ -189,7 +189,7 @@ def all(options = {}) relation end - delegate :where, :find, :find_by, :find_by!, :find_by_id, :count, :pluck, :ids, :pick, :first, :last, :order, to: :all + delegate :where, :find_each, :find, :find_by, :find_by!, :find_by_id, :count, :pluck, :ids, :pick, :first, :last, :order, to: :all def transaction yield diff --git a/lib/active_hash/relation.rb b/lib/active_hash/relation.rb index 59d57b93..47b9afdb 100644 --- a/lib/active_hash/relation.rb +++ b/lib/active_hash/relation.rb @@ -7,6 +7,8 @@ class Relation delegate :empty?, :length, :first, :second, :third, :last, to: :records delegate :sample, to: :records + alias find_each each + attr_reader :conditions, :order_values, :klass, :all_records def initialize(klass, all_records, conditions = nil, order_values = nil) diff --git a/spec/active_file/base_spec.rb b/spec/active_file/base_spec.rb index 4bd99976..1daff629 100644 --- a/spec/active_file/base_spec.rb +++ b/spec/active_file/base_spec.rb @@ -32,6 +32,23 @@ class Bar < ActiveFile::Base end end + describe ".find_each" do + before do + class Country + def self.load_file() + [{"name"=>"Niger", "id"=>1}, {"name"=>"Peru", "id"=>2}] + end + end + end + + it "iterates over the data" do + first_letters = "" + expect do + Country.find_each { |country| first_letters += country.name[0] } + end.to change { first_letters }.to("NP") + end + end + describe ".set_filename" do before do Country.set_filename "foo-izzle" diff --git a/spec/active_hash/base_spec.rb b/spec/active_hash/base_spec.rb index 105ee763..4ff3099a 100644 --- a/spec/active_hash/base_spec.rb +++ b/spec/active_hash/base_spec.rb @@ -369,6 +369,26 @@ class Region < ActiveHash::Base end end + describe ".find_each" do + before do + Country.field :name + Country.field :language + Country.data = [ + {:id => 1, :name => "US", :language => 'English'}, + {:id => 2, :name => "Canada", :language => 'English'}, + {:id => 3, :name => "Mexico", :language => 'Spanish'} + ] + end + + it "iterates over data" do + logs = [] + Country.where(language: 'English').find_each do |country| + logs << "visited #{country.name}" + end + expect(logs).to eq(["visited US", "visited Canada"]) + end + end + describe ".invert_where" do before do Country.field :name