Skip to content

Commit

Permalink
Merge pull request #12007 from bdunne/class_from_request_data
Browse files Browse the repository at this point in the history
Add .class_from_request_data for inverse lookup of model from request_type
  • Loading branch information
abellotti authored Oct 19, 2016
2 parents 32a6bff + 010572a commit 440e856
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
10 changes: 10 additions & 0 deletions app/models/miq_request.rb
Original file line number Diff line number Diff line change
Expand Up @@ -76,11 +76,21 @@ class MiqRequest < ApplicationRecord

REQUEST_TYPES_BACKEND_ONLY = {:MiqProvisionRequestTemplate => {:template => "VM Provision Template"}}
REQUEST_TYPES = MODEL_REQUEST_TYPES.values.each_with_object(REQUEST_TYPES_BACKEND_ONLY) { |i, h| i.each { |k, v| h[k] = v } }
REQUEST_TYPE_TO_MODEL = MODEL_REQUEST_TYPES.values.each_with_object({}) do |i, h|
i.each { |k, v| v.keys.each { |vk| h[vk] = k } }
end


delegate :deny, :reason, :stamped_on, :to => :first_approval
delegate :userid, :to => :requester, :prefix => true
delegate :request_task_class, :request_types, :task_description, :to => :class

def self.class_from_request_data(data)
request_type = data[:request_type].try(:to_sym)
model_symbol = REQUEST_TYPE_TO_MODEL[request_type] || raise(ArgumentError, "Invalid request_type")
model_symbol.to_s.constantize
end

# Supports old-style requests where specific request was a seperate table connected as a resource
def resource
self
Expand Down
14 changes: 14 additions & 0 deletions spec/models/miq_request_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -359,4 +359,18 @@
expect(request.request_state).to eq('active')
end
end

context ".class_from_request_data" do
it "with a valid request_type" do
expect(described_class.class_from_request_data(:request_type => "template")).to eq(MiqProvisionRequest)
end

it "with a invalid request_type" do
expect { described_class.class_from_request_data(:request_type => "abc") }.to raise_error("Invalid request_type")
end

it "without a request_type" do
expect { described_class.class_from_request_data({}) }.to raise_error("Invalid request_type")
end
end
end

0 comments on commit 440e856

Please sign in to comment.