I’m writing a Ruby module to provide automatic markdown generation on blog posts etc.
The code so far looks like this:
class Post < ActiveRecord::Base
contains_markdown
end
module MarkdownMixin
def contains_markdown
# HELP! :)
end
end
ActiveRecord::Base.send :extend, MarkdownMixin
That code seems to be working (i.e. my unit tests don’t throw any ‘not defined’ errors etc.). The Post table contains an input and formatted column.
Where I’ve written # HELP I want to inject code to the Post model so that whenever a change is made to input, formatted is recalculated (using a Markdown engine). Something like (pseudo-code):
def on_input_changed
@formatted = Redcarpet.new(@input).to_html
end
Now I’m still really getting my head around Ruby mixins so my brain’s slightly spinning trying to work out what incantation to call in my module.
So far I’ve found this article quite useful, but can’t work out how to apply it here.
I think the easiest way would be to use a
before_savewhere you make the transformation.