RubyScope

grep and ack are indispensable tools, but they don’t know ruby. That’s where
RubyScope comes in. RubyScope lets you search your codebase for classes, methods, variables, and more. It understands ruby.

For instance you could use it to find all of your test methods:

ruby_scope -R --def '/^test/' ~/SecretProject

That would match:

def test_failing
  assert false
end

But it would skip this:

# TODO: test this later
def suspect_method
  test = 1 / 0
end

Installing

RubyScope is available as a normal gem:

gem install ruby_scope

Alternatively, you can get the source from GitHub:

git clone git://github.com/adamsanderson/ruby_scope.git

If you pull the source, install with rake install.

Examples

Here are some other examples of things you can do with RubyScope.

Find all the places the variable name is assigned:

ruby_scope -R --assign 'name' .

Find any place that cake is mentioned in the code base, this could be a variable, a method call, a symbol, or any other bit of ruby code:

ruby_scope -R --any 'cake' .

I often want to know where a method was defined:

ruby_scope -R --def 'save_or_fail' .

If you’re not afraid of writing a SexpPath query you can even define custom queries:

ruby_scope --custom 's(:call, s(:ivar, atom), :save, _)'

That will find all of the places save is called on an instance variable,
@post.save for instance.

Why

Ruby is a great language, it’s very flexible, but sometimes that can be annoying. These are all the same:

a = 1 / 0.0
(a = 1/0.0)
a =
  1 / 0.0

Meanwhile it can be quite frustrating to be looking for where a got assigned this ridiculous value, and have to wade through all the different places a is used.

This also served as a first step towards common code completion and refactoring tools that could be used by any ruby editor.

Hacking RubyScope

Want to play with ruby_scope? Take a look at cli.rb, this is where all the queries are actually generated. Have an idea for a better caching mechanism? Look at sexp_cache.rb. Want to change how the hits are reported? Take a look at scanner.rb

The source is on GitHub, so go ahead and branch it:

http://github.com/adamsanderson/ruby_scope
About these ads

2 Comments

Filed under ruby

2 responses to “RubyScope

  1. Stephane Liu

    Excellent replacement for my primitive: alias gr='find . -type f|grep rb$|xargs grep '

  2. andris

    also, ack-grep –ruby

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s