Created
September 20, 2011 17:48
-
-
Save potatosalad/1229774 to your computer and use it in GitHub Desktop.
Paste this into a rails console and type "99.bottles.of_beer.on_the_wall.sing!"
This file contains 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
# paste into a rails console | |
# usage: 99.bottles.of_beer.on_the_wall.sing! | |
# alternate: 24.bottles.of_water.on_my_desk.sing! | |
class Bottle < ::ActiveSupport::BasicObject | |
attr_accessor :value, :type, :where | |
def initialize(value, type = nil, where = nil) #:nodoc: | |
@value, @type, @where = value, type, where | |
end | |
def inspect | |
t_string = type.present? ? " of #{type}" : '' | |
w_string = where.present? ? " on #{where}" : '' | |
"#{helper.pluralize(value, 'bottle')}#{t_string}#{w_string}" | |
end | |
alias :to_s :inspect | |
def sing! | |
(1..value).to_a.reverse.each do |n| | |
puts ::Bottle.new(n, type, where) | |
puts ::Bottle.new(n, type) | |
puts "Take one down, pass it around" | |
puts ::Bottle.new(n-1, type, where) unless n == 1 | |
puts '' | |
end | |
t_string = type.present? ? " of #{type}" : '' | |
w_string = where.present? ? " on #{where}" : '' | |
puts "No more bottles#{t_string}#{w_string} :-(" | |
end | |
private | |
def method_missing(method, *args, &block) #:nodoc: | |
if method.to_s =~ /\Aof_(.+)/ | |
::Bottle.new(@value, $1.to_s.gsub(/_/, ' '), @where) | |
elsif method.to_s =~ /\Aon_(.+)/ | |
::Bottle.new(@value, @type, $1.to_s.gsub(/_/, ' ')) | |
else | |
value.send(method, *args, &block) | |
end | |
end | |
end | |
class Numeric | |
def bottles | |
::Bottle.new(self) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment