Question

Is it possible to use ruby in markdown on my Ruby on Rails app? I am using the RedCarpet gem, and I have the following in my application Controller.

class ApplicationController < ActionController::Base
  before_filter :get_contact_info

  private
    def get_contact_info
      @contact = Contact.last
    end
  end

Here is the schema of Contact

create_table "contacts", :force => true do |t|
  t.string   "phone"
  t.string   "email"
  t.string   "facebook"
  t.string   "twitter"
end

So I have the contact info to work with, is there a way I can tell the markdown renderer to render <%= @contact.phone %> as the value of @contact.phone instead of plain text? Or would I need to use something other then markdown for that?

Edit 1:

Rendering markdown here:

app/helpers/application_helper.rb

def markdown(text)
  options = [:hard_wrap, :filter_html, :autolink, :no_intraemphasis]
  Redcarpet.new(text, *options).to_html.html_safe
end

app/views/sites/show.html.erb

<%= markdown(site.description) %>

Edit 2:

Here was my solution, thanks. I integrated your code into my markup helper, this seemed to work so far.

def markdown(text)
  erbified = ERB.new(text.html_safe).result(binding)
  options = [:hard_wrap, :filter_html, :autolink, :no_intraemphasis]
  Redcarpet.new(erbified, *options).to_html.html_safe
end
Était-ce utile?

La solution

You can preprocess your Markdown with ERb, and then pass that result to RedCarpet. I'd suggest putting it in a helper method, something like this:

module ContactsHelper
  def contact_info(contact)
    content = "Hello\n=====\n\nMy number is <%= contact.phone %>"
    erbified = ERB.new(content).result(binding)
    Redcarpet.new(erbified).to_html.html_safe
  end
end

If it's a lot of content, you might consider writing a partial and rendering that partial rather than embedding a lot of HTML in a string as I've done above, but it's up to you.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top