1

I'm using the gem "redcarpet". And I have a markdown file. I want to be able to render it with some ruby variables. Something like this:

 # my_file.md

 ###Something
 fdafdsfdsfds

 ---

 <% for n in my_numbers do %>
     <%= n %>
 <% end %>

What's the proper way to do something like this? How can I pass and render a ruby variable?

Raj
  • 101
  • 1
  • 2
  • 7

1 Answers1

5

You can use the erb library which is included in ruby, but you have to require it:

require 'erb'
require 'redcarpet'

input = File.read "./file.md"

markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML, autolink: true, tables: true)

output = markdown.render ERB.new(input).result(binding)

File.open("output.html", "w") { |f| f.write output }

You can customize the markdown renderer by referencing the redcarpet readme

max pleaner
  • 26,189
  • 9
  • 66
  • 118
  • what's binding? – Raj Dec 31 '17 at 04:38
  • binding is a special variable, search google for "what is binding in ruby" for more info. The ruby variables are assumed to be in the `file.md` file ... – max pleaner Dec 31 '17 at 08:31
  • why use metaprogramming without necessity? how will I pass a concrete variable, not all of the context? – Raj Dec 31 '17 at 14:12
  • this isn't really much metaprogramming. If you want to only expose particular data and not the whole context, you can create a custom binding object, but i'm not really sure why you would want to do that. – max pleaner Dec 31 '17 at 18:06
  • `If you want to only expose particular data and not the whole context, you can create a custom binding object, ` --- how? – Raj Jan 01 '18 at 03:25
  • 1
    https://stackoverflow.com/questions/41589976/how-to-create-new-binding-and-assign-instance-variables-to-it-for-availability-i – max pleaner Jan 03 '18 at 16:45