t6d / smart_properties

Ruby accessors on steroids
MIT License
177 stars 20 forks source link

Patch for dup Symbols (Ruby 2.2.3) #71

Closed thedrummeraki closed 3 years ago

thedrummeraki commented 5 years ago

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, 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.

Quality code checking

thedrummeraki commented 5 years ago

Hi, I was wondering if I could get some input on this PR please. @t6d