Skip to content

Commit

Permalink
Add resource unwrapping for singular resource
Browse files Browse the repository at this point in the history
  • Loading branch information
slevenick committed Oct 16, 2018
1 parent ec00543 commit cee98a6
Showing 1 changed file with 57 additions and 7 deletions.
64 changes: 57 additions & 7 deletions templates/inspec/singular_resource.erb
Original file line number Diff line number Diff line change
Expand Up @@ -64,21 +64,29 @@ url = "'#{url}'"

<% if object.self_link_query.nil? -%>
def initialize(params)
@fetched = <%= method_call('fetch_resource', ['params', ("'#{object.kind}'" if object.kind?)], 2) %>
@fetched = fetch_resource(params)
parse unless @fetched.nil?
end
<% else # object.self_link_query.nil? -%>
def initialize(params)
@fetched = <%= method_call('fetch_wrapped_resource', ['params', ("'#{object.kind}'" if object.kind?),
"'#{object.self_link_query.kind}'",
"'#{object.self_link_query.items}'"], 2) %>
@fetched = <%= method_call('fetch_wrapped_resource',
[
'params',
"'#{object.kind}'",
"'#{object.self_link_query.kind}'",
"'#{object.self_link_query.items}'"
], 2) %>
parse unless @fetched.nil?
end
<% end # object.self_link_query.nil? -%>

def fetch_resource(params)
get_request = inspec.backend.fetch(base, url, params)
end

def parse
<%
fetch_code = object.properties.reject(&:input).map do |prop|
<%
parse_code = object.properties.reject(&:input).map do |prop|
name = prop.out_name

if primitive?(prop) || resource_ref?(prop)
Expand All @@ -92,10 +100,52 @@ url = "'#{url}'"
assignment = "@#{name} = #{init}"
end
-%>
<%= lines(indent(fetch_code, 4)) -%>
<%= lines(indent(parse_code, 4)) -%>
end

def exists?
[email protected]?
end

<% unless object.self_link_query.nil? -%>
def fetch_wrapped_resource(params, kind, wrap_kind, wrap_path)
result = fetch_resource(params, wrap_kind)
return if result.nil? || !result.key?(wrap_path)
result = unwrap_resource(result[wrap_path], params)
return if result.nil?
raise "Incorrect result: #{result['kind']} (expected #{kind})" \
unless result['kind'] == kind
result
end


def unwrap_resource(result, resource)
query_predicate = unwrap_resource_filter(resource)
matches = result.select do |entry|
query_predicate.all? do |k, v|
entry[k.id2name] == v
end
end
raise "More than 1 result found: #{matches}" if matches.size > 1
return if matches.empty?
matches.first
end

<%
urf_code = [
'{',
indent_list(
Hash[object.identity.map { |i| [i, "resource[:#{property_out_name(i)}]"] }]
.map { |k, v| "#{k.out_name}: #{v}" }, 2
),
'}'
]
-%>
def unwrap_resource_filter(resource)
self.class.unwrap_resource_filter(resource)
end

<%= lines(indent(emit_method('self.unwrap_resource_filter', %w[resource],
urf_code, file_relative), 2), 1) -%>
<% end # object.self_link_query.nil? -%>
end

0 comments on commit cee98a6

Please sign in to comment.