Here’s a handy ruby script that will read the contents of a file
regions.txt
AB Aberdeen
AL St. Albans
B Birmingham
BA Bath
and generating some output (in this case sql) based on the content:
sqlgen.rb
#!/usr/bin/env ruby class SqlGenerator def GenerateInsert file = File.open("regions.txt") contents = "" file.each {|line| tokens = line.split(" ") code = tokens[0] description = tokens[1] # handle descriptions with space if tokens.count > 2 description = tokens[1] + " " + tokens[2] end insertStatement = "INSERT INTO [Province]( [CountryId], [Code], [Description] ) VALUES (3, '#{code}', '#{description}');\n" contents << insertStatement my_file = File.new("inserts.sql", "w") my_file.puts contents } end end if __FILE__ == $0 sql = SqlGenerator.new sql.GenerateInsert end
Run from the command line as:
> ruby sqlgen.rb
Filed under: programming, rails Tagged: ruby, scripting
