How to define private attributes?

Some of my Struct need a way to hold attributes that are not exposed, but that could be used by custom methods. An example:

class Product < Dry::Struct
  attribute :price, Types::Price
  # I don't know if there is something like this
  private_attribute :is_x, Types::Bool

  def x_price
   @is_x ? @price * 2 : @price
  end
end

Product.new(price: 1, is_x: true).respond_to?(:is_x) # => false

What is the recommended approach?

Use plain Ruby:

class Product < Dry::Struct
  attribute :is_x
  private :is_x
end

Hope that helps!
François

1 Like

Thanks a lot @francois: that approach is simpler than my initial ideas.

I’ve created a PR to document it: https://github.com/dry-rb/dry-struct/pull/155