Search code examples
ruby-on-railsrubyblacklight

Overriding Modules in Blacklight


I would like to override some of the methods defined in the file document_presenter.rb. How can I do this? This module is defined inside the Blacklight gem's "lib" directory.

Is there an easy way to do this? I'm fairly new to Ruby and Rails (coming from a pure Java background), so this is kind of difficult.

Thanks.


Solution

  • It sounds like you are talking about monkey patching the methods in the Backlight gem. You might want to read this post that explains more about monkey patching - and how not to break things badly!

    In Ruby, you can always open an existing class, with the class keyword, and use the def keyword to redefine the original method.

    class DocumentPresenter
      def method_you_want_to_override
        # Your code here.
      end
    end
    

    So for example, you could put the above code into your lib folder:

    lib/document_presenter.rb
    

    See this answer re: auto-loading files in the lib folder.

    After you've done that, whenever you call the method you've monkey patched on an instance of the DocumentPresenter class, the Ruby interpreter will run your code instead. This is not recommended, as it can have dangerous and unpredictable results, as per then blog post I linked to.

    A better practice, in Ruby 2, is to use Refinements.