
On the Floor
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
Subscribe 
Follow us on
Twitter 
Archives
May 2012April 2012
March 2012
February 2012
January 2012
December 2011
November 2011
October 2011
September 2011
August 2011
July 2011
May 2011
April 2011
March 2011
February 2011
January 2011
December 2010
November 2010
October 2010
September 2010
August 2010
July 2010
June 2010
May 2010
April 2010
March 2010
February 2010
January 2010
December 2009
November 2009
October 2009
September 2009
June 2009
March 2009
January 2009
December 2008
November 2008
September 2008
August 2008









Comments
Add a Comment