Created
March 26, 2014 09:59
-
-
Save rummelonp/9780005 to your computer and use it in GitHub Desktop.
ActiveRecord で水平分割されてるの楽に扱うやつ
This file contains hidden or 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 HorizontalSplitNyan | |
def self.const_missing(const_name) | |
klass = Class.new(ActiveRecord::Base) | |
klass.table_name = "horizontal_split_nyans_#{const_name.to_s.downcase}" | |
const_set(const_name, klass) | |
end | |
def self.build(&block) | |
relations = table_classes.map { |c| c.instance_eval(&block) } | |
sql = relations.map { |r| r.to_sql }.join(' UNION ') | |
table_classes.first.from("(#{sql}) #{table_classes.first.table_name}") | |
end | |
def self.method_missing(method_name, *args, &block) | |
build { send(method_name, *args) } | |
end | |
def self.tables | |
tables = ActiveRecord::Base.connection.tables.select { |t| t =~ /\Ahorizontal_split_nyans_p\d{6}/ } | |
end | |
def self.table_classes | |
tables.map do |t| | |
_, year, month = *t.match(/horizontal_split_nyans_p(\d{4})(\d{2})/) | |
split_post_class = SplitPost.const_get("P#{year}#{month}") | |
end | |
end | |
end |
Author
rummelonp
commented
Mar 26, 2014
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment