Sha256: 5d2fc25aae90f160ae3c0fe9a645464784d61e1b539f2d6200552fd77b51f77a

Contents?: true

Size: 1.06 KB

Versions: 1

Compression:

Stored size: 1.06 KB

Contents

module Dogo
  class Url
    attr_reader :url, :id

    # Check if the given URL is valid, according the the
    # +URI+ regular expression.
    def self.valid?(url)
      URI::DEFAULT_PARSER.regexp[:ABS_URI] =~ url.to_s
    end

    #
    #
    def self.find(id)
      key = Dogo.redis.keys("urls:*:#{id}").first
      return unless key

      new Dogo.redis.get(key)
    end

    def initialize(url)
      @url = url
      load_or_create
    end

    # Increment the click counter for this URL.
    def click!
      Dogo.redis.incr(click_key)
    end

    # Return the clicks for the current URL.
    def clicks
      Dogo.redis.get(click_key).to_i
    end

    private
    def click_key
      "clicks:#{id}"
    end

    def next_id
      Dogo.redis.incr("urls._id")
    end

    def load_or_create
      key = Dogo.redis.keys("urls:#{hash}:*").first

      if key
        @id = key.split(":").last
      else
        @id = next_id.to_s(36)
        Dogo.redis.set("urls:#{hash}:#{id}", url)
      end
    end

    def hash
      @hash ||= Digest::MD5.hexdigest(url)
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
dogo-0.0.1 lib/dogo/url.rb