Skip to content

Instantly share code, notes, and snippets.

@erpe
Last active September 15, 2015 20:44
Show Gist options
  • Save erpe/cf8d15f6f32e0a1797ce to your computer and use it in GitHub Desktop.
Save erpe/cf8d15f6f32e0a1797ce to your computer and use it in GitHub Desktop.
Custom renderer for redcarpet to render paperclip - images by their id and additional css
# quick'm'dirty way to allow paperclip image-ids
# instead of urls be passed to Redcarpet
# so you can do:
# ![title](42 'thumb|pull-right') - whereas 'thumb' is your available paperclip-style and 'pull-right' a css-class
# and also the knwon way:
# ![title](http://i.ytimg.com/vi/Z6po6SS9Uz4/maxresdefault.jpg "my alt text")
# all this b'cause there is no 'super' in redcarpet...
#
class PaperclipRender < Redcarpet::Render::HTML
include ActionView::Helpers::AssetTagHelper
# my image-object here has_attached_file: :data
# we overwrite Redcarpet::Render::HTML#image
#
def image(link_or_id, style_and_css_or_alt, title)
if link_or_id.to_i > 0
args = style_and_css_or_alt.split("|")
style = args[0].to_sym
css = args[1]
# .find_by here b'cause it won't raise ActiveRecord::RecordNotFound
# if none found - no image output
if img = Image.find_by(id: link_or_id)
image_tag(img.data.url(style), title: title, alt: img.title, class: css)
else
''
end
else
# just do it like Redcarpet::Render::HTML would do
# so we can still use default image markdown
image_tag(link_or_id, title: title, alt: style_and_css_or_alt)
end
end
end
# then make use of it in your helper:
def markdown(content)
md = ::Redcarpet::Markdown.new(
PaperclipRender, # instead of Redcarpet::Render::HTML
space_after_headers: true,
tables: true,
quote: true,
hard_wrap: true
)
md.render(content).html_safe if content
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment