public
Last active — forked from burke/if.rb

  • Download Gist
if.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
# This isn't necessarily "better", or even "useful" in any way, just sort of fun.
 
class Object
# I like how I can actually create methods with these names.
def if
@__if_result = yield self
self
end
def then
@__if_result ? yield self : self
end
def else
@__if_result ? self : yield self
end
end
 
# code sample from elsewhere.
# http://github.com/nateware/redis-objects/blob/master/ATOMICITY.rdoc
@course = Course.find(1)
if @course.num_students < 30
@course.course_students.create!(:student_id => 101)
@course.num_students += 1
@course.save!
else
# course is full
end
 
# revised version.
Course.find(1).if { |course|
course.num_students < 30
}.then { |course|
course.course_students.create!(:student_id => 101)
course.num_students += 1
}.else { |course|
# Do nothing!
}.save!

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.