module Fiona7 class TableSwitcher attr_accessor :klass, :table_suffix, :table_prefix, :table_name def initialize(klass, table_suffix) self.klass = klass self.table_prefix = klass.table_name_prefix self.table_suffix = table_suffix self.table_name = "#{self.table_prefix}#{self.table_suffix}" end def switch if klass.table_name != self.table_name value = self.table_name klass_name = klass.name Rails.logger.debug "Switching table name to #{value} on #{self.klass.name}" # TODO: cache values for two modes somehow? (to improve performance) # NOTE: we abuse the fact that the two tables have identical schemes # and only swap out the table name sneakly, skipping DB schema lookup # and also reloading of attributes, which can break the app # (by removing primary key accessor :id) klass.instance_eval do connection.clear_cache! @table_name = value @quoted_table_name = nil @arel_table = nil @sequence_name = nil unless defined?(@explicit_sequence_name) && @explicit_sequence_name @relation = ActiveRecord::Relation.create(self, arel_table) if self == Fiona7::WriteObj # reset associations, otherwise they go out of sync has_many :children, :class_name => 'RailsConnector::AbstractObj', :foreign_key => 'parent_obj_id' belongs_to :parent, :class_name => 'RailsConnector::AbstractObj', :foreign_key => 'parent_obj_id' end end end end end end