Class: Targeting

Inherits:
ApplicationRecord
  • Object
show all
Defined in:
app/models/targeting.rb

Constant Summary collapse

STATIC_TYPE =
'static_query'.freeze
DYNAMIC_TYPE =
'dynamic_query'.freeze
TYPES =
{ STATIC_TYPE => N_('Static Query'), DYNAMIC_TYPE => N_('Dynamic Query') }.freeze
RESOLVE_PERMISSION =
:view_hosts
ORDERED =
'ordered_execution'.freeze
RANDOMIZED =
'randomized_execution'.freeze
ORDERINGS =
{ ORDERED => N_('Alphabetical'), RANDOMIZED => N_('Randomized') }.freeze

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.build_query_from_hosts(ids) ⇒ Object



66
67
68
69
70
71
# File 'app/models/targeting.rb', line 66

def self.build_query_from_hosts(ids)
  return '' if ids.empty?

  hosts = Host.execution_scope.where(:id => ids).distinct.pluck(:name)
  hosts.any? ? "name ^ (#{hosts.join(', ')})" : ''
end

Instance Method Details

#assign_host_ids(host_ids) ⇒ Object



53
54
55
56
# File 'app/models/targeting.rb', line 53

def assign_host_ids(host_ids)
  # this can be optimized even more, by introducing bulk insert
  self.targeting_hosts.build(host_ids.map { |id| { :host_id => id } })
end

#cloneObject



25
26
27
28
29
30
31
32
33
34
35
36
# File 'app/models/targeting.rb', line 25

def clone
  if static?
    self.dup
  else
    Targeting.new(
      :user => self.user,
      :bookmark_id => self.bookmark.try(:id),
      :targeting_type => self.targeting_type,
      :search_query => self.search_query
    )
  end.tap(&:save)
end

#dynamic?Boolean

Returns:

  • (Boolean)


58
59
60
# File 'app/models/targeting.rb', line 58

def dynamic?
  targeting_type == DYNAMIC_TYPE
end

#mark_resolved!Object



77
78
79
# File 'app/models/targeting.rb', line 77

def mark_resolved!
  self.resolved_at = Time.zone.now
end

#resolve_hosts!Object

Raises:

  • (::Foreman::Exception)


38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'app/models/targeting.rb', line 38

def resolve_hosts!
  raise ::Foreman::Exception, _('Cannot resolve hosts without a user') if user.nil?
  raise ::Foreman::Exception, _('Cannot resolve hosts without a bookmark or search query') if bookmark.nil? && search_query.blank?

  self.search_query = bookmark.query if dynamic? && bookmark.present?
  mark_resolved!
  self.validate!
  # avoid validation of hosts objects - they will be loaded for no reason.
  #   pluck(:id) returns duplicate results for HostCollections
  host_ids = User.as(user.) { Host.execution_scope.authorized(RESOLVE_PERMISSION, Host).search_for(search_query).order(:name, :id).pluck(:id).uniq }
  host_ids.shuffle!(random: Random.new) if randomized_ordering
  self.assign_host_ids(host_ids)
  self.save(:validate => false)
end

#resolved?Boolean

Returns:

  • (Boolean)


73
74
75
# File 'app/models/targeting.rb', line 73

def resolved?
  self.resolved_at.present?
end

#static?Boolean

Returns:

  • (Boolean)


62
63
64
# File 'app/models/targeting.rb', line 62

def static?
  targeting_type == STATIC_TYPE
end