1

I am trying to override Solidus code and wanted to know what my options were?

In particular I am trying to change the Address to make the phone optional.

notapatch
  • 6,569
  • 6
  • 41
  • 45

1 Answers1

2

Solidus aims to provide a better customization interface - they want to avoid you opening up the Solidus/Spree classes - because it increases the chances that you break the system.

The original answer was broken for Rails 6.0 (Zeitwerk changes). For Rails 6 there is untested example code taken from a github issue.

# app/decorators/your_app/spree/address/make_phone_optional_decorator.rb
module YourApp::Spree::Address::MakePhoneOptionalDecorator
  def require_phone?
    false
  end

  Spree::Address.prepend self
end

Be sure to name the files *_decorator.rb, like this they will automatically been picked up by solidus.


Original answer:

Alternatives listed from most to least preferred

  1. To this end they provide extension points
  2. Decorators
    • which doesn't help us because the address acts within Solidus library and not code called within our application
  3. Module#prepend
    • Create a file under app/models/spree and prepending additional spree namespaces if required
    • Add the prepend into config/initializers/spree.rb
    • Prepend is an improvement on class_eval as you can call the non-overridden version of a method call with super.

In the actual problem - there is no extension for a Spree Address, a decorator won't work because we are not calling the code (say in a view we have written), so we need to change the Spree code with prepend.

app/models/spree/optional_phone_address.rb

module Spree
  module OptionalPhoneAddress
    # require_phone?
    #   - no longer require a phone
    #   - a * no longer appears next to phone in the view
    #
    def require_phone?
      false
    end
  end
end

config/initializers/spree.rb

#
# Customization of Spree Code
#

Spree::Address.prepend Spree::OptionalPhoneAddress

Note

Further Study

Felix
  • 4,510
  • 2
  • 31
  • 46
notapatch
  • 6,569
  • 6
  • 41
  • 45
  • 1
    In latest solidus/rails (2020: Rails6, solidus 2.10) this does not work anymore (https://github.com/solidusio/solidus/issues/3651). – Felix Jun 03 '20 at 10:30
  • 1
    Thanks @Felix - I am not working with Solidus but I cut and pasted the example code from the github issue. Feel free, or other people working with it, to change the answer as you see fit. – notapatch Jun 03 '20 at 11:06