Last active
December 11, 2015 06:19
-
-
Save jamilbk/4558815 to your computer and use it in GitHub Desktop.
Implement status states in code using an integer column in the DB.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Implement status states in code using an integer column in the DB | |
# Written by Jamil Bou Kheir, 2012 | |
# | |
# Include this module at the top of your model and use the stuffed_table_columns | |
# method to assign the mappings. Requires a matching integer column present. | |
# Ex: | |
# | |
# class StirFry < ActiveRecord::Base | |
# include StuffedTableColumns | |
# stuffed_column :status, 'cold', 'hot', 'pickled', 'spicy', 'no_msg', 'noodling' | |
# end | |
# TODO: use method_missing to support other column names besides "status" | |
module StuffedTableColumns | |
def self.included(base) | |
base.extend ClassMethods | |
end | |
def status | |
if read_attribute(self.class.instance_variable_get(:@column_name)).blank? | |
read_attribute(self.class.instance_variable_get(:@column_name)) | |
else | |
self.class.instance_variable_get(:@column_options)[read_attribute(self.class.instance_variable_get(:@column_name))] | |
end | |
end | |
def status=(status) | |
if self.class.instance_variable_get(:@column_options).include? status | |
write_attribute(self.class.instance_variable_get(:@column_name), self.class.instance_variable_get(:@column_options).index(status.downcase)) | |
elsif status.blank? | |
write_attribute(self.class.instance_variable_get(:@column_name), status) | |
else | |
raise "Error writing status attribute: Not one of #{self.class.instance_variable_get(:@column_options).join(', ')}" | |
end | |
end | |
module ClassMethods | |
def stuffed_column(column, *options) | |
@column_options = options | |
@column_name = column | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment