This project is archived and is in readonly mode.
ActiveSupport: alternative Block execution on empty Enumerable
Reported by Paul | February 12th, 2009 @ 10:21 AM | in 2.x
i did not find an easy way to specify an alternative action when an iterator had nothing to iterate over.
i am using this for now:
module Enumerable def else(&block)
self.respond_to?('empty?') && self.empty? ? yield : self
end
end
in color :) http://blog.sponagl.de/2009/1/23...
maybe this is usable in general...
Comments and changes to this ticket
-
Pratik August 5th, 2009 @ 02:42 PM
- State changed from new to wontfix
This looks interesting. But I'm not sure if this pattern belongs to the core or not. You should probably spark a discussion in the core ML - http://groups.google.com/group/rubyonrails-core
Thanks.
-
Luca Guidi August 6th, 2009 @ 02:32 PM
Attached a patch for a more efficient implementation: http://gist.github.com/163274
-
Eloy Duran August 6th, 2009 @ 02:49 PM
@Luca: In the docs you miss the 'do' keyword: “end.else” => “end.else do”. Besides that; verified and I like it! +1
-
Luca Guidi August 6th, 2009 @ 03:02 PM
Thanks Eloy, I just fixed the rdoc issue and added a couple of test cases.
-
blatyo August 7th, 2009 @ 02:23 PM
I could definitely see myself using something like this. I would definitely change the name from else though. It's bad practice to use keywords as method names and else provides no context when used by itself. +1 (with some changes)
-
Paul August 7th, 2009 @ 03:24 PM
i do not think the use of else is bad within this context. it reads nice:
with.each do this end.else do that end
using it "standalone" does not make much sense i.m.O.
elements.else do
... endan
if elememts.blank?
... endis and will be better - regardless of the naming of the method...
Create your profile
Help contribute to this project by taking a few moments to create your personal profile. Create your profile »
<h2 style="font-size: 14px">Tickets have moved to Github</h2>
The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>