Hooking a function to run in IRB context (but only in IRB context)?

Hi.

I start IRB.

Then I do something like:

pj

(Input is “pj”)

The result is:

NameError: undefined local variable or method `pj’ for
#Object:0xb751d954
from (irb):7

Ok, this is what normally happens.

Now I want to hook up a specific class. Let’s call it

class Foo
end

This class should intercept BEFORE NameError happens. It should then
check that input, like:

Foo.new(input)
Foo.new(‘pj’)

And it will decide against an internal list:

  • When the input was found in the internal list, an action is done,
    and no error is reported.

  • When the input was NOT found, a NameError is triggered just as it
    currently is.

In other words, I need the ability to hook up a specific class before
NameError happens in IRB.

Does anyone have an idea how to do that?

On Sun, Feb 5, 2012 at 3:57 AM, Marc H. [email protected]
wrote:

The result is:
class Foo

Don’t know how to do it with irb, but if you use pry (which is way
better
than irb), you can write a command for it
https://github.com/pry/pry/wiki/Command-system

Hmm thanks but … I am really not sure how to do that …

Marc H. wrote in post #1044196:

Hmm thanks but … I am really not sure how to do that …

Put this in your .pryrc

Pry.commands.block_command “greet” do |name|
puts “hello #{name}!”
end

Commands, can also be regular expressions, try this:

Pry.commands.block_command /[Hh]ello/ do
puts “you called?”
end

Both these commands can only be invoked in the REPL (as you wanted);
they are invoked as follows:

pry(main)> greet marcus
hello marcus!
pry(main)> hello
you called?
pry(main)> Hello
you called?

Marc H. wrote in post #1044134:

Now I want to hook up a specific class. Let’s call it

class Foo
end

This class should intercept BEFORE NameError happens. It should then
check that input, like:

Foo.new(input)
Foo.new(‘pj’)

And it will decide against an internal list:

  • When the input was found in the internal list, an action is done,
    and no error is reported.

  • When the input was NOT found, a NameError is triggered just as it
    currently is.

def method_missing(meth,*args,&blk)
puts “You tried to run ‘#{meth}’”
end
=> nil

pj
You tried to run ‘pj’
=> nil

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs