Suppressing IRB warning when overriding irb_help alias - ruby

I'm working on an application that's a glorified wrapper around irb, and I would like to override the "help" command (which by default seems to be an alias to irb_help). I'm using the approach of executing the following code before allowing the user to do anything in the prompt:
class << self
def help
my_custom_help
end
end
While this seems to work, I get an annoying warn message every time I start the application:
irb: warn: can't alias help from irb_help.
Is there any way to suppress this warning message?

Related

Handle Commander errors manually in Ruby

I'm writing a simple Commander CLI as part of a project I'm working on.
Commander has its own method of handling errors. For example, if the user enters an invalid command, then Commander will print a user-friendly message:
$ my-commander-program some-invalid-command
invalid command. Use --help for more information.
I would like to replace this message with my own, so that the output is more consistent with the rest of my program. For example:
$ my-commander-program some-invalid-command
[ERR ] 'some-invalid-command' is not a known command.
Use --help to see a list of valid commands.
I've looked at Commander's README.md, which contains plenty of examples of how to use Commander, but I can't find how to do this from there.
My program is written using Commander's 'classic' style, where one imports commander/import and uses methods like program and command from the top-level, rather than creating a class which includes Commander::Methods. For example:
require 'commander/import'
program :name, 'my-commander-program'
program :version, '1.0.0'
program :description, 'Example'
command :example do |c|
c.action do |args, options|
puts "Invoked!"
end
end
How can I go about replacing this error message? I'm using Commander 4.4.5.

Not able to get result for def using ruby on mac osx

This is just a sample method I have created for testing purpose using Ruby on Mac OSX 10.12 but I don't get the desired output: Can anyone suggest please? I tried getting the result using both paranthesis and without (). It doesn't even throw any error.
def hi
puts "Hello World"
End
hi
hi()
hi("Hello Matz")`
Try this:
def hi
puts "Hello World"
end
hi
hi()
And this:
def greet(greeting)
puts greeting
end
greet("Hello Matz")
Note that in this line:
hi("Hello Matz")`
you have a tick mark at the end, so that is an error:
1.rb:5: syntax error, unexpected tXSTRING_BEG, expecting end-of-input
It doesn't even throw any error.
Then you aren't running that program.
I suggest you open a Terminal window (Applications/Utilities/Terminal.app), and type in:
$ vimtutor
vim is a free computer programming editor that comes with your Mac. Do the tutorial and learn how to use vim. To run a ruby program, you enter your code into a file, then save it as, say, my_prog.rb. Then you need to give that file to ruby to execute it. You execute a ruby program like this:
$ ruby my_prog.rb
You can create a directory for all your ruby programs like this:
$ mkdir ruby_programs
$ cd ruby_programs
To create a new file inside that directory, use vim:
~/ruby_programs$ vi my_prog.rb
Once you are done typing in your code, save the file, which will put you back at the prompt in Terminal, then you can run your program:
~/ruby_programs$ ruby my_prog.rb
Once you get comfortable with vim, and you feel confident running your ruby programs, consider installing macvim with the vivid chalk color scheme:
It's nicer to look at than plain vim.
Try editing your file so that it reads:
def hi
puts "Hello World"
end
hi
Some important differences to note: def and end are both case-sensitive. The inside of the function definition is indented by two spaces. Since the function takes no arguments, no parentheses are necessary on the call to hi on line 4.
Depending on your filename, enter the command ruby FILENAME and you should see the output Hello World
Ruby keywords are case sensitive. Your code uses End and you probably wanted to use end to mark the end of the hi method.
Because End is not the same as end (and End is not a keyword), irb keeps waiting for input and treats the other three lines as part of the hi method. As far as it can tell, its definition is not complete until it reaches the end keyword (all non-capital letters.)
The correct way to define the method is:
def hi
puts "Hello World"
end
Then you can call it using either hi or hi().
Calling it as hi("Hello Matz") (or hi "Hello Matz") throws an ArgumentError exception with the message wrong number of arguments (given 1, expected 0) because it is called with one argument but the definition of method hi doesn't specify anything about arguments (by its definition, the method hi doesn't accept any argument).

Enabling a console for a Ruby app

I'm trying to add a console to my Ruby cli application (much like the Rails console), but I can't seem to find a solution that does what I need:
Colorization & syntax highlighting
Ability to pass in variables or use the current context
I'd like to use pry, but I can't figure out how to disable the code context from being printed out at the start of the session. I'd like it to immediately start the session without printing anything out besides the prompt.
Here's what currently gets printed when the pry session starts:
Frame number: 0/8
From: <file_path> # line <#> <Class>#<method>:
71: def console
72: client_setup
73: puts "Console Connected to #{#client.url}"
74: puts 'HINT: The #client object is available to you'
75: rescue StandardError => e
76: puts "WARNING: Couldn't connect to #{#client.url}"
77: ensure
78: Pry.config.prompt = proc { "> " }
79: binding.pry
=> 80: end
>
Here's what I want:
>
I've also tried a few other solutions, but here's my problems with each:
IRB: No colorization, doesn't seem customizable
ripl: No colorization or syntax highlighting
Any help here would be greatly appreciated!
We usually create a separate executable file like bin/console in our project and put there content similar to this:
#!/usr/bin/env ruby
require_relative "../application"
require "pry"
Pry.start
Where application.rb is a file which loads gems via Bundler and includes all necessary application-related files, so it will be possible to use application classes in the console.
It's easy to start your console with just ./bin/console command from your terminal.
If you need to customise the look of console then official wiki at github has enough information about this: https://github.com/pry/pry/wiki/Customization-and-configuration
What I ended up doing is defining a pretty simple/empty class to bind to:
class Console
def initialize(client)
#client = client
end
end
Then in my console method:
Pry.config.prompt = proc { '> ' }
Pry.plugins['stack_explorer'] && Pry.plugins['stack_explorer'].disable!
Pry.start(Console.new(#client))
Disabling the stack_explorer prevented it from printing the Frame number info, and inside the Pry session, I can access #client as expected.

Getting an undefined local variable error in Ruby when debugging

I have the following script in a file called foo.rb
def foo(msg)
msg
end
def bar
thing = 123
thing
end
debugger
p foo(:hai)
I run the program in debug mode, like so:
ruby --debug -r debug foo.rb
Notice I make sure the stdlib debug is loaded via -r and I also put the ruby environment into debug mode using --debug
So the first output I get is unexpected:
Debug.rb
Emacs support available.
/Users/M/.rbenv/versions/2.1.2/lib/ruby/2.1.0/rubygems/core_ext/kernel_require.rb:57: RUBYGEMS_ACTIVATION_MONITOR.enter
After that, if I press c to 'continue' the program ends with the following error:
Exception `NameError' at foo.rb:10 - undefined local variable or method `debugger' for main:Object foo.rb:10:in `<main>': undefined local variable or method `debugger' for main:Object (NameError)
Can anyone tell me what I'm doing wrong, and how to actually get debug mode to recognise the relevant debugger command (if that's even the correct command to be using; the docs aren't clear at all on this)
Note: I'm not interested in using 3rd party gems in this instance (e.g. pry or ruby-debug). I'm only interested in understanding how to use the stdlib debugger that comes with Ruby
Update
Since this question was answered, I've gone ahead and created a gist for future reference. For anyone stumbling across this thread you might find it useful: https://gist.github.com/Integralist/5658cb218bb50494a1fa
Don't use -r. The entire mechanism by which an interactive debugging sessions is loaded is by the literal line of code require 'debug'.
Your code should look like this:
def foo(msg)
msg
end
def bar
thing = 123
thing
end
require 'debug'
p foo(:hai)
And you should run the program by simply typing ruby <program_name>.rb.

Running RSpec in debug mode

This is a short question: I am looking for a way to run specs in debug mode, with the -u switch, so that RSpec would drop to console whenever it failed, without having to add a debugger line into the code. Any pointers?
Will answer my own question.
Following this tutorial, I created a custom formatter, as in:
require "spec/runner/formatter/specdoc_formatter"
class DebuggerFormatter < Spec::Runner::Formatter::SpecdocFormatter
def example_failed(example, counter, failure)
super
debugger if Kernel.respond_to?(:debugger)
end
end
hakanensari, your code seems to break inside rspec. It'd be nice if we could break at the failing assert line.

Resources