Created
February 24, 2021 09:49
-
-
Save patorash/7b4559e12bf3a73ef3ff769ed99b4c89 to your computer and use it in GitHub Desktop.
Add column comment from ActiveRecord::Enum. with enum_help gem.
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 AddColumnCommentFromEnum < ActiveRecord::Migration[6.0] | |
def up | |
table_with_columns.each do |table_name, columns| | |
next unless I18n.exists?("enums.#{table_name.singularize}") | |
columns.map(&:name).each do |column_name| | |
next unless I18n.exists?("enums.#{table_name.singularize}.#{column_name}") | |
model = table_name.classify.constantize | |
enums = model.send(column_name.pluralize) | |
enums_i18n = enums.map { |k, v| [model.send("#{column_name.pluralize}_i18n")[k], v] } | |
change_column_comment( | |
table_name, | |
column_name, | |
"#{I18n.t("activerecord.attributes.#{table_name.singularize}.#{column_name}")}:#{enums_i18n.to_h.invert.to_s}", | |
) | |
end | |
end | |
end | |
def down | |
table_with_columns.each do |table_name, columns| | |
next unless I18n.exists?("enums.#{table_name.singularize}") | |
columns.map(&:name).each do |column_name| | |
next unless I18n.exists?("enums.#{table_name.singularize}.#{column_name}") | |
change_column_comment( | |
table_name, | |
column_name, | |
I18n.t("activerecord.attributes.#{table_name.singularize}.#{column_name}"), | |
) | |
end | |
end | |
end | |
private | |
def table_with_columns | |
system_view_names = %w( | |
pg_stat_statements | |
geography_columns | |
geometry_columns | |
raster_columns | |
raster_overviews | |
) | |
tables = ApplicationRecord.connection.tables | |
views = ApplicationRecord.connection.views - system_view_names | |
(tables + views).each_with_object({}) { |table, hash| hash[table] = ApplicationRecord.connection.columns(table) } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment