QuickGraph
Requirements: none
Type: library
A Ruby library that can build simple, easy to use html bar graphs.
Requirements: none
Type: library
A Ruby library that can build simple, easy to use html bar graphs.
LightsoutRLightsoutR
Requirements: none
Type: terminal game
A Ruby version of the LightsOut game in the games. This was the very first program I wrote in Ruby, so it's circa January 2005.
Requirements: none
Type: terminal game
A Ruby version of the LightsOut game in the games. This was the very first program I wrote in Ruby, so it's circa January 2005.
class Lights
attr_accessor :coord, :score
attr_reader :coord_map
# clear screen and display quit thing
def initialize
@coord = []
@score = 0
@coord_map = [*(1..5)]
self.clear_screen
self.build_grid
print "\t\t" + ("=" * 55) + "\n"
print "\t\t" + "RUBY LIGHTSOUT".center(55) + "\n"
print "\t\t" + ("=" * 55) + "\n\n\n"
puts "\t\t(press \"q\" at any time during the game to quit)"
self.menu(0)
self.reload
end
# setup grid of coords
def build_grid
@coord_map.each do |x|
@coord[x] = []
@coord_map.each do |y|
@coord[x][y] = " "
end
end
end
# draw grid on screen
def draw
print "\t\t Y 1 | 2| 3| 4| 5 \n"
print "\t\tX\n"
print "\t\t-- --+--+--+--+--\n"
print "\t\t1 #{@coord[1][1]}|#{@coord[1][2]}|#{@coord[1][3]}|#{@coord[1][4]}|#{@coord[1][5]}\n"
print "\t\t-- --+--+--+--+--\n"
print "\t\t2 #{@coord[2][1]}|#{@coord[2][2]}|#{@coord[2][3]}|#{@coord[2][4]}|#{@coord[2][5]}\n"
print "\t\t-- --+--+--+--+--\n"
print "\t\t3 #{@coord[3][1]}|#{@coord[3][2]}|#{@coord[3][3]}|#{@coord[3][4]}|#{@coord[3][5]}\n"
print "\t\t-- --+--+--+--+--\n"
print "\t\t4 #{@coord[4][1]}|#{@coord[4][2]}|#{@coord[4][3]}|#{@coord[4][4]}|#{@coord[4][5]}\n"
print "\t\t-- --+--+--+--+--\n"
end
# reset game and randomize lights
def reload
@coord_map.each do |x|
@coord_map.each do |y|
# get random number and fill grid based on results
if rand(2).eql?(1)
@coord[x][y] = "XX"
else
@coord[x][y] = " "
end
end
end
end
# perform menu actions
def menu_select
print "What would you like to do?\n> "
choice = gets.chomp
self.menu(choice)
end
# perform menu selections
def menu(select)
case select
# player wants to play game, clear screen and reload grid
when "1"
self.clear_screen
self.reload
@score = 0
self.mainloop
# clear screen and display help file
when "2"
self.clear_screen
print "\n\n\t\t=====================================================\n"
print "\t\t HELP\n"
print "\t\t=====================================================\n"
print "\t\tThe main point of this game is to shut off all of the\n"
print "\t\tlights. Lights that are on are marked by a blank space\n"
print "\t\tand lights that are turned off are marked by an \"XX\".\n"
print "\t\tEvery time you specify a light to toggle, that light's\n"
print "\t\tneighboring 4 rooms will be toggled as well. Try to get\n"
print "\t\tall of the lights on or off in as few moves as possible.\n"
print "\t\t~~~~~~~~~~~~~~~~~~~~| Good luck! |~~~~~~~~~~~~~~~~~~~~"
self.menu(0)
self.menu_select
# clear screen and display about author page
when "3"
self.clear_screen
print "\n\n\t\tRuby implementation of LightsOut, by Nicholas Wright.\n\t\t\tOriginal idea unknown.\n"
self.menu(0)
self.menu_select
# allow player to quit game
when "4", /q/i
self.clear_screen
print "\t\tGood bye! Thanks for playing, hope to see you again soon. =)\n\n"
exit
# display menu
else
self.clear_screen if (select != 0)
print "\n\n\t\t" + ("=" * 55) + "\n"
print "\t\t" + "MENU".center(55) + "\n"
print "\t\t" + ("=" * 55) + "\n"
print "\t\t1. Play LightsOut\n";
print "\t\t2. Instructions\n";
print "\t\t3. About\n";
print "\t\t4. Quit\n";
self.menu_select
end
end
# check grid for winner
def check_grid
taken = 0
# run a loop to check x coords in the grid
@coord_map.each do |x|
# run another loop to check the y coords in the grid
@coord_map.each do |y|
# check if light is on
if @coord[x][y].eql?(" ")
taken += 1
end
end
# determine type of winner based on above
return 1 if taken.eql?(25) # all lights out, stop game
return 2 if taken.zero? # all lights on, stop game
return 0
end
end
# toggle light on or off based on the player's input
def toggle(i, j)
if @coord[i][j].eql?(" ")
@coord[i][j] = "XX"
else
@coord[i][j] = " "
end
end
# toggle neighboring lights on or off
def toggle_neighbors(i, j)
self.toggle((i - 1), j) if ((i - 1) > 0)
self.toggle((i + 1), j) if ((i + 1) < 6)
self.toggle(i, (j - 1)) if ((j - 1) > 0)
self.toggle(i, (j + 1)) if ((j + 1) < 6)
end
# allow player to move
def move(select)
self.clear_screen
if (select =~ /q/i)
self.menu(4)
else
# depending on input, we allow them to move or give an error message
case select
# make sure syntax is x,y within required fields
when /^[1-5],[1-5]$/;
result = select.split(',')
self.toggle(result[0].to_i,result[1].to_i)
self.toggle_neighbors(result[0].to_i, result[1].to_i)
@score += 1
# check if input isn't within required fields, display error
when /^[^1-5],[^1-5]$/;
print "\nInvalid move, coords must appear on grid.\n\n"
# user didn't follow x,y syntax, display error
else;
print "\nInvalid move, please use x,y syntax to label coords.\n\n"
end
end
end
# announce winners
def winner
if self.check_grid.zero?
outcome = game.check_grid.eql?(2) ? "on" : "off"
self.clear_screen
self.draw
plural = @score.eql?(1) ? "" : "s";
print "Congratulations! You managed to turn every light #{outcome} in only #{@score.to_s} move#{plural}!"
self.menu(0)
else
print "Hopefully next time you'll complete the game!\n\n"
end
end
# clear screen to clean up look of game
def clear_screen
print (RUBY_PLATFORM !~ /mswin/i) ? `clear` : `cls`
end
# mainloop to run game
def mainloop
# begin game loop until user decides to quit
while self.check_grid.zero?
self.draw
plural = @score.eql?(1) ? "" : "s"
print "#{@score.to_s} move#{plural} so far\n"
print "Which light light do you want to effect? (X,Y)\n> "
choice = gets.chomp
self.move(choice)
end
end
# play the game!
def play
self.menu(0)
self.winner
end
end
# initialize game
game = Lights.new
game.play
Tooltips
Requirements: Prototype
Type: library
Provides customizable and simple to use javascript tooltips.
Requirements: Prototype
Type: library
Provides customizable and simple to use javascript tooltips.
RailsToDjangoRailsToDjango
Requirements: A schema.rb file
Type: single use
A Ruby script that generates default models for the Django web framework from a Rails schema.rb file. This was created with the intent to stuff Django admin interfaces on all of my Rails applications.
Requirements: A schema.rb file
Type: single use
A Ruby script that generates default models for the Django web framework from a Rails schema.rb file. This was created with the intent to stuff Django admin interfaces on all of my Rails applications.
#!/usr/local/bin/ruby
def tablize(word)
a = word.split(/_/).map {|l| l.capitalize}.join("")
a[-1].chr[/s/i] ? a[0..-2] : a
end
def args_mapper(args)
@float = nil
hash = args.split(/,\s+/).inject({}) do |hsh, cur|
key, value = cur.split(" => ")
key.strip!
key = key[/^:/] ? key[1..-1] : key
value = value.capitalize if ["true", "false"].include?(value)
@float = true if key.eql?("default") and value[/^\d+\.\d+$/] and @float.nil?
case key
when "limit"
hsh["maxlength"] = value
else
hsh[key] = value unless value.empty?
end
hsh
end
if @float
hash["max_digits"] = hash.delete("maxlength")
hash["decimal_places"] = 2
end
hash
end
def column_mapper(column)
case column
when "string"
column = "Char"
when "datetime"
column = "DateTime"
else
column = tablize(column)
end
column + "Field"
end
def mapper(line)
line.scan(/t.column\s+"(\w+)".*?:(\w+),?(.*)/) do |column, column_type, args|
if fk = column[/(\w+)_id/, 1]
return [fk, "ForeignKey", "'%s'" % tablize(fk)]
end
return [column, column_mapper(column_type), args_mapper(args)]
end
end
schema = IO.read("schema.rb")
django = ["from django.db import models", "import datetime"]
schema.scan(/create_table\s(.*?)end/m).flatten.each do |chunk|
chunk.scan(/(\w+)",\s:force\s=>\strue\sdo\s\|t\|\n(.*)$/m).each do |table, data|
django << "class %s(models.Model):" % tablize(table)
data.chomp.split("\n").each do |line|
column, column_type, args = mapper(line)
args["maxlength"] = 255 if column_type.eql?("CharField") and args["maxlength"].nil?
unless column.nil? or column_type.nil? or args.nil?
@first = column if @first.nil? and not column_type.eql?("ForeignKey")
args = args.is_a?(Hash) ? args.map {|k, v| "%s=%s" % [k, v]}.join(", ") : args
django << " %s = models.%s(%s)" % [column, column_type, args]
end
end
django << " class Meta:"
django << " db_table = '%s'" % table
django << " class Admin:"
django << " pass"
unless @first.nil?
django << " def __str__(self):"
django << " return self.%s" % @first
end
end
django << "\n\n"
@first = nil
end
open("django.txt", "w+") do |file|
file.write(django.join("\n"))
end
LoadAllFixturesLoadAllFixtures
Requirements: Fixtures
Type: single use
A single use Ruby script that loads all fixtures into the database. This was created for use in irb to give myself some junk data for developing.
Requirements: Fixtures
Type: single use
A single use Ruby script that loads all fixtures into the database. This was created for use in irb to give myself some junk data for developing.
Dir["test/fixtures/*.yml"].each do |file|
next if File.directory?(file)
YAML::load(IO.read(file)).each do |name, hash|
begin
(table = file[/(\w+)\.yml/, 1]).classify.constantize.send(:create, hash.inject({}) {|hash, value|
hash[value.first] = ERB.new(value.last.to_s).result
hash
})
rescue # not all tables have models
begin
ActiveRecord::Base.connection.execute("insert into %s set %s" % [table, hash.map {|a, b|
"%s='%s'" % [a, ERB.new(b.to_s).result]
}.join(",")])
rescue ActiveRecord::StatementInvalid
print "F"
end
end
print "."
end
end
ReplaceAllEmailsInDevelopmentDataReplaceAllEmailsInDevelopmentData
Requirements: none
Type: single use
Single use Ruby script to update all columns in the database that should contain emails, with the provided email. This script was originally written to add my email address in place of the junk email addresses that were loaded from fixtures via the script above.
Requirements: none
Type: single use
Single use Ruby script to update all columns in the database that should contain emails, with the provided email. This script was originally written to add my email address in place of the junk email addresses that were loaded from fixtures via the script above.
email = "you@devemail.com"
ActiveRecord::Base.connection.tables.each do |table|
begin
klass = table.classify.constantize
if records = klass.column_names.grep(/email/) and not records.blank?
klass.update_all records.map {|column| break if column[/_id$/]; "%s='%s'" % [column, email]}.join(" and ")
puts "updated %s" % table
next
end
rescue; end
puts "skipped %s" % table
end