public
Last active

  • Download Gist
tableless_columns.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.