0

In my rails app, I am using Kramdown to parse Markdown. I want to extend the functionality of the convert_a method in the HTML converter. Part of this involves accessing the database, but it is dependent on a parameter in the URL. Because I am not directly calling the method that I am overriding I cannot simply pass the method the params hash. Is there a way to access this hash, or even just get the current URL in a module in the lib directory?

to give a bit more context, the method call is in a helper method here:

# in app/helpers/myhelper.rb

def to_html(text)
     Kramdown::Document.new(text, parse_block_html: true).to_custom_html
end

and here is the file in which I override the convert_a:

# in lib/custom_html.rb

class CustomHtml < Kramdown::Converter::Html
    def convert_a(el, indent)
        # use params[:foo] to make query
        format_as_span_html(el.type, el.attr, inner(el, indent))
    end
end

Edit:

To give a bit more context on where the overrided method is called. I am not extremely familiar with the Kramdown codebase, however it seems that when to_custom_html is called the following bit of code is run inside of Kramdown.rb:

output, warnings = Converter.const_get(name).convert(@root, @options)

which subsequently calls convert_#{el.type} on the internal kramdown elements.

Chris Morgan
  • 85
  • 1
  • 6
  • Can you show the code where this `CustomHtml` class is being used? – max pleaner Jan 22 '20 at 04:09
  • It gets used internally by the Kramdown gem. Kramdown has an internal representation of the text which is converted by the HTML converter. I am just overriding one of the methods. I don't know when it is called precisely I just know it is at some point within the Kramdown lifecycle – Chris Morgan Jan 22 '20 at 04:18
  • Well, I can give you two options. #1 is you do the "hard way" and patch the whole method chain to pass along your params data. #2 is the hacky way, where you use something like a global or thread variable and don't bother passing params around at all. For a hobby project I would just go with the hacky way. You should think more deeply about it before using that approach in production though. – max pleaner Jan 22 '20 at 04:46
  • Might I ask, what behavior are you trying to conditionally implement? Maybe it'd be easier to manipulate the HTML after the conversion happens, with something like Nokogiri – max pleaner Jan 22 '20 at 06:41

1 Answers1

0

You can pass additional options in Kramdown::Document#new, so just do something like Kramdown::Document.new(text, my_params: params). Then you can use the #options method of the converter to access your params.

gettalong
  • 735
  • 3
  • 10