11

I am using Spree, and Spree has a class called Order that looks like:

module Spree
  class Order
    # class definition.
  end
end

In my own app, I have been customising Order like so:

Spree::Order.class_eval do
  # customisations
end

My question is, can I simply just do this:

module Spree
  class Order
    # My own customisations.
  end
end

Any downsides to this? Essentially, I want to avoid using class_eval.

Benjamin Tan Wei Hao
  • 9,621
  • 3
  • 30
  • 56
  • hey.. did you find a solution to this? I'm now just getting started with spree, and need to add a constant to the Spree::Order class. using `class_eval` somehow isn't working for constants, and without class_eval, I can't figure out how to access other methods in the class that I am reopening. – kapad Jul 17 '18 at 09:36
  • 1
    Try using `@@some_constant`. Not a Spree issue, but a general Ruby weirdness. – Benjamin Tan Wei Hao Jul 18 '18 at 08:34
  • 1
    yep.. that's what I did and it worked. One note though, I had to `require` the module/class that I was opening prior to opening it. This ensured that the original class file was loaded before I opened it again to change it to avoid getting class not found errors. – kapad Jul 18 '18 at 10:16

2 Answers2

6

Benjamin, reopen class will not inform you (but class_eval will raise error) if the existing class does not exist or not loaded.

But if you have test coverage, reopen class should be safe I guess?

See https://stackoverflow.com/a/900508/474597 for more detailed explanation.

lulalala
  • 17,572
  • 15
  • 110
  • 169
Huiming Teo
  • 293
  • 3
  • 7
0

you cant alter the class without class_eval. just try to override one method, and all other methods are gone. with class_eval you avoid it. thats the ruby way.

Tim Kretschmer
  • 2,272
  • 1
  • 22
  • 35