Skip to content

Instantly share code, notes, and snippets.

@FiXato
Created December 8, 2009 12:52
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 FiXato/251606 to your computer and use it in GitHub Desktop.
Save FiXato/251606 to your computer and use it in GitHub Desktop.
Holiday Greetings
require 'yaml'
class Array
def random
self[Kernel.rand(size)]
end
end
class Hash
def random
self[self.keys.random]
end
end
class Greetings
attr_accessor :greetings, :source
def initialize(source='christmas.yaml')
@source = source
@greetings = {:by_cctld => {},:by_lang => {}}
@greetings = YAML.load_file(source) if File.exist?(source)
end
def save
File.open(source, 'w') do |fp|
YAML.dump(greetings, fp)
end
nil
end
def add_greeting(greeting)
greeting.cctlds.each do |countrycode|
@greetings[:by_cctld][countrycode] = [@greetings[:by_cctld][countrycode], greeting].flatten.compact.uniq
end
@greetings[:by_lang][greeting.lang] = [@greetings[:by_lang][greeting.lang], greeting].flatten.compact.uniq
nil
end
def random(key=nil)
if key.kind_of?(String)
greetings = @greetings[:by_lang][key]
elsif key.kind_of?(Symbol)
greetings = @greetings[:by_cctld][key]
else
greetings = @greetings[:by_cctld].random
end
return greetings.random if greetings
nil
end
end
class Greeting
attr_accessor :lang, :cctlds, :greetings
def initialize(lang,cctlds,greeting)
@lang = lang.to_s.capitalize
@cctlds = cctlds.map{|cctld| cctld.to_sym}
@greeting = greeting
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment