Tweak engine models

One of the good things about using a Rails engine is that you can pretty easily enhance a class of the engine directly in your application.

As an example, we are going to tweak the LocomotiveCMS Page model in order to manage the cache of a page.

We assume you're using Textmate. That is why you will see mate to edit a file. If not, please correct it accordingly.

1. Initialize the custom Page model

cd <your application path>
mkdir app/models/locomotive
mate app/models/locomotive/page.rb

Fill in the blank file with the following code:

module Locomotive
  class Page
  end
end

In other words, we just re-open in Ruby an existing class from the engine.

Keep in mind that the engine models are loaded BEFORE those from the application.

2. Implement a new behavior

Let's say we want to manage the cache of a Page.

mkdir -p app/concerns/locomotive/page
mate app/concerns/locomotive/page/cache.rb

We use the Concern module from ActiveSupport to implement the new behavior.

module Locomotive::Page::Cache

  extend ActiveSupport::Concern

  included do

    ## callbacks ##
    after_update  :reset_cache
    after_destroy :reset_cache

  end

  def reset_cache
    logger.info "Reset cache for " + page.title
    # TODO: really reset cache :-)
  end

end

3. Add the new behavior to our custom Page

Open your page class:

mate app/models/locomotive/page.rb

Finally, include the Cache module we have just created:

module Locomotive
  class Page

    ## injections ##
    include Locomotive::Page::Cache

  end
end
You can add as many modules as you want.
The same mechanism can be applied to the LocomotiveCMS controllers.
© 2024 LocomotiveCMS Terms of use Privacy Policy
Back to top