SciRuby / iruby

Official gem repository: Ruby kernel for Jupyter/IPython Notebook
https://github.com/SciRuby/iruby
MIT License
890 stars 27 forks source link

Allow `pre_run_cell` to modify cell #319

Open felix-dumit opened 2 years ago

felix-dumit commented 2 years ago

This change allows for pre_run_cell events to modify the content of the cell before it is executed.

One use case for this is a lightweight implementation of magic comments, the event can look for a particular pattern and modify the string before it is run.

kojix2 commented 8 months ago

Hi @felix-dumit

Thanks for the pull request. There are not many active maintainers on iruby and sorry for not replying for 2 years. If possible, we would like to merge the PRs received. Please provide use cases and screenshots if you have them.

felix-dumit commented 8 months ago

Hi @kojix2,

Thanks taking a look at this.

The way I am currently using this is as a building block to enable some light-weight magic comment functionality in ruby jupyter notebooks, so I have this code for example that runs during jupyter setup:

IRuby::Kernel.instance.events.register(:pre_run_cell) do |result|
        # magic comment
        if result.raw_cell.start_with?(MAGIC_COMMENT_PREFIX)
          result.raw_cell.delete_prefix!(MAGIC_COMMENT_PREFIX)
          result.raw_cell = wrap_in_staging_call(result.raw_cell)
        end
end

Here's a screenshot showing the difference when running with the magic comment (in my case it makes any queries go to a staging db server, instead of my local one), and without (local)

image

But this simple change in the code would allow any custom code editing on top of the raw cell content before it is actually executed.

kojix2 commented 8 months ago

Thank you very much. I understand the use case. However, it looks like IPython does not allow me to change the code using pre_run_cell.

image

What do you think @mrkn?