Enhance Rails' delegate to allow customizing of the value returned when the delegation target is absent

28 views
Skip to first unread message

Bruno Sofiato

unread,
Aug 10, 2017, 5:21:34 AM8/10/17
to Ruby on Rails: Core
Hi guys. 

How do you feel about an enhancement to Rails' delegate method that enables us to define an arbitrary value which is bound to be returned whenever the delegation target is nil

I've came across an use case on which I was required to do so.  What I did was include the on_nil: option to delegate. I can use this new option the value that should be returned. The value can be either a literal or a Proc. When on_nil is not supplied the current behavior is followed (i.e. nil is returned). Here is an example:

class User < ActiveRecord::Base
  has_one :profile 
  delegate :age, to: :profile, allow_nil: true, on_nil: 21
end

User.new.age # 21 

Do you guys think this would be an useful enhancement to Rails' core ?
Best Regards


Roque Pinel

unread,
Aug 10, 2017, 8:01:34 AM8/10/17
to Ruby on Rails: Core

Bruno Sofiato

unread,
Aug 10, 2017, 9:17:47 PM8/10/17
to Ruby on Rails: Core
Yeah. That's pretty much the same features. Well no harm in asking ! Thanks for pointing that out.
Reply all
Reply to author
Forward
0 new messages