active-hash / active_hash

A readonly ActiveRecord-esque base class that lets you use a hash, a Yaml file or a custom file as the datasource
MIT License
1.2k stars 179 forks source link

ActiveHash scope affecting self #257

Closed mogya closed 1 year ago

mogya commented 2 years ago

Define scope on ActiveHash class and calling it, seems polluting original object.

reproduce

class Country < ActiveHash::Base
  self.data = [
    {:id => 1, :name => "US"},
    {:id => 2, :name => "Japan"}
  ]
  scope :east_asia, -> do
    where(name: "Japan")
  end
end

irb(main):054:0> c = Country.all
=> 
#<ActiveHash::Relation:...
irb(main):055:0> c.count
=> 2
irb(main):056:0> c.east_asia
=> 
#<ActiveHash::Relation:...
irb(main):057:0> c.count
=> 1

expected behavior

c.count should returns 2 because ActiveRecord scope returns new relation and do not affect to self.

environment

irb(main):058:0> ActiveHash::gem::VERSION
=> "3.1.1"
irb(main):063:0> Rails::VERSION::STRING
=> "7.0.3.1"
pfeiffer commented 1 year ago

The same happens with simply using where on a scope. A failing test:


countries = Country.where(language: "English")

expect(countries.size).to eq 2
expect(countries.where(name: "US").size).to eq 1 # ✅
expect(countries.size).to eq 2 # 🤯 fails as the previous line mutated the scope!
pfeiffer commented 1 year ago

Fixed in #265

kbrock commented 1 year ago

Thank you for helping us with this solution. Going with #268 instead