Since ActiveSupport already has #blank?, you can easily give yourself
a #nonblank? The symmetry with the Numeric#nonzero? is nice.
-Rob
class String
# Allowing a chain like: string_value.nonblank? || 'default value'
def nonblank?
self unless blank?
end
end
class NilClass
# Allowing a chain like: value.nonblank? || 'default value'
def nonblank?
self
end
# so it plays nicely with Numeric#nonzero?
def nonzero?
self
end
end
On Jan 28, 2009, at 1:04 AM, Mike Gaffney wrote:
>
> ifempty?
>
> Pascal Ehlert wrote:
>> Hi,
>>
>> How about adding some method #foo instead that returns nil if the
>> string is blank and self otherwise, so that you can do:
>>
>> self.email.foo || self.name
>>
>> This looks slightly better and more intuitive to me, if we can figure
>> out a descriptive name for the #foo method (I can’t think of any atm,
>> admittedly).
>>
>>
>> Cheers
>>
>> Pascal
>>
>>
>> On 1/28/09 6:45 AM, "Ryan Angilly" <[email protected]> wrote:
>>
>> Hey guys,
>>
>> I find myself doing stuff like this a lot:
>>
>> self.email.blank? ? self.name <http://self.name> : self.email
>>
>>
>> Anyone feel like adding an 'or' method to nil and String (a la
>> blank?) so that this will work:
>>
>>
>> self.email.or(self.name <http://self.name> )
>>
>>
>> It would be as simple as adding this file to ActiveSupport
>>
>>
>> activesupport/lib/core_ext/or.rb
>>
>> class String
>> def or(val)
>> self == "" ? val : self
>> end
>> end
>>
>> class NilClass
>> def or(val)
>> val
>> end
>> end
>>
>>
>> I'll submit a patch of this + tests to LH if people are
>> interested.
>>
>>>
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby
on Rails: Core" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/rubyonrails-core?hl=en
-~----------~----~----~----~------~----~------~--~---