Skip to content

Instantly share code, notes, and snippets.

@raws
Created September 26, 2010 06:11
Show Gist options
  • Save raws/597648 to your computer and use it in GitHub Desktop.
Save raws/597648 to your computer and use it in GitHub Desktop.
Over-engineered bit of Ruby to try out some code techniques and help me work on projects
#!/usr/bin/env ruby
require "pathname"
require "rubygems"
require "active_support/inflector"
require "spotlight"
class Symbol
Operators = {
:not => "!=", :gt => ">", :lt => "<", :gte => ">=", :lte => "<="
}
def method_missing(name, *args)
if Operators.include?(name)
@condition = Operators[name]
return self
end
end
def operator
@condition || "=="
end
def to_condition
"kMD#{to_s.classify} #{operator}"
end
end
class String
def spotlight_escape
self.gsub(/(["'‘`])/, '\\\1')
end
end
module Workon
class << self
attr_accessor :projects
def project?(dir)
dir = Pathname.new(dir)
[dir.parent, dir.parent.parent].include?(Workon.projects)
end
def commands
methods.map { |method| method[/^(.*)_command$/, 1] }.compact.sort
end
def run(command, args)
send :"#{command}_command", args
end
def help_command(args)
puts "usage: workon <#{commands.join(" | ")}>"
end
def search_command(args)
project = args.first
query = Query.new :item_display_name => project, :item_kind => "Folder"
require "pp"
pp query.execute
end
end
class Query < ::Spotlight::Query
def initialize(conditions={})
query_string = conditions.map do |key, val|
%{#{key.to_condition} "#{val.to_s.spotlight_escape}"c}
end.join(" && ")
super(query_string)
scopes << Workon.projects.realpath
end
alias :original_execute :execute
def execute
original_execute.tap do |results|
results.reject! { |result| !Workon.project?(result.get(:kMDItemPath)) }
end
end
end
end
if ENV["WORKON_PROJECTS"]
Workon.projects = Pathname.new(ENV["WORKON_PROJECTS"])
else
$stderr.puts "Error: please set WORKON_PROJECTS."
exit 1
end
command = ARGV[0]
if command && Workon.commands.include?(command)
Workon.run command, ARGV[1..-1]
elsif command
Workon.run :search, ARGV.dup
else
Workon.run :help, ARGV[1..-1]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment