Skip to content

Commit

Permalink
fix: ensure the stored field names are always symbols
Browse files Browse the repository at this point in the history
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
  • Loading branch information
flavorjones committed Jul 3, 2024
1 parent 24579e9 commit e5ca5ad
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
7 changes: 5 additions & 2 deletions lib/active_hash/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down
10 changes: 10 additions & 0 deletions spec/active_hash/base_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit e5ca5ad

Please sign in to comment.