In the python world, there are a number of alternative python interpreters that add cool additional features. One particularly useful example is bpython, which adds dynamic syntax highlighting, automatically pulls documentation, and displays live autocomplete information. In the Ruby world, I have yet to uncover any projects which add to the basic IRB interpreter even a subset of these features. Am I just not looking hard enough, or is this just something the Ruby community is lacking?
Use Pry: https://github.com/pry/pry
Let's you:
start sessions at runtime
view method source code
view method documentation (not using RI so you dont have to pre-generate it)
pop in and out of different contexts
syntax highlighting
gist integration
view and replay history
open editors to edit method using edit-method obj.my_method syntax
A tonne more great and original features
What a coincidence. Rubyflow just yesterday announced the irbtools gem, which is a meta-gem containing lots of cool irb enhancement gems. It contains:
Colorized and output as comment by wirb and fancy_irb
Nice IRB prompt and IRB’s auto indention
Includes stdlib’s FileUtils: ls, cd, pwd, ln_s, rm, mkdir, touch, cat
Many debugging helpers: ap, q, o, c, y, Object#m, Object#d
ap – awesome_print
q – like p, but on one line
Object#m – ordered method list (takes integer parameter: level of nesting)
Object#d – puts the object, returns self (using tap)
“Magical” information constants: Info, OS, RubyVersion, RubyEngine
OS.windows?
RubyEngine.jruby?
RubyVersion.is.at_least? 1.9
Clipboard features: copy and paste
also available: copy_input and copy_output for session history
Call vim (or another supported editor) to edit a file, close it and it gets loaded into your current irb session, powered by interactive_editor
Another way of live loading into irb: sketches
Highlight a string with olorize('string') or a file with ray('path'), powered by coderay
Displays ActiveRecord database entries as tables with hirb
Restart irb with reset! or change the Ruby version with the use method and rvm!
Includes the current directory in the load path (was removed in 1.9.2 for security reasons, but is pretty annoying in IRB)
Shorter requiring like this: rq:mathn
And rerquiring with rrq
Try the included Object#ri helper, powered by ori!
Access to a lot of more commands with boson – call commands to get started
There are nice screenshots on the irbtools page. One nice thing about it is that each of the utilities can stand on its own, in case you just want to cherry-pick one or two features.
2013 Update
Since I wrote this, Pry has become a popular IRB replacement. It doesn't do as much as irbtools out of the box, but it extensible with plugin gems that add cool features. You can browse source code like it was a unix directory:
pry(main)> cd FileUtils
pry(FileUtils):1> show-method rm
From: /opt/ruby/lib/ruby/1.9.1/fileutils.rb # line 556:
Number of lines: 10
Owner: FileUtils
def rm(list, options = {})
fu_check_options options, OPT_TABLE['rm']
list = fu_list(list)
fu_output_message "rm#{options[:force] ? ' -f' : ''} #{list.join ' '}" if options[:verbose]
return if options[:noop]
list.each do |path|
remove_file path, options[:force]
end
end
pry(FileUtils):2>
You can also browse Ruby documentation, issue shell commands, and if you're a Rails user, you can use the pry-rails gem to get pry in your Rails console. There's also a way to hook it into Sinatra and use it with Heroku.
There's ample documentation--there are a bunch of screencasts including a Railscast. It's definitely worth looking into.
I've never heard of a (popular) alternative to IRB, but there certainly are several useful gems that make the IRB experience a lot nicer:
awesome_print pretty prints Ruby objects with indentation and coloring, very useful when trying to look at nested hashes or other complicated data structures.
looksee is pretty awesome too, it provides a method lp (lookup path) that shows you where a Ruby object gets its methods from (class, superclass etc).
Sketches connects your editor and IRB, so it's especially useful if you are the type who likes interactive development. Emacs with inf-ruby is also good for this.
Wirble is a whole set of IRB enhancements, like tab completion and syntax highlighting. There's also Utility Belt, but I don't personally use that, so can't comment on its features.
Edit
I forgot Hirb, which is very useful for e.g. showing the results of an ActiveRecord query in a Rails console.
There's http://github.com/alloy/dietrb.
JRuby ships with jirb_swing, which provides code completion.
There's not much in the area of alternatives to irb, but there are a couple of gems that add useful features to irb.
Most notably wirble, which, among other things, gives you colored output (not input though) and a history that goes beyond the current session.
Check out ripl, a modular irb alternative which is designed to be extendable. You may also get some answers from Is there something like bpython for Ruby?.
rib is a modular and light Ruby interactive shell.
It, like Pry, uses Ruby's parser so has consistent behavior with Ruby thus less bugs (e.g. https://stackoverflow.com/a/39271791/474597)
It is modular so one can easily extend it with more functionalities.
It is also still actively maintained as of 2016.
I made a pure Ruby console, inspired off Google Chrome's JavaScript console.
https://github.com/sancarn/RubyConsole
It's still mostly a WIP project as I keep finding bugs with the current algorithm, however I'm building it to be 1.9.3+ compatible.
Related
I'm developing a "Rails-less" Ruby daemon for automation (although in theory it runs within a Rails directory). For general purposes and the principle of the matter, I would like to find the (most) "native"/common way to utilize a Ruby version of .present?/.blank?/.empty?/.nil? to identify if an array or a (hash) value exists and is not empty (i.e., [] or {}).
From what I've read (e.g., Stack Overflow) and tested, all of these functions appear to be Rails-specific methods, part of ActiveSupport(?).
Coming from other web/interpreter languages (PHP, Python, JS, etc.), this is a general logic function most languages (with arrays, which are most) have this functionality built in one way or another (e.g., PHP's isset( ... ) or JavaScript's .length).
I understand there are RegEx workarounds for .blank?, but .present? seems it would require exception handling to identify if it's "present"). I'm having a hard time believing it doesn't exist, but there's little talk about Ruby without Rails' involvement.
Active Support is broken in small pieces so that you can load just what you need. For .blank? and .present? methods it would be enough to require:
require 'active_support/core_ext/object/blank.rb'
As docs say.
Object#nil? , Array#empty? and Hash#empty? already defined so you dont need anything to require to use those.
Make sure active_support gem installed in your system
You can use ActiveSupport without including all rails in your app, that's actually quite common.
nil? and empty? are defined in the standard library.
E.g., String#empty? is simply testing if the length is 0.
To use active support, just install the gem or add it to your gemfile then:
require 'active_support'
The documentation also states you can cherry pick the core extensions you want:
require 'active_support/core_ext/object/blank'
With this minimal ruby code:
require 'debug'
puts
in a file called, e.g. script.rb
if I launch it like so: ruby -rdebug script.rb
and then press l on the debug prompt, I get the listing, as expected
if I instead run it normally as ruby script.rb
when pressing l I get:
(rdb:1) l
[-3, 6] in script.rb
No sourcefile available for script.rb
The error message seems misleading at best: the working directory hasn't changed, and the file is definitely still there!
I'm unable to find documentation on this behavior (I tried it on both jruby and mri, and the behavior is the same)
I know about 'debugger' and 'pry', but they serve a different use case:
I'm used to other scripting languages with a builtin debug module, that can let me put a statement anywhere in the code to drop me in a debug shell, inspect code, variables and such... the advantage of having it builtin it's that it is available everywhere, without having to set up an environment for it, or even when I'm on a machine that's not my own
I could obviously workaround this by always calling the interpreter with -rdebug and manually setting the breakpoint, but I find this more work than the alternative
After looking into the debug source code, I found a workaround and a fix:
the workaround can be:
trace on
next
trace off
list
this will let you get the listing without restarting the interpreter with -rdebug, with the disadvantage that you'll get some otherwise unwanted output from the tracing, and you'll be able to see it only after moving by one statement
for the fix: the problem is that the SCRIPT_LINES__ Hash lacks a value for the current file... apparently it's only set inside tracer.rb
I've changed line 161, and changed the Hash with a subclass that tracks where []= has been called from, and I wasn't able to dig up the actual code that does the work when stepping into a function that comes from a different file
Also: I haven't found a single person yet who actively uses this module (I asked both on #ruby, #jruby and #pry on freenode), and together with the fact that it uses a function that is now obsolete it leads me to be a bit pessimistic about the maintenance state of this module
nonetheless, I submitted a pull request for the fix (it's actually quite dumb and simple, but to do otherwise I'd need a deeper understanding of this module, and possibly to refactor some parts of it... but if this module isn't actively maintaned, I'm not sure that's a good thing to put effort on)
I suspect the Ruby interpreter doesn't have the ability to load the sourcefile without the components in the debug module. So, no -rdebug, no access to the sourcefile. And I agree it is a misleading error. "Debugging features not loaded" might be better.
Exumerant Ctags does not work well with Ruby, you can see there are many hacks in the ruby.c code and basically it fails recognizing many cases. One of the most important is this bit:
class SomeModule::SomeClass
end
Ctags generates:
SomeModule someclass.rb /^class SomeModule::SomeClass$/;" c
which is wrong. The correct and expected entry is:
SomeClass someclass.rb /^class SomeModule::SomeClass$/;" c
This is very limiting. There are some patches for ctags available which does not work, e.g. https://github.com/xtao/overlay/blob/master/dev-util/ctags/files/ctags-5.5.4-ruby-classes.patch but looking on the ctags ruby codebase, this really needs complete rewrite.
So I have been playing with other option which is https://github.com/rdoc/rdoc-tags which works nicer, but it is slow. I mean really SLOW. Generating tags on my project is 2 seconds with ctags but one hour with this tool. Really.
I found one old project that was parsing Ruby on it's own and generating tags, but it was only for Ruby 1.8. It was slower than ctags, but not that bad.
So I am searching for some alternatives. Do you know about any other working ruby ctags generators which give you proper output and are fast?
Thanks!
Edit: I have found very nice project that works with Ruby 1.9+ and is accurate and fast. I recommend it:
https://github.com/tmm1/ripper-tags
Ripper-tags effort does solve everything described here. It is based on official Ruby parser which is also quite fast. https://github.com/tmm1/ripper-tags
gem install ripper-tags
cd your_project/
ripper-tags -R
It does also support Emacs as well.
Exuberant ctags out of the box doesn’t do a number of useful things:
It doesn’t deal with:
module A::B
It doesn’t tag (at least some of) the “operator” methods like ‘==’
It doesn’t support qualified tags, —type=+
It doesn’t output tags for constants or attributes.
Patch available, but it is only for version 5.5 and does not work anymore.
Other projects:
https://github.com/tmm1/ripper-tags (best option for Ruby 1.9+)
https://rubygems.org/gems/rdoc-tags (very slow but works with 1.8)
Source
Add following to your ~/.ctags
--regex-ruby=/(^|;)[ \t]*(class|module)[ \t]+([A-Z][[:alnum:]_]+(::[A-Z][[:alnum:]_]+)+)/\3/c,class,constant/
So you can:
deal with: module A::B
See more here: https://github.com/bltavares/dot-files/blob/master/ctags
A patch is available as of 2013-02
https://github.com/fishman/ctags (ctags patch for Ruby, including rspec)
the rspec tag generator will not properly recognize describe blocks that start with semicolor (:some-method), but other than that, it's great.
There is also https://github.com/eapache/starscope
It doesn't support the extended tag format (yet) but it does other things such as exporting cscope databases.
I'm reading through "Programming Ruby 1.9". On page 208 (in a "Where to Put Tests" section), the book has the code organized as
roman
lib/
roman.rb
other files...
test/
test_roman.rb
other_tests...
other stuff
and asks how we get our test_roman.rb file to know about the roman.rb file.
It says that one option that doesn't work is to build the path into require statements in the test code:
# in test_roman.rb
require 'test/unit'
require '../lib/roman'
Instead, it says a better solution is for all other components of the application to assume that the top-level directory of the application is in Ruby's load path, so that the test code would have
# in test_roman.rb
require 'test/unit'
require '/lib/roman'
and we'd run the tests by calling ruby -I path/to/app path/to/app/test/test_roman.rb.
My question is: is this realy the best way? It seems like
If we simply replaced require '../lib/roman' in the first option with require_relative '../lib/roman', everything would work fine.
The assumption in the second option (that all components have the top-level directory in Ruby's load path) only works because we pass the -I path/to/app argument, which seems a little messy.
Am I correct that replacing require with require_relative fixes all the problems? Is there any reason to prefer the second option anyways?
Further on, that same book makes use of require_relative (Chapter 16, Organizing your source code) in the context of testing, so yes, I would say that using it is a Good Thing, since it "always loads files from a path relative to the directory of the file that invokes it".
Of course, like #christiangeek noticed, require_relative is new in the 1.9 series, but there's a gem that provides you with the same functionality.
It might be worth pointing out that the Pickaxe too provides a little method you can stick in your code in the same chapter I mentioned before.
require_relative does make the code cleaner but is only available natively on Ruby > 1.9.2. Which means if you want want your code to be portable to versions of Ruby < 1.9.2 you need to use a extension or the regular require AFAIK. The book is most likely a) written before 1.9.2 became widespread or b) providing a example for lowest common denominator.
Most of the code I write is in Ruby, and every once in a while, I make some typo which only gets caught after a while. This is irritating when I have my scripts running long tasks, and return to find I had a typo.
Is there an actively developed lint tool for Ruby that could help me overcome this? Would it be possible to use it across a system that works with a lot of source files, some of them loaded dynamically?
Take this snippet as an example:
a = 20
b = 30
puts c
To win bounty, show me a tool that will detect the c variable as not created/undefined.
ruby -c myfile.rb will check for correct Ruby syntax.
Reek checks Ruby code for common code smells.
Roodi checks Ruby code for common object-oriented design issues.
Flog can warn you about unusually complex code.
[Plug] If your project is in a public Github repository, Caliper can run the latter three tools and others on your code every time you commit. (Disclaimer: I work on Caliper)
You could give Diamondback Ruby a try. It does a static typecheck of Ruby code, and will thus blame you for using an undefined variable.
While DRuby is an ongoing research project, it already works quite well for small, self-contained Ruby scripts. Currently, it is unable to analyze much of the Ruby standard library “out-of-the-box”. Currently they are working toward typing Ruby on Rails (see their most recent papers).
RubyMine (http://www.jetbrains.com/ruby) does the trick:
alt text http://img707.imageshack.us/img707/5688/31911448.png
None of the below will do all the analysis that RubyMine does.
NetBeans Ruby pack
Aptana RadRails
gVIM (with syntastic plugin by scrooloose)
Each of these has the capacity to identify syntax errors such as wrong number of parentheses, too many defs, ends, braces, etc. But none will identify invalid method calls the way RubyMine does.
Here's why: it's difficult.
Since Ruby is extremely dynamic (and methods like 'c' could easily be generated on the fly), any editor that tries to identify non-existent variables/methods would need to have a large part of the entire evironment loaded and multiple program flow paths constantly tested in order to get accurate 'validity' results. This is much more difficult than in Java where almost all programming is static (at least it was when I dropped that hat).
This ability to easily generate methods on the fly is one of the reasons the community holds testing to such high esteem. I really do reccomend you try testing as well.
Have a look at RuboCop. It is a Ruby code style checker based on the Ruby Style Guide. It's maintained pretty actively and supports all major Ruby implementations. It works well with Ruby 1.9 and 2.0 and has great Emacs integration.
Yes. Test::Unit
Ok, I know you already know this and that in some sense this is a non-helpful answer, but you do bring up the negative consequence of duck typing, that there kind of is (at this time) no way around just writing more tests than something like Java might need.
So, for the record, see Test::Unit in the Ruby Standard Library or one of the other test frameworks.
Having unit tests that you can run and rerun is the best way to catch errors, and you do need more of them (tests, not errors :-) in dynamic languages like Ruby...
nitpick might be what you're lookng for.
With this code:
class MyString < String
def awesome
self.gsub("e", "3").gsub("l", "1").uppercase
end
end
puts MyString.new("leet").awesome
... it outputs:
$ nitpick misspelling.rb
*** Nitpick had trouble loading "misspelling.rb":
NoMethodError undefined method `uppercase' for "133t":MyString
Nothing to report boss! He's clean!
Have not used it yet, but sounds promising (will update when I've tested this).
https://github.com/michaeledgar/laser
Static analysis and style linter for Ruby code.
Pelusa is nice, but is working in rubinius only. This shouln't be a proplem for people familar with RVM though.
avdi#lazarus:~$ irb
>> a = 20
=> 20
>> b = 30
=> 30
>> puts c
NameError: undefined local variable or method `c' for main:Object
from (irb):3
>>
There ya go, the tool is called "IRB". Do I get the bounty?
I'm only half joking. I wrote this second answer to hopefully drive home the point that in Ruby, if you want to know that something is defined or not, you have to run the code.