Guest User

Untitled

a guest
Oct 18th, 2018
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.53 KB | None | 0 0
  1. # Finds all column that reference a certain model name via a polymorphic association.
  2. # This is helpful when renaming a table, because if you don't update the model names
  3. # in these polymorphic belongs_to associations they will break.
  4. class PolymorphicBelongsToFinder
  5. POLYMORPHIC_COLUMN_MATCH = /_type\Z/.freeze
  6.  
  7. def initialize(old_model_name)
  8. @old_model_name = old_model_name
  9. end
  10.  
  11. # Columns that reference the old model
  12. def problematic_columns
  13. problem_cols = []
  14.  
  15. all_models.select do |model|
  16. polymorphic_columns_for(model).each do |col|
  17. if model.pluck(col).include?(old_model_name)
  18. problem_cols << model.column_for_attribute(col)
  19. end
  20. end
  21. end
  22.  
  23. problem_cols
  24. end
  25.  
  26. def print_report
  27. cols = problematic_columns
  28.  
  29. if cols.any?
  30. puts "#{cols.count} polyorphic association(s) to #{old_model_name} were found"
  31.  
  32. cols.each do |col|
  33. puts "#{col.table_name}.#{col.name} references #{old_model_name}"
  34. end
  35. else
  36. puts "No polyorphic associations to #{old_model_name} were found"
  37. end
  38.  
  39. nil
  40. end
  41.  
  42. private
  43.  
  44. attr_reader :old_model_name
  45.  
  46. def all_models
  47. (ApplicationRecord.subclasses | ActiveRecord::Base.subclasses).reject(&:abstract_class)
  48. end
  49.  
  50. def polymorphic_columns_for(model)
  51. # Really just columns who's name matches polymorphic belongs_to naming
  52. # TODO: improve this to detect non-standard naming
  53. model.column_names.grep(POLYMORPHIC_COLUMN_MATCH)
  54. end
  55. end
  56.  
  57. # Example:
  58. # PolymorphicBelongsToFinder.new('OldModelName').print_report
Add Comment
Please, Sign In to add comment