From 32c73429357cc3571961a371197054525ea94847 Mon Sep 17 00:00:00 2001 From: Chris Gunther Date: Thu, 7 Mar 2024 15:56:43 -0500 Subject: [PATCH] Define `respond_to?` on `RecordRef` to match `method_missing` behavior `RecordRef`s often include a name, which allows access via `method_missing` by calling `record_ref.name`, however if no referenced record is assigned, you'll still get a `RecordRef` instance, it just wont have any fields, so `record_ref.name` raised a `NoMethodError`, but if you checked for the field first via `record_ref.respond_to?(:name)`, it'd be falsey regardless of whether the field existed or not. Defining `respond_to?` in good practice alongside `method_missing`. Ideally, `respond_to_missing?` would be used instead, as that enables access to the method like `record_ref.method(:name)`, however I kept with `respond_to?` to match `CustomFieldList`. `CustomRecordRef` also uses `method_missing`, however there's no specs and I'm not familiar with that record, so I left it alone. --- HISTORY.md | 1 + lib/netsuite/records/record_ref.rb | 5 +++++ spec/netsuite/records/record_ref_spec.rb | 8 ++++++++ 3 files changed, 14 insertions(+) diff --git a/HISTORY.md b/HISTORY.md index e689e70de..8e906dbcf 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -6,6 +6,7 @@ ### Fixed * Revert recent proxy changes which breaks proxy usage by @andrewdicken-stripe in https://github.com/NetSweet/netsuite/pull/579 +* Define `respond_to?` on `RecordRef` to match `method_missing` behavior (#) ### Breaking Changes diff --git a/lib/netsuite/records/record_ref.rb b/lib/netsuite/records/record_ref.rb index 1ada59644..e5c96c46e 100644 --- a/lib/netsuite/records/record_ref.rb +++ b/lib/netsuite/records/record_ref.rb @@ -33,6 +33,11 @@ def method_missing(m, *args, &block) end end + def respond_to?(m, include_private = false) + return true if attributes.keys.map(&:to_sym).include?(m.to_sym) + super + end + end end end diff --git a/spec/netsuite/records/record_ref_spec.rb b/spec/netsuite/records/record_ref_spec.rb index 162f33ee9..f8503f3df 100644 --- a/spec/netsuite/records/record_ref_spec.rb +++ b/spec/netsuite/records/record_ref_spec.rb @@ -40,8 +40,16 @@ context 'readers' do it 'can take on arbitrary attributes into itself on initialization' do + expect(record_ref).to respond_to(:name) + expect(record_ref).to respond_to('name') expect(record_ref.name).to eql('This is a record_ref') + + expect(record_ref).to respond_to(:banana) + expect(record_ref).to respond_to('banana') expect(record_ref.banana).to eql('for monkeys') + + expect(record_ref).to_not respond_to(:non_existant_field) + expect(record_ref).to_not respond_to('non_existant_field') end end end