yyyc514-lookup 0.2.0

Sign up to get free protection for your applications and to get access to all the features.
data/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ Copyright (c) 2009 Ryan Bigg
2
+
3
+ Contributions by: Josh Goebel / Dreamer3
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining
6
+ a copy of this software and associated documentation files (the
7
+ "Software"), to deal in the Software without restriction, including
8
+ without limitation the rights to use, copy, modify, merge, publish,
9
+ distribute, sublicense, and/or sell copies of the Software, and to
10
+ permit persons to whom the Software is furnished to do so, subject to
11
+ the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be
14
+ included in all copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,26 @@
1
+ # Lazy Man's ri (lookup)
2
+
3
+ ## Example usage:
4
+
5
+ * `lookup ActiveRecord::Base#new` (returns a single method, since the method name is right)
6
+ * `lookup ActiveRecord::Base#destroy` (returns two methods, since there's two methods with that name)
7
+ * `lookup ActiveRecord::Base#destro` (returns three methods, uses methods beginning with "destroy")
8
+ * `lookup ActiveRecord::Base#d` (tells you to be more specific, because it can't open 35 tabs at once)
9
+ * `lookup ActiveRecord::Base` (returns a single consant)
10
+ * `lookup Acv::Base` (returns six constants, because it does a fuzzy match)
11
+
12
+ ## Options
13
+
14
+ It also takes options:
15
+
16
+ * `-c or --clear` will delete the database and update the api again. This can take a minute or two.
17
+ * `-t or --text` is useful for when you don't want lookup to spam tabs into your browser willy-nilly.
18
+
19
+ ## How it finds them
20
+
21
+ 1. Checks if there's constants/methods with that exact name.
22
+ 2. Checks if there's constants/methods with names beginning with that name.
23
+ 3. Does a "fuzzy match" splitting the name and getting anything containing those letters in that order.
24
+ 4. Opens your browser if you're running a DECENT_OPERATING_SYSTEM (may add support for things other than Mac later on)
25
+ 5. ???
26
+ 6. Profit
data/Rakefile ADDED
@@ -0,0 +1,63 @@
1
+ require 'rubygems'
2
+ require 'rake/gempackagetask'
3
+ require 'rubygems/specification'
4
+ require 'date'
5
+ require 'spec/rake/spectask'
6
+
7
+ GEM = "lookup"
8
+ GEM_VERSION = "0.1.0"
9
+ AUTHOR = "Ryan Bigg"
10
+ EMAIL = "radarlistener@gmail.com"
11
+ HOMEPAGE = "http://gitpilot.com"
12
+ SUMMARY = "A gem that provides a lazy man's ri"
13
+
14
+ spec = Gem::Specification.new do |s|
15
+ s.name = GEM
16
+ s.version = GEM_VERSION
17
+ s.platform = Gem::Platform::RUBY
18
+ s.has_rdoc = true
19
+ s.extra_rdoc_files = ["README.md", "LICENSE", 'TODO']
20
+ s.summary = SUMMARY
21
+ s.description = s.summary
22
+ s.author = AUTHOR
23
+ s.email = EMAIL
24
+ s.homepage = HOMEPAGE
25
+ s.executables << "lookup"
26
+
27
+ # Uncomment this to add a dependency
28
+ # s.add_dependency "foo"
29
+
30
+ s.require_path = 'lib'
31
+ s.autorequire = GEM
32
+ (Dir.entries("doc") - ['..', '.']).each do |file|
33
+ FileUtils.rm("doc/#{file}")
34
+ end
35
+ Dir.delete("doc")
36
+ Dir.mkdir("doc")
37
+ s.files = %w(LICENSE README.md Rakefile TODO) + Dir.glob("{lib,spec,bin,doc}/**/*")
38
+ end
39
+
40
+ task :default => :spec
41
+
42
+ desc "Run specs"
43
+ Spec::Rake::SpecTask.new do |t|
44
+ t.spec_files = FileList['spec/**/*_spec.rb']
45
+ t.spec_opts = %w(-fs --color)
46
+ end
47
+
48
+
49
+ Rake::GemPackageTask.new(spec) do |pkg|
50
+ pkg.gem_spec = spec
51
+ end
52
+
53
+ desc "install the gem locally"
54
+ task :install => [:package] do
55
+ sh %{sudo gem install pkg/#{GEM}-#{GEM_VERSION}}
56
+ end
57
+
58
+ desc "create a gemspec file"
59
+ task :make_spec do
60
+ File.open("#{GEM}.gemspec", "w") do |file|
61
+ file.puts spec.to_ruby
62
+ end
63
+ end
data/TODO ADDED
@@ -0,0 +1,2 @@
1
+ TODO:
2
+ Test the bloody thing.
data/bin/lookup ADDED
@@ -0,0 +1,79 @@
1
+ #!/usr/bin/ruby
2
+ require 'optparse'
3
+
4
+ # How many methods / constants to return.
5
+ THRESHOLD = 5
6
+ MAC = !!/darwin/.match(PLATFORM)
7
+ WINDOWS = !!/win/.match(PLATFORM) if not MAC
8
+
9
+ def clear_database
10
+ file = File.join(File.dirname(__FILE__), "lookup.sqlite3")
11
+ FileUtils.rm(file) if File.exists?(file)
12
+ end
13
+
14
+ def display_url(result, options={})
15
+ # if we're not on mac or windows we default to text output
16
+ if OPTIONS[:text] or not (MAC || WINDOWS)
17
+ s = options[:number] ? options[:number].to_s + ". " : ""
18
+ # if we're a method then show the constant in parans
19
+ s += "(#{result.constant.name}) " if result.respond_to?(:constant)
20
+ s += "#{result.name} #{result.url}"
21
+ puts s
22
+ elsif MAC
23
+ `open #{result.url}`
24
+ elsif WINDOWS
25
+ `start #{result.url}`
26
+ end
27
+ end
28
+
29
+ def display_results(results, search_string)
30
+ if results.empty?
31
+ puts "There were no results matching #{search_string}."
32
+ # if entry
33
+ # puts "There are no constants that match #{name} and contain #{entry}."
34
+ # else
35
+ # puts "There are no constants that match #{name}"
36
+ # end
37
+ elsif results.size == 1
38
+ display_url(results.first)
39
+ elsif results.size <= THRESHOLD
40
+ results.each_with_index do |result, i|
41
+ display_url(result, :number => i+1)
42
+ end
43
+ else
44
+ puts "Please refine your query, we found #{results.size} results (threshold is #{THRESHOLD})."
45
+ end
46
+ end
47
+
48
+ OPTIONS = {}
49
+ op=OptionParser.new do |opts|
50
+ opts.banner = "Usage: lookup <constant|method> [method] [OPTIONS]"
51
+
52
+ opts.on("-c", "--clear", "Clear database") do
53
+ OPTIONS[:clear] = true
54
+ end
55
+ opts.on("-t", "--text", "Text only") do
56
+ OPTIONS[:text] = true
57
+ end
58
+ end
59
+ op.parse!
60
+
61
+ clear_database if OPTIONS[:clear]
62
+
63
+
64
+ local_lib=File.join(File.dirname(__FILE__), "../lib/lookup")
65
+ if File.exists?(local_lib + ".rb")
66
+ require local_lib
67
+ else
68
+ require 'rubygems'
69
+ require 'lookup'
70
+ end
71
+
72
+ search_string=ARGV[0..-1].join(" ")
73
+ if search_string.strip.empty?
74
+ puts op.help
75
+ puts
76
+ else
77
+ results=APILookup.search(ARGV[0..-1])
78
+ display_results(results, search_string)
79
+ end
data/lib/config.rb ADDED
@@ -0,0 +1,5 @@
1
+ require 'rubygems'
2
+ require 'hpricot'
3
+ require 'net/http'
4
+
5
+ DEBUG = true
data/lib/lookup.rb ADDED
@@ -0,0 +1,139 @@
1
+ require 'rubygems'
2
+ require 'activerecord'
3
+
4
+ class APILookup
5
+
6
+ class << self
7
+ def update
8
+ require 'hpricot'
9
+ require 'net/http'
10
+ puts "Updating API, this may take a minute or two. Please be patient!"
11
+ Constant.delete_all
12
+ Entry.delete_all
13
+ # Ruby on Rails Classes & Methods
14
+ update_api("Rails", "http://api.rubyonrails.org")
15
+ # Ruby Classes & Methods
16
+ update_api("Ruby", "http://www.ruby-doc.org/core")
17
+
18
+ weight_results
19
+ puts "Updated API index! Use the lookup <method> or lookup <class> <method> to find what you're after"
20
+ end
21
+
22
+ def update_api(name, url)
23
+ puts "Updating API for #{name}..."
24
+ Api.find_or_create_by_name_and_url(name, url)
25
+ update_methods(Hpricot(Net::HTTP.get(URI.parse("#{url}/fr_method_index.html"))), url)
26
+ update_classes(Hpricot(Net::HTTP.get(URI.parse("#{url}/fr_class_index.html"))), url)
27
+ puts "DONE (with #{name})!"
28
+ end
29
+
30
+ def update_methods(doc, prefix)
31
+ doc.search("a").each do |a|
32
+ names = a.inner_html.split(" ")
33
+ method = names[0]
34
+ name = names[1].gsub(/[\(|\)]/, "")
35
+ # The same constant can be defined twice in different APIs, be wary!
36
+ url = prefix + "/classes/" + name.gsub("::", "/") + ".html"
37
+ constant = Constant.find_or_create_by_name_and_url(name, url)
38
+ constant.entries.create!(:name => method, :url => prefix + "/" + a["href"])
39
+ end
40
+ end
41
+
42
+ def update_classes(doc, prefix)
43
+ doc.search("a").each do |a|
44
+ constant = Constant.find_or_create_by_name_and_url(a.inner_html, prefix + "/" + a["href"])
45
+ end
46
+ end
47
+
48
+ # Weights the results so the ones more likely to be used by people come up first.
49
+ def weight_results
50
+ e = Constant.find_by_name("ActiveRecord::Associations::ClassMethods").entries.find_by_name("belongs_to")
51
+ e.increment!(:weighting)
52
+ end
53
+
54
+ def find_constant(name, entry=nil)
55
+ # Find by specific name.
56
+ constants = Constant.find_all_by_name(name, :include => "entries")
57
+ # search for class methods, which is prolly what we want if we can find it
58
+ constants = Constant.find_all_by_name("#{name}::ClassMethods", :include => "entries") if constants.empty?
59
+ # Find by name beginning with <blah>.
60
+ constants = Constant.all(:conditions => ["name LIKE ?", name + "%"], :include => "entries") if constants.empty?
61
+ # Find by fuzzy.
62
+ match="%#{name.split("").join("%")}%"
63
+ constants = Constant.find_by_sql("select * from constants where name LIKE '#{match}'") if constants.empty?
64
+ regex=build_regex_from_constant(name)
65
+ constants = constants.select { |x| x.name =~ regex }
66
+ # Narrow it down to the constants that only contain the entry we are looking for.
67
+ if entry
68
+ constants = constants.select { |constant| !constant.entries.find_by_name(entry).nil? }
69
+ end
70
+ constants
71
+ end
72
+
73
+ # this uses a regex to lock down our SQL finds even more
74
+ # so that things like AR::Base will not match
75
+ # ActiveRecord::ConnectionAdapters::DatabaseStatements
76
+ def build_regex_from_constant(name)
77
+ parts=name.split("::").map do |c|
78
+ c.split("").join("[^:]*")+"[^:]*"
79
+ end
80
+ /#{parts.join("::")}/i
81
+ end
82
+
83
+ def smart_rails_constant_substitutions(name)
84
+ parts=name.split("::").map { |x| x.split(":")}.flatten
85
+ rep = case parts.first.downcase
86
+ # so it falls back on fuzzy and matches AR as well as ActiveResource
87
+ when "ar": "ActiveRecord"
88
+ when "ares": "ActiveResource"
89
+ when "am": "ActionMailer"
90
+ when "as": "ActiveSupport"
91
+ when "ac": "ActionController"
92
+ when "av": "ActionView"
93
+ else
94
+ parts.first
95
+ end
96
+ ([rep] + parts[1..-1]).join("::")
97
+ end
98
+
99
+ # Find an entry.
100
+ # If the constant argument is passed, look it up within the scope of the constant.
101
+ def find_method(name, constant=nil)
102
+ methods = []
103
+ methods = Entry.find_all_by_name(name.to_s)
104
+ methods = Entry.all(:conditions => ["name LIKE ?", name.to_s + "%"]) if methods.empty?
105
+ methods = Entry.find_by_sql("select * from entries where name LIKE '%#{name.split("").join("%")}%'") if methods.empty?
106
+
107
+ # Weight the results, last result is the first one we want shown first
108
+ methods = methods.sort_by(&:weighting)
109
+
110
+ if constant
111
+ constants = find_constant(constant, name)
112
+ methods = methods.select { |m| constants.include?(m.constant) }
113
+ end
114
+ methods
115
+ end
116
+
117
+ def search(msg)
118
+ msg = msg.split(" ")[0..-1].flatten.map { |a| a.split("#") }.flatten!
119
+
120
+ # It's a constant! Oh... and there's nothing else in the string!
121
+ first=smart_rails_constant_substitutions(msg.first)
122
+ if /^[A-Z]/.match(first) && msg.size == 1
123
+ find_constant(first)
124
+ # It's a method!
125
+ else
126
+ # Right, so they only specified one argument. Therefore, we look everywhere.
127
+ if msg.size == 1
128
+ find_method(msg)
129
+ # Left, so they specified two arguments. First is probably a constant, so let's find that!
130
+ else
131
+ find_method(msg.last, first)
132
+ end
133
+ end
134
+ end
135
+
136
+ end
137
+ end
138
+
139
+ require File.join(File.dirname(__FILE__), 'models')
data/lib/models.rb ADDED
@@ -0,0 +1,70 @@
1
+ require 'fileutils'
2
+
3
+ class APILookup
4
+
5
+ class MissingHome < StandardError
6
+ end
7
+
8
+ class LookupBase < ActiveRecord::Base
9
+ end
10
+ if ENV["HOME"].nil?
11
+ puts "The HOME environment variable should be set so lookup knows where"
12
+ puts "to store it's lookup database."
13
+ raise MissingHome, "HOME must be set to know where to store our local db."
14
+ end
15
+
16
+ LookupBase.establish_connection(:adapter => "sqlite3",
17
+ :database => File.join(ENV["HOME"],".lookup", "lookup.sqlite3"))
18
+
19
+ class Api < LookupBase
20
+ set_table_name "apis"
21
+ has_many :constants
22
+ end
23
+
24
+ class Constant < LookupBase
25
+ set_table_name "constants"
26
+ belongs_to :api
27
+ has_many :entries
28
+ end
29
+
30
+ class Entry < LookupBase
31
+ set_table_name "entries"
32
+ belongs_to :constant
33
+ end
34
+
35
+ end
36
+
37
+ class SetupTables < ActiveRecord::Migration
38
+ def self.connection
39
+ APILookup::Api.connection
40
+ end
41
+
42
+ def self.up
43
+ create_table :apis do |t|
44
+ t.string :name, :url
45
+ end
46
+
47
+ create_table :entries do |t|
48
+ t.string :name, :url
49
+ t.references :constant
50
+ t.integer :weighting, :default => 0
51
+ t.integer :count, :default => 0
52
+ end
53
+
54
+ create_table :constants do |t|
55
+ t.string :name, :url
56
+ t.references :api
57
+ t.integer :weighting, :default => 0
58
+ t.integer :count, :default => 0
59
+ end
60
+ end
61
+ end
62
+
63
+ FileUtils.mkdir_p(File.join(ENV["HOME"],".lookup"))
64
+
65
+ if !APILookup::Api.table_exists? &&
66
+ !APILookup::Constant.table_exists? &&
67
+ !APILookup::Entry.table_exists?
68
+ SetupTables.up
69
+ APILookup.update
70
+ end
@@ -0,0 +1,32 @@
1
+ require File.dirname(__FILE__) + '/spec_helper'
2
+
3
+ describe "Lookup" do
4
+ before do
5
+ # So it outputs text for us.
6
+ OPTIONS.merge!({ :text => true })
7
+ end
8
+
9
+ it "should be able to find a constant" do
10
+ Lookup.do("ActiveRecord::Base")
11
+ end
12
+
13
+ it "should be able to find a constant and a method (using hash symbol)" do
14
+ Lookup.do("ActiveRecord::Base#new")
15
+ end
16
+
17
+ it "should be able to find a constant and a method (using space)" do
18
+ Lookup.do("ActiveRecord::Base new")
19
+ end
20
+
21
+ it "should be able to do a fuzzy match on the method" do
22
+ Lookup.do("ActiveRecord::Base#destry")
23
+ end
24
+
25
+ it "should prompt the user to be more specific" do
26
+ Lookup.do("be")
27
+ end
28
+
29
+ it "should be able to do a fuzzy match on the constant and method" do
30
+ Lookup.do("AR::B#destroy")
31
+ end
32
+ end
@@ -0,0 +1,3 @@
1
+ $TESTING=true
2
+ $:.push File.join(File.dirname(__FILE__), '..', 'lib')
3
+ require 'lookup'
metadata ADDED
@@ -0,0 +1,64 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: yyyc514-lookup
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.2.0
5
+ platform: ruby
6
+ authors:
7
+ - Ryan Bigg
8
+ autorequire: lookup
9
+ bindir: bin
10
+ cert_chain: []
11
+
12
+ date: 2009-03-30 00:00:00 -07:00
13
+ default_executable: lookup
14
+ dependencies: []
15
+
16
+ description: A gem that provides a lazy man's ri
17
+ email: radarlistener@gmail.com
18
+ executables:
19
+ - lookup
20
+ extensions: []
21
+
22
+ extra_rdoc_files:
23
+ - README.md
24
+ - LICENSE
25
+ - TODO
26
+ files:
27
+ - LICENSE
28
+ - README.md
29
+ - Rakefile
30
+ - TODO
31
+ - lib/config.rb
32
+ - lib/lookup.rb
33
+ - lib/models.rb
34
+ - spec/lookup_spec.rb
35
+ - spec/spec_helper.rb
36
+ - bin/lookup
37
+ has_rdoc: true
38
+ homepage: http://gitpilot.com
39
+ post_install_message:
40
+ rdoc_options: []
41
+
42
+ require_paths:
43
+ - lib
44
+ required_ruby_version: !ruby/object:Gem::Requirement
45
+ requirements:
46
+ - - ">="
47
+ - !ruby/object:Gem::Version
48
+ version: "0"
49
+ version:
50
+ required_rubygems_version: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: "0"
55
+ version:
56
+ requirements: []
57
+
58
+ rubyforge_project:
59
+ rubygems_version: 1.2.0
60
+ signing_key:
61
+ specification_version: 2
62
+ summary: A gem that provides a lazy man's ri
63
+ test_files: []
64
+