Customizing Blacklight Tutorial Series (v5.14.0)

Overrides

Much of Blacklight is written in a way that is overridable, helper methods are no different.

Let’s take a look at the module that renders search constraints on results pages. This module is mixed into the Blacklight::RenderConstraintsHelper which allows us to override methods mixed in.

For example, the render_constraints method renders the constraints area in the results page.

##
# Render the actual constraints, not including header or footer
# info.
#
# @param [Hash] query parameters
# @return [String]
def render_constraints(localized_params = params)
  render_constraints_query(localized_params) + render_constraints_filters(localized_params)
end
Default constraints
Default constraints

If we want to modify this method to return something different, we first need to create the RenderConstraintsHelper module in our local application.

$ touch app/helpers/render_constraints_helper.rb

And then within render_constraints_helper.rb we need to include the Blacklight::RenderConstraintsHelperBehavior mixin.

# app/helpers/render_constraints_helper.rb
module RenderConstraintsHelper
  include Blacklight::RenderConstraintsHelperBehavior
end

Now we are free to override methods to meet our custom application needs. For example, lets override the render_constraints method.

# app/helpers/render_constraints_helper.rb
module RenderConstraintsHelper
  include Blacklight::RenderConstraintsHelperBehavior
  ##
  # Overridden to include an extra message
  #
  # @param [Hash] query parameters
  # @return [String]
  def render_constraints(localized_params = params)
   (super + "<--- Remove limits by clicking the x").html_safe
  end
end

This overridden method adds a string to the super call. super here calls the render_constraints method defined in Blacklight::RenderConstraintsHelperBehavior and our concatenated string is returned and displayed in the interface.

Custom constraints
Custom constraints

This is just one way that the Blacklight code can be overridden and customized. Similar patterns can be used to customize controllers and search behavior.