Thursday, June 28, 2012

Easily Override ActiveRecord Model Instance Attributes in Specific Environments

Was looking for a trivial way to override an ActiveRecord model instance's attribute that would have been non-trivial to setup, and I wanted to only override it in development. I ended up writing a generic implementation and releasing it as a gem called: activerecord-attribute_override.

For example, to override my_attribute_name method in my_model instance to return 'some value':

my_model.override_attribute(:my_attribute_name, 'some value')
Override my_attribute_name method in my_model instance to return 'some value' only when Rails.env is 'development':
my_model.override_attribute(:my_attribute_name, 'some value', :development)
Override my_attribute_name method in my_model instance to return 'some value' only when Rails.env is 'test' or 'production':
my_model.override_attribute(:my_attribute_name, 'some value', [:test, :production])
Override my_attribute_name and my_other_attribute_name:
my_model.override_attributes({my_attribute_name: 'some value', my_other_attribute_name: 'some other value'})
Override my_attribute_name and my_other_attribute_name only when Rails.env is 'development':
my_model.override_attributes({my_attribute_name: 'some value', my_other_attribute_name: 'some other value'}, :development)
Override my_attribute_name and my_other_attribute_name only when Rails.env is 'test' or 'production':
my_model.override_attributes({my_attribute_name: 'some value', my_other_attribute_name: 'some other value'}, [:test, :production])

Please check it out if you get a chance, and submit any issues and suggestions via GitHub.

No comments: