Data.define is introduced by Zverok in Ruby 3.2.

This is really amazing and desired by most Rubyists. However, regardless to say, the function is not available in Ruby 2.7-3.1 applications. Some users (including me), at this moment, still uses older versions of Ruby with struggling to upgrade large Rails applications.

data_class_factory

I developed a backport of Data.define for Ruby 2.7, 3.0, 3.1.
https://rubygems.org/gems/data_class_factory

require 'data_class_factory'

Point = Data.define(:x, :y) do
  def norm
    Math.sqrt(x * x + y * y)
  end
end

p1 = Point.new(x: 3, y: 4)
p2 = Point.new(x: 3, y: 4)

p1 == p2 # => true
p1.norm # => 5
Enter fullscreen mode Exit fullscreen mode

It covers most of the spec of original Data class introduced in Ruby 3.2.
https://github.com/YusukeIwaki/data_class_factory/blob/0.1.0/test/data_test.rb

Feedback is really welcome :)

I personally use this library on my Rails apps. So try this lib for your app, and let me know issues and feel free to feedback.
https://github.com/YusukeIwaki/data_class_factory/issues