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.19k stars 178 forks source link

Bugfix: Use correct value for field attributes when default field value is `false` #274

Closed ihollander closed 1 year ago

ihollander commented 1 year ago

Given a class with a default value of false for a field:

class Country < ActiveHash::Base
  field :active, default: false

  self.data = [
    {:id => 1, :name => "US", :active => true},
    {:id => 2, :name => "Canada"}
  ]
end

I'd expect that accessing the field would return false when accessed via the attributes hash or via the method for the field:

Country.find(2)[:active]            # false
Country.find(2).attributes[:active] # false
Country.find(2).active              # false

But the attributes hash returns nil (tho the method for the field works as expected and returns false):

Country.find(2)[:active]            # nil
Country.find(2).attributes[:active] # nil
Country.find(2).active              # false

This PR fixes this behavior by ensuring the default value is correctly set as long as there's a key of default passed to the field method.

I added a spec for this bug, saw it fail, made the change, and confirmed all specs pass.