We are using smart_properties (through the gem active_operation) in our legacy Ruby on Rails application. This app uses an older version of Ruby, 2.2.3. Unfortunately, it is not a possibility to upgrade to Ruby 2.4.
An error TypeError: can't dup Symbol was being triggered because when initializing a property, the default attribute is a initialized with a Symbol in active_operation (like you can see at this line here).
Until I believe Ruby v2.4, Symbols cannot be duplicated which throws this type error. On more recent applications, this error obviously does not get triggered.
This is not only true for Symbols, but also applies to NilClass, True/FalseClass, Numeric, BigDecimal, and Method.
Solution
If the property's default attribute is a Symbol, return it, don't dup it.
The behaviour will not change if default is a proc and supports dup.
Rails gives the duplicable? method for free to check if the object can be dup'ed. If this is defined (ie: if we are using Rails), we check if the object can be duplicated and we duplicate it. If duplicable? is not defined, then we return default.dup
The goal here is to preserve the exact behaviour just by adding some protection for those who want to use this gem with older versions of Ruby (on Rails).
Alternatives
Instead of writing @default && @default.dup, we wanted to write @default&.dup but the safe navigation operator is not available until Ruby 2.3 either.
Background
We are using smart_properties (through the gem
active_operation
) in our legacy Ruby on Rails application. This app uses an older version of Ruby,2.2.3
. Unfortunately, it is not a possibility to upgrade to Ruby 2.4.An error
TypeError: can't dup Symbol
was being triggered because when initializing a property, thedefault
attribute is a initialized with aSymbol
inactive_operation
(like you can see at this line here).Until I believe Ruby v2.4,
Symbol
s cannot be duplicated which throws this type error. On more recent applications, this error obviously does not get triggered.This is not only true for Symbols, but also applies to
NilClass
,True/FalseClass
,Numeric
,BigDecimal
, andMethod
.Solution
If the property's
default
attribute is a Symbol, return it, don'tdup
it. The behaviour will not change ifdefault
is a proc and supportsdup
.Rails gives the
duplicable?
method for free to check if the object can bedup
'ed. If this is defined (ie: if we are using Rails), we check if the object can be duplicated and we duplicate it. Ifduplicable?
is not defined, then we returndefault.dup
The goal here is to preserve the exact behaviour just by adding some protection for those who want to use this gem with older versions of Ruby (on Rails).
Alternatives
Instead of writing
@default && @default.dup
, we wanted to write@default&.dup
but the safe navigation operator is not available until Ruby 2.3 either.Quality code checking