Skip to content

Overriding built in tags

Rene Saarsoo edited this page Aug 5, 2013 · 4 revisions

To change the behavior of existing tags, we can just override their class definitions.

For example we can look at the Template tag class definition and override the to_html method to put out different markup:

require "jsduck/tag/template"

class JsDuck::Tag::Template
  def to_html(context)
    "<p class='template-highlight'>It's a template!</p>"
  end
end

In addition to the to_html we'd also like to change the @css instance variable. We could just override the initialize method:

class JsDuck::Tag::Template
  def initialize
    @pattern = "template"
    @signature = {:long => "template", :short => "TMP"}
    @html_position = POS_TEMPLATE
    # Box with light gray background
    @css = <<-EOCSS
      .template-highlight {
        font-weight: bold;
        color: red;
      }
    EOCSS
    super
  end

  ...
end

But this way we end up duplicating a bunch of other unrelated code of which we're not at all interested. A better approach is to call the overridden method first and then apply some additional modifications on top of that:

class JsDuck::Tag::Template
  alias_method :old_initialize, :initialize

  def initialize
    old_initialize
    @css = <<-EOCSS
      .template-highlight {
        font-weight: bold;
        color: red;
      }
    EOCSS
  end

  ...
end

Here we're using alias_method to give the old initialize method another name before we override it. It's not the cleanest approach, but unless you're going to override it several times (and I see no reason to) this should be good enough.

Clone this wiki locally