Skip to content

Instantly share code, notes, and snippets.

@owenthereal
Created December 16, 2010 22:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save owenthereal/744165 to your computer and use it in GitHub Desktop.
Save owenthereal/744165 to your computer and use it in GitHub Desktop.
class User < ActiveRecord::Base
include TablelessColumns
tableless_column :license_accepted, :boolean
# other fields that are corresponding to table columns
end
module TablelessColumns
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def tableless_columns
read_inheritable_attribute(:tableless_columns)
end
def tableless_column(name, sql_type = nil, default = nil, null = true)
write_inheritable_attribute(:tableless_columns, {}) if tableless_columns.nil?
tableless_columns[name] = ActiveRecord::ConnectionAdapters::Column.new(name.to_s, default, sql_type.to_s, null)
define_method("#{name.to_s}=".to_sym) { |value| instance_variable_set(to_variable(name), value) }
define_method(name) { self.class.tableless_columns[name].type_cast(instance_variable_get(to_variable(name))) }
end
end
def to_variable(sym)
"@#{sym.to_s}".to_sym
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment