Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@kirkelifson
Created January 28, 2016 19:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kirkelifson/d9ea5588f6b72f82719f to your computer and use it in GitHub Desktop.
Save kirkelifson/d9ea5588f6b72f82719f to your computer and use it in GitHub Desktop.
Generates a list of params straight from the database schema
#!/usr/bin/env ruby
# Usage: generate_params.rb [/path/to/db/schema.rb] [table name]
# By: Kirk Elifson <kirk [at] parodybit [dot] net>
def print_usage
puts "", "\tUsage: ruby generate_params.rb /path/to/db/schema.rb table_name", ""
exit
end
print_usage if ARGV.length != 2
full_path = ARGV.shift
table_name = ARGV.shift
begin
schema = File.open(full_path, 'r')
rescue Errno::ENOENT => e
puts "Failure to open file '#{full_path}'"
puts "Please provide the full path to schema.rb (e.g., /path/to/myblog/db/schema.rb)"
print_usage
end
begin
schema_content = schema.read
table_start = schema_content.index("create_table \"#{table_name}\"")
table_end = schema_content[table_start..-1].index("end") - 3 # Remove end line
lines = schema_content[table_start..(table_start + table_end)].split("\n").map(&:strip)
lines.shift # Remove create_table line
rescue => e
puts "Not a valid table name."
exit
end
columns = []
lines.each do |line|
next if line.include?("\"created_at\"") || line.include?("\"updated_at\"") # Timestamps are not params
line.gsub(/t.[a-z]+[\s]+"([a-zA-Z0-9_-]+)"/) {
columns << Regexp.last_match[1]
}
end
columns.sort.each { |column| puts ":#{column}" }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment