Created
April 28, 2010 09:30
-
-
Save stonegao/381926 to your computer and use it in GitHub Desktop.
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
| class Remote < ActiveRecord::Base | |
| @abstract_class = true | |
| def self.db_context(db_name, &block) | |
| if block_given? | |
| block.call remote_class(db_name) | |
| else | |
| return remote_class(db_name) | |
| end | |
| end | |
| private | |
| def self.remote_classes | |
| @remote_classes ||= {} | |
| end | |
| # returns proper class from cache or creates new one | |
| def self.remote_class(db_name) | |
| remote_classes[db_name] ||= begin | |
| # creates dynamically descendant Class of self | |
| remote_class = Class.new(self) | |
| remote_class.class_eval { establish_connection db_hash(db_name) } | |
| remote_class | |
| end | |
| end | |
| def self.db_hash(db_name) | |
| # returns db hash for connection to db_name | |
| end | |
| end | |
| class RemoteSomething < Remote | |
| @abstract_class = true | |
| set_table_name "somethings" | |
| # actual model definition | |
| # validations, callbacks etc for Something | |
| end | |
| # usage | |
| # finds all objects in DB db_name | |
| RemoteSomething.db_context(db_name).all | |
| # or with block | |
| RemoteSomething.db_context(db_name) do |klass| | |
| klass.all | |
| klass.first | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment