From 890e08ae0a6ec2ac7e9168783566d5c9875e8c04 Mon Sep 17 00:00:00 2001 From: James Wong Date: Tue, 11 Jul 2017 10:50:59 -0400 Subject: [PATCH] method_missing for missing attr https://github.com/ansible/ansible_tower_client_ruby/issues/95 --- lib/ansible_tower_client/base_model.rb | 12 ++++++++++++ spec/base_model_spec.rb | 3 ++- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/lib/ansible_tower_client/base_model.rb b/lib/ansible_tower_client/base_model.rb index 121b894..11f5e88 100644 --- a/lib/ansible_tower_client/base_model.rb +++ b/lib/ansible_tower_client/base_model.rb @@ -10,6 +10,18 @@ def self.endpoint base_class.to_s.split(/::/)[1].tableize.to_s.freeze end + def method_missing(m, *args, &_block) + if self.class.send(:id_attrs).include?(method.to_s) + super + else + self.class.send(:convert_value, m, args, self) + end + end + + def respond_to_missing?(method, *) + !self.class.send(:id_attrs).include?(method.to_s) + end + # Constructs and returns a new JSON wrapper class. Pass in a plain # JSON string and it will automatically give you accessor methods # that make it behave like a typical Ruby object. You may also pass diff --git a/spec/base_model_spec.rb b/spec/base_model_spec.rb index b55849e..6179883 100644 --- a/spec/base_model_spec.rb +++ b/spec/base_model_spec.rb @@ -34,8 +34,9 @@ hash_with_relations = hash.merge("host" => 1, "related" => {"host" => "http://example.com/hosts/1"}) instance = described_class.new(api, hash_with_relations) - expect(instance).to_not respond_to(:host) + expect(instance).to_not respond_to(:host) expect(instance.host_id).to eq(1) + expect(instance).to respond_to(:anything) end end