What is the difference between ruby ​​decorators and eval class?

Hey, I'm currently working on a project combining Spree and Refinery. Spree suggests that many modifications are made using what they call decorators:

Refinery::Page.class_eval do def autocomplete_label title end attr_accessible :spree_taxon_id has_one :spree_taxon end 

It works great. But what is the difference between simply opening a class and directly adding methods?

 class Refinery::Page def autocomplete_label title end attr_accessible :spree_taxon_id has_one :spree_taxon end 

I can understand that the first can be used when the class is unknown before runtime (which is not required for this use case). Are there any other differences?

+4
source share
2 answers

The only difference I can think of is that the first version will autoload the existing page class, and then your code will be after adding. If the class is not loaded yet, and you are using the second version, this will most likely interfere with the autoload mode that Spree and Refinery expect, and the class may not load correctly.

+2
source

If you use the class decorator template proposed by Spree, your changes will go through the Gem update. If you instead want to add your methods directly to the class definition, they will be lost after updating your gems.

0
source

All Articles