Class: Ad

Inherits:
ActiveRecord::Base
  • Object
show all
Defined in:
app/models/ad.rb

Constant Summary collapse

FREQUENCIES =
1..10
AUDIENCES =
%w(all logged_in logged_out)

Class Method Summary collapse

Class Method Details

.audiences_for(logged_in) ⇒ Object



22
23
24
# File 'app/models/ad.rb', line 22

def self.audiences_for(logged_in)
  ["all", "logged_#{logged_in ? 'in' : 'out'}"]
end

.audiences_for_selectObject



30
31
32
# File 'app/models/ad.rb', line 30

def self.audiences_for_select
  AUDIENCES.map{|a| [a, a.to_s]}
end

.display(location, logged_in = false) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
# File 'app/models/ad.rb', line 10

def self.display(location, logged_in = false)
  return nil if location.blank?
  ads = where("location = ?
      AND published = ?
      AND (time_constrained = ? OR (start_date > ? AND end_date < ?))
      AND (audience IN (?) )",
      location.to_s, true, false, Time.now, Time.now, audiences_for(logged_in))

  ad = random_weighted(ads.map{|a| [a, a.frequency] })
  ad ? ad.html.html_safe : ''
end

.frequencies_for_selectObject



26
27
28
# File 'app/models/ad.rb', line 26

def self.frequencies_for_select
  FREQUENCIES.map{|f| [f, f.to_s]}
end

.random_weighted(items) ⇒ Object



34
35
36
37
38
39
40
41
# File 'app/models/ad.rb', line 34

def self.random_weighted(items)
  total = 0
  pick = nil
  items.each do |item, weight|
    pick = item if rand(total += weight) < weight
  end
  pick
end