Last active
April 3, 2020 18:04
-
-
Save lujanfernaud/0d00e252a8feacf095fa4dc734246776 to your computer and use it in GitHub Desktop.
Rails: Tables Finder
This file contains 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
# Example: | |
# | |
# > TablesFinder.call(column_name: 'site_id') | |
# => ['events', 'users'] | |
class TablesFinder | |
VALID_ATTRIBUTES = %w[ | |
COLUMN_NAME | |
].freeze | |
def self.call(args) | |
new(args).call | |
end | |
def initialize(args) | |
@matcher_attribute = args.keys.first.to_s.upcase | |
@matcher_value = args.values.first.to_s.downcase | |
end | |
def call | |
return [] unless [matcher_attribute, matcher_value].all? | |
return [] unless matcher_attribute.in?(VALID_ATTRIBUTES) | |
find_tables | |
end | |
private | |
attr_reader :matcher_attribute, :matcher_value | |
def find_tables | |
ActiveRecord::Base.connection.execute( | |
"SELECT table_name FROM INFORMATION_SCHEMA.COLUMNS | |
WHERE #{matcher_attribute} = '#{matcher_value}' | |
ORDER BY TABLE_NAME" | |
).values.flatten | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment