Last active
December 20, 2015 15:58
-
-
Save leandro/6157737 to your computer and use it in GitHub Desktop.
Rails Model's table info generator (indexes included)
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
| def table_info(model) | |
| puts "# Table name: #{model.table_name}", "#", "# Columns:" | |
| cols = model.columns.inject([]) {|arr, e| arr << [e.name || '-', e.type || '-', e.sql_type || '-', e.limit || '-', e.default || '-'].map(&:to_s)} | |
| col_sizes = cols.inject([]) {|arr, c| arr << c.map {|e| e.size }} | |
| max_sizes = 4.times.inject([]) {|arr, i| arr << col_sizes.max_by {|e| e[i] }[i] } | |
| cols.each { |c| puts "# #{c[0].ljust(max_sizes[0] + 2)}:#{c[1].ljust(max_sizes[1] + 3)}#{c[2].ljust(max_sizes[2] + 2)}#{c[3].ljust(max_sizes[3] + 2)}#{c[4]}" } | |
| puts "#", "# Indexes:" | |
| indexes = ActiveRecord::Base.connection.indexes(model.table_name).map {|e| [e.name, "(#{e.columns.join(", ")})"]} | |
| max_size = indexes.map {|e| e.first.size}.max | |
| indexes.each { |c| puts "# #{c[0].ljust(max_size + 2)}#{c[1]}" } | |
| puts "#" | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment