Created
February 1, 2013 11:22
-
-
Save todesking/4690748 to your computer and use it in GitHub Desktop.
Customizable STI rule for ActiveRecord
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
# usage: | |
# class User < AR::Base | |
# extend ActiveSTI | |
# define_sti_rule do|record| | |
# if record['parent'] | |
# ChildUser | |
# else | |
# RootUser | |
# end | |
# end | |
# end | |
# | |
# tested with activerecord 3.2.11 | |
module ActiveSTI | |
def instantiate(record) | |
sti_class = find_active_sti_class(record) | |
record_id = sti_class.primary_key && record[sti_class.primary_key] | |
if ActiveRecord::IdentityMap.enabled? && record_id | |
instance = use_identity_map(sti_class, record_id, record) | |
else | |
instance = sti_class.allocate.init_with('attributes' => record) | |
end | |
instance | |
end | |
def find_active_sti_class(record) | |
if @@sti_rule | |
@@sti_rule[record] | |
else | |
find_sti_class(record[inheritance_column]) | |
end | |
end | |
# (record -> sti_class) -> | |
def define_sti_rule(&block) | |
@@sti_rule = block | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment