Skip to content
This repository has been archived by the owner on May 23, 2024. It is now read-only.

method_missing for missing attr #96

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 13 additions & 5 deletions lib/ansible_tower_client/base_model.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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?(m.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
Expand Down Expand Up @@ -83,11 +95,7 @@ def update_attributes!(attributes)
@api.patch(url, attributes.to_json)
attributes.each do |method_name, value|
invoke_name = "#{override_raw_attributes[method_name] || method_name}="
if respond_to?(invoke_name)
send(invoke_name, value)
else
AnsibleTowerClient.logger.warn("Unknown attribute/method: #{invoke_name}. Skip updating it ...")
end
send(invoke_name, value)
end
true
end
Expand Down
3 changes: 2 additions & 1 deletion spec/base_model_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
6 changes: 0 additions & 6 deletions spec/support/shared_examples/crud_methods.rb
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,6 @@
expect(obj.name).to eq 'blah'
end

it "ignore unknown attributes if patch succeeds" do
expect(instance_api).to receive(:patch).and_return(instance_double("Faraday::Result", :body => raw_instance.to_json))
expect(obj.update_attributes!(:name => 'blah', :stranger_thing => 'bomb')).to eq true
expect(obj.name).to eq 'blah'
end

it "returns an error if an error is raised" do
expect(instance_api).to receive(:patch).and_raise(AnsibleTowerClient::Error, 'error')
expect { obj.update_attributes!(:name => 'bad name') }.to raise_error(AnsibleTowerClient::Error)
Expand Down