Created Uproar module, moved script stuff to __FILE__ block, no matter how frowned...
[uproar.git] / Uproar.rb
blobda40d53ede6c3695abc3e3a3550b037ff49f59f6
1 #!/usr/bin/env ruby
2 # uproar.rb - search a YAML-encoded list of links for matching tags
3 # version 0.2
4 # see http://ardekantur.com/misc/uproar for information.
6 %w[ rubygems yaml open-uri hpricot ].each { |x| require x }
8 def set_option hash, name, default
9   i = ARGV.index(name)
10   hash[name] = i ? ARGV[i + 1] : default
11 end
13 module Uproar
15   def Uproar.search_tags file, tag
16     links = File.open( file )
17     db = []
18     YAML::load_documents( links ) { |doc| db << doc }
19     db.each { |l| printf "%s\n %s\n", l['title'], l['link'] if l['tags'].include? tag }
20   end
21   
22   def Uproar.add_link file, address, tags
23     begin
24       doc = Hpricot(open(address))
25       title = doc.at("title").inner_html.strip
26       puts "Adding '#{title}' to #{file}..."
27     rescue
28       $stderr.puts "site could not be reached."
29       exit
30     end
31   
32     link = { "title" => title, "link" => address, "tags" => ( tags ? tags.strip.gsub(/ /, ', ') : '' ) }
33   
34     links = File.new( file, "a" )
35     links.puts link.to_yaml
36     links.close
37   end
38 end
40 if __FILE__ == $0
42   o = {}
43   set_option o, '-s', nil
44   set_option o, '-f', 'Links.yaml'
45   set_option o, '-t', ''
46   set_option o, '-a', nil
47   
48   if (!o['-s'] and !o['-a']) or (o['-s'] and o['-a'])
49     $stderr.puts "please specify either a tag to search for or a link to add."
50     exit
51   end
52   
53   Uproar.search_tags o['-f'], o['-s'] if o['-s']
54   Uproar.add_link o['-f'], o['-a'], o['-t'] if o['-a']
56 end