Class: HitCounter

Inherits:
Object
  • Object
show all
Includes:
Mongoid::Document, Mongoid::Timestamps
Defined in:
lib/version.rb,
lib/hit_counter.rb

Overview

Ruby version of that old 90s chestnut, <BLINK>the web-site hit counter</BLINK>

Examples:

hc = HitCounter.get 'cnn.com'
hc.increment

Defined Under Namespace

Classes: UrlValidator

Constant Summary collapse

VERSION =
'0.1.4'
STYLES =
%w[odometer scout celtic].freeze

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.get(url, hits = 0) ⇒ HitCounter

Returns a HitCounter matching the specified URL. The HitCounter is created if no matching one is found. In the latter case, the hits argument specifies the starting count.

Examples:

hc = HitCounter.get 'cnn.com'
hc = HitCounter.get 'cnn.com', 100

Parameters:

  • url (String)

    the URL for the site being counted

  • hits (Integer) (defaults to: 0)

    the number of hits to start with

Returns:



52
53
54
55
56
# File 'lib/hit_counter.rb', line 52

def self.get(url, hits = 0)
  args = { url: normalize_url(url) }
  args[:hits] = hits unless where(conditions: args).exists?
  find_or_create_by args
end

Instance Method Details

#hits=(value) ⇒ Integer

Sets the number of hits.

Examples:

hc.hits = 100

Parameters:

  • value (Integer)

    the initial number of hits

Returns:

  • (Integer)

    the number of hits



66
67
68
# File 'lib/hit_counter.rb', line 66

def hits=(value)
  self[:hits] = value.to_i
end

#image(style_number) ⇒ Magick::Image

Returns the hit count as a PNG image, using the specified style:

1 odometer
2 scout
3 Celtic

Examples:

hc.image = 1

Parameters:

  • style_number (String)

    the image style

Returns:

  • (Magick::Image)

    the current hit count as a PNG image



91
92
93
94
95
# File 'lib/hit_counter.rb', line 91

def image(style_number)
  image = HitCounter.send(:cat_image, hits.to_s, HitCounter.send(:normalize_style_number, style_number))
  image.format = 'png'
  image
end

#incrementtrue

Increments the hit count and saves the HitCounter.

Examples:

hc.increment

Returns:

  • (true)

    if the save was successful



102
103
104
105
# File 'lib/hit_counter.rb', line 102

def increment
  self.hits += 1
  save
end

#url=(value) ⇒ String

Sets the URL to be tracked. The http prefix is optional.

Examples:

hc.url = 'cnn.com'

Parameters:

  • value (String)

    the URL for the site being counted

Returns:

  • (String)

    the normalized URL



76
77
78
# File 'lib/hit_counter.rb', line 76

def url=(value)
  self[:url] = HitCounter.send(:normalize_url, value)
end