Module: DbCharmer::Sharding::Method::SchemaTableNamePrefix

Defined in:
lib/db_charmer/sharding/method/db_block_schema_map.rb

Overview

To be mixed in AR#base. Allows a schema name to be set at the same time a db connection is selected.

Instance Method Summary collapse

Instance Method Details

#orig_table_nameObject



196
197
198
199
200
201
202
203
204
205
206
207
208
# File 'lib/db_charmer/sharding/method/db_block_schema_map.rb', line 196

def orig_table_name
  # Polymorphic active record classes won't have orig_table_name defined and we'll add double prefixes without this logic, because table_name
  # usees parent class tables
  if self.superclass && self.superclass.respond_to?(:orig_table_name) && self.superclass.orig_table_name
    self.superclass.orig_table_name
  elsif self == ::ActiveRecord::Base
    nil
  elsif @orig_table_name
    @orig_table_name 
  else
    self.table_name
  end
end

#reset_cached_table_name(orig_table_name) ⇒ Object

Rails memoizes table_name and table_name_prefix at the time the models are loaded. This method forces refreshing those names



212
213
214
215
216
# File 'lib/db_charmer/sharding/method/db_block_schema_map.rb', line 212

def reset_cached_table_name(orig_table_name)
  self.table_name = "#{full_table_name_prefix}#{orig_table_name}#{table_name_suffix}"
  @arel_table = nil
  @relation = nil
end

#set_schema_table_name_prefix(con) ⇒ Object



164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
# File 'lib/db_charmer/sharding/method/db_block_schema_map.rb', line 164

def set_schema_table_name_prefix(con)
  
  #Rails.logger.debug "set_schema_table_name_prefix: self=#{self} @dbcharmer_table_name_prefix=#{@dbcharmer_table_name_prefix}"
  if con.is_a?(Hash) && con[:schema_name]
    new_prefix = con[:schema_name] + '.'
    if @orig_table_name.blank? && self.to_s != "ActiveRecord::Base"
      @orig_table_name = orig_table_name
    end
  else
    new_prefix = '' if self.to_s=='ActiveRecord::Base' # this is for migrations
  end

  # Set the new table_name_prefix
  if new_prefix && @dbcharmer_table_name_prefix != new_prefix
    # remove the old dbcharmer prefix first
    if !@dbcharmer_table_name_prefix.blank?
      self.table_name_prefix = self.table_name_prefix.gsub(/#{Regexp.escape(@dbcharmer_table_name_prefix)}/, '')
    end

    @dbcharmer_table_name_prefix = new_prefix
    self.table_name_prefix = new_prefix

    # Reset all forms of table_name that were memoized in Rails.
    # Don't do it in the context of migrations where the current class
    # is AR::Base and there is no actual table name.
    unless self.to_s=='ActiveRecord::Base'
      #Rails.logger.debug "set_schema_table_name_prefix: resetting"
      reset_cached_table_name(orig_table_name)
    end
  end
end