On-the-floor

On the Floor

Reversible Rails Generators

In order to help us develop our sites more efficiently, we use some custom Rails generators, particularly one that creates a scaffold hand-crafted for our purposes.  After generate-ing a new scaffold incorrectly, I destroyed it.  I noticed, however, that one of the steps in the scaffold had been duplicated during the destroy, rather than being reversed.  Hmm, how to fix that?

First things first, when you run a generator (either by invoking it with generate or destroy), every method is called once.  So, the secret to creating a reversible method is in discovering how the generator was invoked.  After doing a ton of Googling, then reading the Thor documentation and source code, I found out that you just need to check self.behavior inside the method, and tailor the code depending on the return value, like this:

def do_some_stuff
  case self.behavior
  when :invoke
    # do that stuff
  when :revoke
    # undo it!
  end
end

Bam!  Reversible generator.

Bonus tip:  One of the methods I wanted to reverse required some user action once the method had run.  You can output coloured output from the method by using the say method, and passing it the string and the colour.  To save you the googling, source code reading and head-scratching, you specify the colour like this:

say "WTF?!?", :red

Comments

There are no comments to display.

Add a Comment

Your Comment:

Your Name:

Your Email Address: (Won't be published)

Your Website: (If you've got one)