Skip to content

Commit

Permalink
New and improved Field.is_field?()
Browse files Browse the repository at this point in the history
Fixes issue when MiqExpression engine is a regular expression
and the field looks like "Model-field" but the attribute doesn't exist

Example: if there is vm named "Lan-yuri" than this expression
Virtual Machine : Name REGULAR EXPRESSION MATCHES "L+" triggers error

https://bugzilla.redhat.com/show_bug.cgi?id=1581853
  • Loading branch information
kbrock committed Aug 4, 2018
1 parent ce1baa2 commit 4dc6d18
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 14 deletions.
15 changes: 3 additions & 12 deletions lib/miq_expression/field.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,25 +18,16 @@ def self.parse(field)
end

def self.is_field?(field)
return false unless field.kind_of?(String)
match = REGEX.match(field)
return false unless match
model =
begin
match[:model_name].safe_constantize
rescue LoadError
nil
end
return false unless model
!!(model < ApplicationRecord)
parse(field)&.valid? || false
end

def to_s
"#{[model, *associations].join(".")}-#{column}"
end

def valid?
target.column_names.include?(column) || virtual_attribute? || custom_attribute_column?
(target < ApplicationRecord) &&
(target.column_names.include?(column) || virtual_attribute? || custom_attribute_column?)
end

def attribute_supported_by_sql?
Expand Down
7 changes: 6 additions & 1 deletion lib/miq_expression/target.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,16 @@ def self.parse!(field)
# returns hash:
# {:model_name => Host<ApplicationRecord> , :associations => ['vms']<Array>, :column_name => 'host_name' <String>}
def self.parse_params(field)
return unless field.kind_of?(String)
match = self::REGEX.match(field) || return
# convert matches to hash to format
# {:model_name => 'User', :associations => ...}
parsed_params = Hash[match.names.map(&:to_sym).zip(match.to_a[1..-1])]
parsed_params[:model_name] = parsed_params[:model_name].classify.safe_constantize
begin
parsed_params[:model_name] = parsed_params[:model_name].classify.safe_constantize
rescue LoadError # issues for case sensitivity (e.g.: VM vs vm)
parsed_params[:model_name] = nil
end
parsed_params[:associations] = parsed_params[:associations].to_s.split(".")
parsed_params
end
Expand Down
6 changes: 5 additions & 1 deletion spec/lib/miq_expression/field_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -351,7 +351,11 @@

it "does not detect a string to looks like a field but isn't" do
expect(MiqExpression::Field.is_field?("NetworkManager-team")).to be_falsey
expect(described_class.is_field?("ManageIQ-name")).to be(false)
expect(described_class.is_field?("ManageIQ-name")).to be_falsey
end

it "handles regular expression" do
expect(MiqExpression::Field.is_field?(/x/)).to be_falsey
end
end
end

0 comments on commit 4dc6d18

Please sign in to comment.