Created
February 27, 2015 21:24
-
-
Save jamilbk/b689346d39ec363b000f to your computer and use it in GitHub Desktop.
Stuffed Table Columns
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
# Represent states such as 'active', 'disabled', etc in the DB as an int | |
# | |
# Use like so: | |
# | |
# class MyModel < ActiveRecord::Base | |
# include StuffedTableColumns | |
# stuffed_column :status, *(%w(active inactive blocked disabled banned)) | |
# end | |
# TODO: use method_missing to match the column name | |
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 | |
scope "with_#{column}", lambda { |status| | |
index = options.index(status.downcase) | |
where(status: index) | |
} | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment