How to run IRB.start in context of current class

后端 未结 8 985
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-29 21:23

I\'ve been just going through PragProg Continuous Testing With Ruby, where they talk about invoking IRB in context of current class to inspect the code

8条回答
  •  长发绾君心
    2020-12-29 22:24

    As you've already discovered, self does not refer to the object where IRB was started, but to the TOPLEVEL_BINDING, which seems to be an instance of the Object class itself.

    You can still run an IRB session with a specific class or object as the context, but it's not as simple as just starting IRB.

    If you care about is starting IRB with a specific context, then it's really easy to do when you're starting IRB manually. Just start IRB normally and then call the irb method, passing it the object/class you want as the context.

    $ irb
    irb(main):002:0> require 'myclass'
    => true
    irb(main):003:0> irb MyClass
    irb#1(MyClass):001:0> self
    => MyClass
    

    You can also start an IRB session programmatically and specify the context, but it's not nearly as easy as it should be because you have to reproduce some of IRB's start-up code. After a lot of experimenting and digging around in the IRB source code, I was able to come up with something that works:

    require 'irb'
    IRB.setup nil
    IRB.conf[:MAIN_CONTEXT] = IRB::Irb.new.context
    require 'irb/ext/multi-irb'
    IRB.irb nil, self
    

提交回复
热议问题