Today I Learned

A Zero One initiative

4 posts by dominicsanto

Stimulus Use

I was getting rather annoyed when using modals with stimulus, especially when it came to actually closing them. I didnt like the way I wrote the general function to close the modals so I decided to refactor it. In doing so I came across a package that would solve it all. The package is called stimulus-use (https://github.com/stimulus-use/stimulus-use). It enables new lifecycle behaviors to your stimulus controllers. Now I can close my modals like so, instead of trying to check if my modal has a click event outside of it:

import { Controller } from 'stimulus'
import { useClickOutside } from 'stimulus-use'

export default class extends Controller {

  connect() {
    useClickOutside(this)
  }

  clickOutside(event) {
    event.preventDefault()
    this.modal.close()
  }
}

Ensure clauses

Today I learned about the ensure clause when raising exceptions. I was having trouble cleaning up certain operations, now within the ensure block the code will always get executed whether an exception is raised or not.

def foo
  begin
     raise Exception, "Oh no"
   ensure
     return "Clean me up Scotty"
  end
end