Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails "try" a constant

I am loading serializers by building the namespace and name of them and using constantize.

If the serializer doesn't exist then this will throw the uninitialized constant error.

Is there any way I can try the constant or actively check that the serializer exists before converting the name to a constant?

like image 825
Cjmarkham Avatar asked Dec 02 '25 04:12

Cjmarkham


1 Answers

You can use Object.const_defined?:

'Serializer'.constantize if Object.const_defined?('Serializer')

Alternatively you can also use the Ruby method Object.const_get instead the Rails one:

Object.const_get('Serializer')
like image 141
Rafa Paez Avatar answered Dec 03 '25 16:12

Rafa Paez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!