Permalink
Browse files

perfection

  • Loading branch information...
0 parents commit 9b79f4f2c227a0b57d1acaae8098e19c9ae23371 @technoweenie committed May 10, 2011
Showing with 376 additions and 0 deletions.
  1. +27 −0 README.md
  2. +135 −0 Rakefile
  3. +72 −0 active_set.gemspec
  4. +97 −0 lib/active_set.rb
  5. +45 −0 test/active_test.rb
@@ -0,0 +1,27 @@
+# Active Set
+
+This tracks the number of active objects during a certain time period in
+a Redis sorted set. Object activity is defined by your application, and
+is out of the scope of this library.
+
+When an object is active, it gets added to a Redis set with a timestamp.
+
+ set = ActiveSet.new(:objects)
+ set.add(1, Time.now) # Time.now is default if no time is given.
+
+This is equivalent to the following Redis command:
+
+ ZADD active:objects 1305054408 "1"
+
+We can count the number of items in the set:
+
+ set.count # => 1
+ # ZCARD active:objects
+
+The set should be trimmed periodically so that old objects aren't
+counted.
+
+ set.trim(1302462660)
+ # ZREMRANGEBYSCORE active:objects -inf (1302462660
+
+If no trim date is given, 30 days is assumed.
135 Rakefile
@@ -0,0 +1,135 @@
+require 'rubygems'
+require 'rake'
+require 'date'
+
+#############################################################################
+#
+# Helper functions
+#
+#############################################################################
+
+def name
+ @name ||= Dir['*.gemspec'].first.split('.').first
+end
+
+def version
+ line = File.read("lib/#{name}.rb")[/^\s*VERSION\s*=\s*.*/]
+ line.match(/.*VERSION\s*=\s*['"](.*)['"]/)[1]
+end
+
+def date
+ Date.today.to_s
+end
+
+def rubyforge_project
+ name
+end
+
+def gemspec_file
+ "#{name}.gemspec"
+end
+
+def gem_file
+ "#{name}-#{version}.gem"
+end
+
+def replace_header(head, header_name)
+ head.sub!(/(\.#{header_name}\s*= ').*'/) { "#{$1}#{send(header_name)}'"}
+end
+
+#############################################################################
+#
+# Standard tasks
+#
+#############################################################################
+
+task :default => :test
+
+require 'rake/testtask'
+Rake::TestTask.new(:test) do |test|
+ test.libs << 'lib' << 'test'
+ test.pattern = 'test/**/*_test.rb'
+ test.verbose = true
+end
+
+desc "Open an irb session preloaded with this library"
+task :console do
+ sh "irb -rubygems -r ./lib/#{name}.rb"
+end
+
+#############################################################################
+#
+# Custom tasks (add your own tasks here)
+#
+#############################################################################
+
+
+
+#############################################################################
+#
+# Packaging tasks
+#
+#############################################################################
+
+desc "Create tag v#{version} and build and push #{gem_file} to Rubygems"
+task :release => :build do
+ unless `git branch` =~ /^\* master$/
+ puts "You must be on the master branch to release!"
+ exit!
+ end
+ sh "git commit --allow-empty -a -m 'Release #{version}'"
+ sh "git tag v#{version}"
+ sh "git push origin master"
+ sh "git push origin v#{version}"
+ sh "gem push pkg/#{name}-#{version}.gem"
+end
+
+desc "Build #{gem_file} into the pkg directory"
+task :build => :gemspec do
+ sh "mkdir -p pkg"
+ sh "gem build #{gemspec_file}"
+ sh "mv #{gem_file} pkg"
+end
+
+desc "Generate #{gemspec_file}"
+task :gemspec => :validate do
+ # read spec file and split out manifest section
+ spec = File.read(gemspec_file)
+ head, manifest, tail = spec.split(" # = MANIFEST =\n")
+
+ # replace name version and date
+ replace_header(head, :name)
+ replace_header(head, :version)
+ replace_header(head, :date)
+ #comment this out if your rubyforge_project has a different name
+ replace_header(head, :rubyforge_project)
+
+ # determine file list from git ls-files
+ files = `git ls-files`.
+ split("\n").
+ sort.
+ reject { |file| file =~ /^\./ }.
+ reject { |file| file =~ /^(rdoc|pkg)/ }.
+ map { |file| " #{file}" }.
+ join("\n")
+
+ # piece file back together and write
+ manifest = " s.files = %w[\n#{files}\n ]\n"
+ spec = [head, manifest, tail].join(" # = MANIFEST =\n")
+ File.open(gemspec_file, 'w') { |io| io.write(spec) }
+ puts "Updated #{gemspec_file}"
+end
+
+desc "Validate #{gemspec_file}"
+task :validate do
+ libfiles = Dir['lib/*'] - ["lib/#{name}.rb", "lib/#{name}"]
+ unless libfiles.empty?
+ puts "Directory `lib` should only contain a `#{name}.rb` file and `#{name}` dir."
+ exit!
+ end
+ unless Dir['VERSION*'].empty?
+ puts "A `VERSION` file at root level violates Gem best practices."
+ exit!
+ end
+end
+
@@ -0,0 +1,72 @@
+## This is the rakegem gemspec template. Make sure you read and understand
+## all of the comments. Some sections require modification, and others can
+## be deleted if you don't need them. Once you understand the contents of
+## this file, feel free to delete any comments that begin with two hash marks.
+## You can find comprehensive Gem::Specification documentation, at
+## http://docs.rubygems.org/read/chapter/20
+Gem::Specification.new do |s|
+ s.specification_version = 2 if s.respond_to? :specification_version=
+ s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
+ s.rubygems_version = '1.3.5'
+
+ ## Leave these as is they will be modified for you by the rake gemspec task.
+ ## If your rubyforge_project name is different, then edit it and comment out
+ ## the sub! line in the Rakefile
+ s.name = 'active_set'
+ s.version = '0.1.0'
+ s.date = '2011-05-10'
+ s.rubyforge_project = 'active_set'
+
+ ## Make sure your summary is short. The description may be as long
+ ## as you like.
+ s.summary = "Tracks the number of active objects during a certain time period in a Redis sorted set."
+ s.description = s.summary
+
+ ## List the primary authors. If there are a bunch of authors, it's probably
+ ## better to set the email to an email list or something. If you don't have
+ ## a custom homepage, consider using your GitHub URL or the like.
+ s.authors = ["Rick Olson"]
+ s.email = 'technoweenie@example.com'
+ s.homepage = 'http://github.com/technoweenie/active_set'
+
+ ## This gets added to the $LOAD_PATH so that 'lib/NAME.rb' can be required as
+ ## require 'NAME.rb' or'/lib/NAME/file.rb' can be as require 'NAME/file.rb'
+ s.require_paths = %w[lib]
+
+ ## This sections is only necessary if you have C extensions.
+ #s.require_paths << 'ext'
+ #s.extensions = %w[ext/extconf.rb]
+
+ ## If your gem includes any executables, list them here.
+ #s.executables = ["name"]
+ #s.default_executable = 'name'
+
+ ## Specify any RDoc options here. You'll want to add your README and
+ ## LICENSE files to the extra_rdoc_files list.
+ s.rdoc_options = ["--charset=UTF-8"]
+ s.extra_rdoc_files = %w[README.md LICENSE]
+
+ ## List your runtime dependencies here. Runtime dependencies are those
+ ## that are needed for an end user to actually USE your code.
+ s.add_dependency('redis', ["< 3.0", ">= 2.0"])
+
+ ## List your development dependencies here. Development dependencies are
+ ## those that are only needed during development
+ #s.add_development_dependency('DEVDEPNAME', [">= 1.1.0", "< 2.0.0"])
+
+ ## Leave this section as-is. It will be automatically generated from the
+ ## contents of your Git repository via the gemspec task. DO NOT REMOVE
+ ## THE MANIFEST COMMENTS, they are used as delimiters by the task.
+ # = MANIFEST =
+ s.files = %w[
+ README.md
+ lib/active_set.rb
+ test/active_test.rb
+ ]
+ # = MANIFEST =
+
+ ## Test files will be grabbed from the file list. Make sure the path glob
+ ## matches what you actually use.
+ s.test_files = s.files.select { |path| path =~ /^test\/test_.*\.rb/ }
+end
+
@@ -0,0 +1,97 @@
+require 'redis'
+
+class ActiveSet
+ VERSION = "0.1.0"
+ SECONDS_PER_DAY = 86400
+
+ attr_reader :key
+
+ # Initializes a new Set of active objects.
+ #
+ # name - String name to identify this ActiveSet.
+ # options - Hash of options.
+ # :prefix - String prefix used to namespace the Redis key.
+ # :days - Default Fixnum of days of items to allow in the
+ # set. Default to 30.
+ # :sec - Fixnum of seconds of items to allow in the set.
+ # Defaults to using MATH to calculate seconds in
+ # 30 days.
+ # :redis - An existing Redis connection. If not set, the
+ # rest of this options Hash is used to initialize
+ # a new Redis connection.
+ def initialize(name, options = {})
+ @name = name
+ @prefix = options.delete(:prefix) || :active
+ @days = options.delete(:days) || 30
+ @sec = options.delete(:sec) || (SECONDS_PER_DAY * @days)
+ @redis = options.delete(:redis)
+ @key = "#{@prefix}:#{@name}"
+ @redis ||= Redis.new(options)
+ end
+
+ # Public: Adds a new object to the Set.
+ #
+ # entry - The String identifier of the object.
+ # time - Optional Time specifying when the object was last active.
+ #
+ # Returns nothing.
+ def add(entry, time = Time.now)
+ @redis.zadd(@key, time.to_i, entry)
+ end
+
+ # Public: Checks to see if the object is in the Set.
+ #
+ # entry - The String identifier of the object.
+ #
+ # Returns true if the object is in the set, or false.
+ def include?(entry)
+ !@redis.zscore(@key, entry).nil?
+ end
+
+ # Public: Gets the timestamp for when the given object was active.
+ #
+ # entry - The String identifier of the object.
+ #
+ # Returns the Time the object was last active, or nil.
+ def timestamp_for(entry)
+ sec = @redis.zscore(@key, entry)
+ sec ? Time.at(sec.to_i) : nil
+ end
+
+ # Public: Counts the number of objects in the set.
+ #
+ # since - An optional Time to specify the cutoff time to
+ # count. If provided, any object updated since the timestamp
+ # is counted.
+ #
+ # Returns a Fixnum.
+ def count(since = nil)
+ (since ?
+ @redis.zcount(@key, since.to_i, "+inf") :
+ @redis.zcard(@key)).to_i
+ end
+
+ # Public: Trims the Set.
+ #
+ # time - Optional Time specifying the earliest cutoff point. Any
+ # object with a later timestamp is purged.
+ #
+ # Returns nothing.
+ def trim(time = earliest_time)
+ @redis.zremrangebyscore(@key, "-inf", "(#{time.to_i}")
+ end
+
+ # Public: Clears the Set.
+ #
+ # Returns nothing.
+ def clear
+ @redis.del(@key)
+ end
+
+ # Calculates the earliest time used as a cutoff point for #trim.
+ #
+ # Returns Fixnum seconds.
+ def earliest_time
+ Time.now.to_i - @sec
+ end
+end
@@ -0,0 +1,45 @@
+require 'rubygems'
+require 'test/unit'
+require File.expand_path("../../lib/active_set", __FILE__)
+
+class ActiveSetTest < Test::Unit::TestCase
+ def setup
+ @set = ActiveSet.new :lols, :prefix => 'active_test'
+ @set.clear
+ @key = @set.key
+ end
+
+ def test_adds_item
+ assert_equal 0, @set.count
+ assert !@set.include?('abc')
+ @set.add 'abc'
+ assert_equal 1, @set.count
+ assert @set.include?('abc')
+ end
+
+ def test_adds_item_with_custom_time
+ time = Time.local(2001)
+ @set.add 'abc', time
+ assert_equal time, @set.timestamp_for('abc')
+ end
+
+ def test_counts_items
+ assert_equal 0, @set.count
+ @set.add 'abc'
+ assert_equal 1, @set.count
+ @set.add 'def', Time.local(2001)
+ assert_equal 2, @set.count
+ @set.add 'abc'
+ assert_equal 2, @set.count
+ assert_equal 1, @set.count(Time.local(2002))
+ end
+
+ def test_trims_set
+ @set.add 'abc'
+ @set.add 'def', Time.local(2001)
+ assert_equal 2, @set.count
+ @set.trim
+ assert_equal 1, @set.count
+ assert @set.include?('abc')
+ end
+end

0 comments on commit 9b79f4f

Please sign in to comment.