Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a method/property is defined or not before calling

I am a newbie to RoR. I am trying to figure out how to check if a property is defined or not in the environment file(development.rb in this case).

We have a property defined in development.rb file, something like:

config.user = 'test-user'

Now in the code, I use it by calling:

 Rails.application.config.user

which gives me the required value.

But the problem is this configuration may be disabled sometimes. So, I want to check if this property is defined or not before assigning it. Something like

user_name = (if Rails.application.config.user is available)? 
             Rails.application.config.user : 'some_other_value'

I tried defined? and respond_to but did not work.

Any help/suggestions are appreciated. Thanks!

like image 429
Sravan Kumar Avatar asked Sep 07 '25 18:09

Sravan Kumar


1 Answers

If you are using rails (it comes from active_support actually) every object will have a try method which also does what you want:

user_name = Rails.application.config.try(:user)

And ruby 2.3 brought us &.:

user_name = Rails.application.config&.user

Note that in both cases you can use the return value implicitly if nil should not be a valid user_name (because try and &. will return nil if config does not respond to user):

user_name = Rails.application.config&.user || 'Guest' # ruby >= 2.3.0
user_name = Rails.application.config.try(:user) || 'Guest'

If you are calling that piece of code more than twice (my rule of thumb), you should consider extracting it into an own method, e.g. Application#user_name.

Correction

In afterthought, I figured that &. will probably not work as expected here, because config is probably not nil. It really depends on the setting (is user configured, but empty? How is config implemented?). I keep that part of the answer though because it might be of interest for related problems (but remember: you'll need ruby 2.3 or later).

like image 96
Felix Avatar answered Sep 10 '25 06:09

Felix