Skip to content

@jingweno /tableless_columns.rb
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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
Something went wrong with that request. Please try again.