Overwriting "Constants"

In Ruby, constants aren't the same as in other languages since you can change them at runtime. This code:

ENDPOINT_URL = 'http://mysubdomain.unfuddle.com/api/v1/'
ENDPOINT_URL = 'http://othersubdomain.unfuddle.com/api/v1/'
puts ENDPOINT_URL

produces this output (including the warning):

warning: already initialized constant ENDPOINT_URL
http://othersubdomain.unfuddle.com/api/v1/

If you need to override a constant and don't want to trigger a warning (in a test environment, for example) you can use the replace method:

ENDPOINT_URL = 'http://mysubdomain.unfuddle.com/api/v1/'
ENDPOINT_URL.replace 'http://othersubdomain.unfuddle.com/api/v1/'
puts ENDPOINT_URL

This will only work with those objects that have a replace method defined (e.g. Array, Hash, and String) and the new value must have the same datatype.

blog comments powered by Disqus