Deface
Using Deface is no longer recommended

What is Deface?

Deface is a standalone Rails library that enables you to customize Erb templates without needing to directly edit the underlying view file. Deface allows you to use standard CSS3 style selectors to target any element (including Ruby blocks), and perform an action against all the matching elements.

Improving Our Extension Using Deface

The Goal

Our goal is to add a field to the product edit admin page that allows the sale_price to be added or updated. We could do this by overriding the view Spree provides, but there are potential problems with this technique. If Spree updates the view in a new release we won't get the updated view as we are already overriding it. We would need to update our view with the new content from Spree and then add our customizations back in to stay fully up to date.
Let's do this instead using Deface, which we just learned about. Using Deface will allow us to keep our view customizations in one spot, app/overrides, and make sure we are always using the latest implementation of the view provided by Spree.

The Implementation

We want to override the product edit admin page, so the view we want to modify in this case is the product form partial. This file's path will be spree/admin/products/_form.html.erb.
First, let's create the overrides directory with the following command:
1
mkdir app/overrides
Copied!
So we want to override spree/admin/products/_form.html.erb. Here is the part of the file we are going to add content to (you can also view the full file):
1
<div class="right four columns omega" data-hook="admin_product_form_right">
2
<%= f.field_container :price do %>
3
<%= f.label :price, raw(Spree.t(:master_price) + required_span_tag) %>
4
<%= f.text_field :price, value: number_to_currency(@product.price, unit: '')%>
5
<%= f.error_message_on :price %>
6
<% end %>
7
</div>
Copied!
We want our override to insert another field container after the price field container. We can do this by creating a new file app/overrides/add_sale_price_to_product_edit.rb and adding the following content:
1
Deface::Override.new(virtual_path: 'spree/admin/products/_form',
2
name: 'add_sale_price_to_product_edit',
3
insert_after: "erb[loud]:contains('text_field :price')",
4
text: "
5
<%%= f.field_container :sale_price do %>
6
<%%= f.label :sale_price, raw(Spree.t(:sale_price) + content_tag(:span, ' *')) %>
7
<%%= f.text_field :sale_price, value:
8
number_to_currency(@product.sale_price, unit: '') %>
9
<%%= f.error_message_on :sale_price %>
10
<%% end %>
11
")
Copied!
We also need to delegate sale_price to the master variant in order to get the updated product edit form working.
We can do this by creating a new file app/models/spree/product_decorator.rb and adding the following content to it:
1
module Spree
2
Product.class_eval do
3
delegate :sale_price, :sale_price=, to: :master
4
end
5
end
Copied!
Now, when we head to http://localhost:3000/admin/products and edit a product, we should be able to set a sale price for the product and be able to view it on our sale page, http://localhost:3000/sale. Note that you will likely need to restart our example Spree application (created in the Getting Started tutorial).

Available actions

Deface applies an action to element(s) matching the supplied CSS selector. These actions are passed when defining a new override are supplied as the key while the CSS selector for the target element(s) is the value, for example:
1
remove: "p.junk"
2
3
insert_after: "div#wow p.header"
4
5
insert_bottom: "ul#giant-list"
Copied!
Deface currently supports the following actions:
  • :remove - Removes all elements that match the supplied selector
  • :replace - Replaces all elements that match the supplied selector, with the content supplied
  • :replace_contents - Replaces the contents of all elements that match the supplied selector
  • :surround - Surrounds all elements that match the supplied selector, expects replacement markup to contain <%%= render_original %> placeholder
  • :surround_contents - Surrounds the contents of all elements that match the supplied selector, expects replacement markup to contain <%%= render_original %> placeholder
  • :insert_after - Inserts after all elements that match the supplied selector
  • :insert_before - Inserts before all elements that match the supplied selector
  • :insert_top - Inserts inside all elements that match the supplied selector, as the first child
  • :insert_bottom - Inserts inside all elements that match the supplied selector, as the last child
  • :set_attributes - Sets attributes on all elements that match the supplied selector, replacing existing attribute value if present or adding if not. Expects :attributes option to be passed.
  • :add_to_attributes - Appends value to attributes on all elements that match the supplied selector, adds attribute if not present. Expects :attributes option to be passed.
  • :remove_from_attributes - Removes value from attributes on all elements that match the supplied selector. Expects :attributes option to be passed.
Not all actions are applicable to all elements. For example, `:insert_top` and `:insert_bottom` expects a parent element with children.

Supplying content

Deface supports three options for supplying content to be used by an override:
  • :text - String containing markup
  • :partial - Relative path to a partial
  • :template - Relative path to a template
As Deface operates on the Erb source the content supplied to an override can include Erb, it is not limited to just HTML. You also have access to all variables accessible in the original Erb context.

Targeting elements

While Deface allows you to use a large subset of CSS3 style selectors (as provided by Nokogiri), the majority of Spree's views have been updated to include a custom HTML attribute (data-hook), which is designed to provide consistent targets for your overrides to use.
As Spree views are changed over coming versions, the original HTML elements maybe edited or be removed. We will endeavour to ensure that data-hook / id combination will remain consistent within any single view file (where possible), thus making your overrides more robust and upgrade proof.
For example, spree/products/show.html.erb looks as follows:
1
<div data-hook="product_show" itemscope itemtype="http://schema.org/Product">
2
<%% body_id = 'product-details' %>
3
<div class="columns six alpha" data-hook="product_left_part">
4
<div class="row" data-hook="product_left_part_wrap">
5
<div id="product-images" data-hook="product_images">
6
<div id="main-image" data-hook>
7
<%%= render 'image' %>
8
</div>
9
10
<div id="thumbnails" data-hook>
11
<%%= render 'thumbnails', product: product %>
12
</div>
13
</div>
14
15
<div data-hook="product_properties">
16
<%%= render 'properties' %>
17
</div>
18
19
</div>
20
</div>
21
22
<div class="columns ten omega" data-hook="product_right_part">
23
<div class="row" data-hook="product_right_part_wrap">
24
25
<div id="product-description" data-hook="product_description">
26
27
<h1 class="product-title" itemprop="name"><%%= accurate_title %></h1>
28
29
<div itemprop="description" data-hook="description">
30
<%%= product_description(product) rescue Spree.t(:product_has_no_description) %>
31
</div>
32
33
<div id="cart-form" data-hook="cart_form">
34
<%%= render 'cart_form' %>
35
</div>
36
</div>
37
38
<%%= render 'taxons' %>
39
</div>
40
</div>
41
</div>
Copied!
As you can see from the example above the data-hook can be present in a number of ways:
  • On elements with no id attribute the data-hook attribute
    contains a value similar to what would be included in the id
    attribute.
  • On elements with an id attribute the data-hook attribute does
    not normally contain a value.
  • Occasionally on elements with an id attribute the data-hook will
    contain a value different from the elements id. This is generally to
    support migration from the old 0.60.x style of hooks, where the old
    hook names were converted into data-hook versions.
The suggested way to target an element is to use the data-hook attribute wherever possible. Here are a few examples based on products/show.html.erb above:
1
replace: "[data-hook='product_show']"
2
3
insert_top: "#thumbnails[data-hook]"
4
5
remove: "[data-hook='cart_form']"
Copied!
You can also use a combination of both styles of selectors in a single override to ensure maximum protection against changes:
1
insert_top: "[data-hook='thumbnails'], #thumbnails[data-hook]"
Copied!

Targeting ruby blocks

Deface evaluates all the selectors passed against the original erb view contents (and importantly not against the finished / generated HTML). In order for Deface to make ruby blocks contained in a view parseable they are converted into a pseudo markup as follows.
Given the following Erb file:
1
<%% if products.empty? %>
2
<%%= Spree.t(:no_products_found) %>
3
<%% elsif params.key?(:keywords) %>
4
<h3><%%= Spree.t(:products) %></h3>
5
<%% end %>
Copied!
Would be seen by Deface as:
1
<!-- <html>
2
<erb[silent]> if products.empty? </erb>
3
<erb[loud]> Spree.t(:no_products_found) </erb>
4
<erb[silent]> elsif params.key?(:keywords) </erb>
5
6
<h3><erb[loud]> Spree.t(:products) </erb></h3>
7
8
<erb[silent]> end </erb>
9
</html> -->
Copied!
So you can target ruby code blocks with the same standard CSS3 style selectors, for example:
1
replace: "erb[loud]:contains('t(:products)')"
2
3
insert_before: "erb[silent]:contains('elsif')"
Copied!

View upgrade protection

To ensure upgrading between versions of Spree is as painless as possible, Deface supports an :original option that can contain a string of the original content that's being replaced. When Deface is applying the override it will ensure that the current source matches the value supplied and will output to the Rails application log if they are different.
These warnings are a good indicator that you need to review the source and ensure your replacement is adequately replacing all the functionality provided by Spree. This will help reduce unexpected issues after upgrades.
Once you've reviewed the new source you can update the :original value to new source to clear the warning.
Deface removes all whitespace from both the actual and `:original` source values before comparing, to reduce false warnings caused by basic whitespace differences.

Organizing Overrides

The suggested method for organizing your overrides is to create a separate file for each override inside the app/overrides directory, naming each file the same as the :name specified within.

More information on Deface

For more information and sample overrides please refer to its README file on GitHub.
Last modified 3mo ago