From e5ca5ad89509bcaf9d90f782e3e669a0aec6c6f7 Mon Sep 17 00:00:00 2001 From: Mike Dalessio Date: Wed, 3 Jul 2024 12:23:17 -0400 Subject: [PATCH] fix: ensure the stored field names are always symbols There is code that assumes that `@field_names` will contain symbols, like this method in ActiveHash::Base: def respond_to?(method_name, include_private=false) super || begin config = configuration_for_custom_finder(method_name) config && config[:fields].all? do |field| field_names.include?(field.to_sym) || field.to_sym == :id end end end --- lib/active_hash/base.rb | 7 +++++-- spec/active_hash/base_spec.rb | 10 ++++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/lib/active_hash/base.rb b/lib/active_hash/base.rb index 4a36b03..901cdb7 100644 --- a/lib/active_hash/base.rb +++ b/lib/active_hash/base.rb @@ -198,7 +198,9 @@ def fields(*args) end def field(field_name, options = {}) + field_name = field_name.to_sym validate_field(field_name) + field_names << field_name add_default_value(field_name, options[:default]) if options.key?(:default) @@ -210,7 +212,8 @@ def field(field_name, options = {}) end def validate_field(field_name) - if [:attributes].include?(field_name.to_sym) + field_name = field_name.to_sym + if [:attributes].include?(field_name) raise ReservedFieldError.new("#{field_name} is a reserved field in ActiveHash. Please use another name.") end end @@ -264,7 +267,7 @@ def add_default_value field_name, default_value end def define_getter_method(field, default_value) - unless instance_methods.include?(field.to_sym) + unless instance_methods.include?(field) define_method(field) do attributes[field].nil? ? default_value : attributes[field] end diff --git a/spec/active_hash/base_spec.rb b/spec/active_hash/base_spec.rb index 9cec450..0af1a45 100644 --- a/spec/active_hash/base_spec.rb +++ b/spec/active_hash/base_spec.rb @@ -106,6 +106,16 @@ class Country < ActiveHash::Base end end + describe ".field_names" do + before do + Country.fields :name, :iso_name, "size" + end + + it "returns an array of field names" do + expect(Country.field_names).to eq([:name, :iso_name, :size]) + end + end + describe ".data=" do before do class Region < ActiveHash::Base