The Blog

Dec 2
0

My “Freedom Patch” Gem: constant-redefinition

by David Czarnecki

Categories

The constant-redefinition gem allows you to define constants if not defined on an object and redefine constants without warning.

Are you still with me? Good.

The code “credit” for this gem comes from the Stack Overflow post, “How to redefine a Ruby constant without warning?”. It just so happens that I was working on a project today where our test suite was testing a large number of iterations to write out data. I wanted to redefine the number of iterations in test (based on a constant in the model) to respect the spirit of the test, but not do as many iterations in test. I googled, found that post, and it seemed like a neatly packageable item that would be useful to other developers.

So, I created the constant-redefinition gem. You can also check out the GitHub constant-redefinition project. My contribution was merely packaging it up as a gem, formalizing the tests, and making the method names longer (sue me, I prefer readability).

The project page has a good overview of using the two methods, but I’ll reproduce it here.

Define a constant if not defined:

    define_if_not_defined(:A, 1)
  
    assert_equal 1, A
  
Define a constant and redefine it:

    define_if_not_defined(:B, 1)
    redefine_without_warning(:B, 2)
    
    assert_equal 2, B
    
Redefine a constant which should set the constant:

    redefine_without_warning(:C, 3)
    
    assert_equal 3, C

Define a constant within a module:

    Math.define_if_not_defined(:FOO, 2 * Math::PI)
    
    assert_equal 2 * Math::PI, Math::FOO

Define and redefine a constant within a module:

    Math.define_if_not_defined(:BAR, 3)
    Math.redefine_without_warning(:BAR, 5)

    assert_equal 5, Math::BAR

Redefine a constant within a module which should set the constant:

    Math.redefine_without_warning(:AMAZING, 3)
    
    assert_equal 3, Math::AMAZING

view raw gistfile1.txt This Gist brought to you by GitHub.

You may know “freedom patch” by its other names, “monkey patch” or “duck punch”.

You can find more hilarity over on my Twitter account, CzarneckiD.

  • Reddit
  • Digg
  • del.icio.us
  • Facebook
  • Tumblr
  • Twitter

Leave a Reply

*