Created
February 25, 2014 14:21
-
-
Save ohnishiakira/9209692 to your computer and use it in GitHub Desktop.
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
module SequelAutoTableLoader | |
def method_missing(name, *args, &block) | |
if name =~ /^#{self.class.const_get(:TABLE_PREFIX)}_/ | |
table_class_name = name.to_s.split(/_/).map(&:capitalize).join | |
table_name = [table_class_name[0].downcase, table_class_name[1..-1]].join | |
unless instance_variable_defined? "@#{name}" | |
instance_variable_set( | |
"@#{name}", | |
self.class.const_get(table_class_name).send( | |
name, | |
self.send(self.class.const_get(:UNIQ_ID)) | |
) | |
) | |
end | |
_yield instance_variable_get("@#{name}"), &block | |
end | |
end | |
def self.included(class_or_module) | |
class_or_module.define_singleton_method :const_missing do |table_class_name| | |
table_class_name = table_class_name.to_s | |
if table_class_name =~ /^#{class_or_module.const_get(:TABLE_PREFIX).capitalize}/ | |
first, *others = table_class_name.scan(/[A-Z][a-z]*/) | |
table_name = [first.downcase, others.map(&:upcase)].join.to_sym | |
singleton_method = table_class_name.scan(/[A-Z][a-z]*/).map(&:downcase).join("_").to_sym | |
__uniq_id__ = class_or_module.const_get(:UNIQ_ID) | |
table = Class.new(Sequel::Model(table_name)) | |
table.class_eval{ | |
define_singleton_method singleton_method do |_uniq_id| | |
where(__uniq_id__ => _uniq_id).all | |
end | |
def method_missing(name, *args) | |
column = DB.schema(self.class.table_name).find{|column, info| | |
[column, name].map{|sym| | |
sym.to_s.downcase.split(/_/).join | |
}.inject(&:==) | |
} | |
if column | |
send :[], column.first | |
end | |
end | |
} | |
const_set table_class_name, table | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment