Sha256: b6b9a448724f624c08793b40a7649d789f5cb5e37ce5de5ade82bef2ffba557f

Contents?: true

Size: 1.59 KB

Versions: 23

Compression:

Stored size: 1.59 KB

Contents

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

Version data entries

23 entries across 23 versions & 1 rubygems

Version Path
infopark_fiona7-1.2.0.0.0 lib/fiona7/table_switcher.rb
infopark_fiona7-1.1.0.0.9 lib/fiona7/table_switcher.rb
infopark_fiona7-1.1.0.0.10 lib/fiona7/table_switcher.rb