Sanitizing and textilizing in Model
This is a two fold question.
I have a RoR (3.0.7) application that accepts user input, for instance creating a news article. So far the user input was in plain XHTML as the users are trusted. However, creating posts on a website in XHTML is challenging for some users so we will try to move to textile.
To use textile I installed RedCloth.
Since we will not be converting the already existing news articles to textile, which I know would be the correct thing to do to have uniform data, the plan is, to use RedCloth on the content only after a given date.
In the views I would simply have a conditional that checks for the created_at date and then call for RedCloth before outputting. However, that would mean that I had to itera开发者_开发百科te through all views and insert the conditional whenever I present that specific content. I could possibly even create a helper that would minimize the code I would have to replicate.
Instead of doing that and keeping it DRY I decided to move the logic down in to the Model. The Model has a column called articlecontent. What I came up with is the below code, which so far seems to work:
def articlecontent
if !self.new_record? && created_at.to_datetime > 'YYYY.MM.DD'.to_datetime
articlecontent_in_textile = self[:articlecontent]
articlecontent_in_html = RedCloth.new(articlecontent_in_textile, [:filter_html]).to_html
return articlecontent_in_html
else
return self[:articlecontent]
end
end
So my questions are:
1) Is this the right way to go about it? Or should I define some sort of ViewHelper?
2) It seems I cannot call the sanitize helper in the Model, probably for a good reason. Is there way to call the helper in the Model?
Thanks Marc
I'd go with defining a helper, as this is logic that really belongs in the view rather than the model.
However, you may want to define a method on the model which returns the type of markup used:
def markup_type
created_at > MARKUP_CHANGED_DATETIME ? "textile" : "html"
end
With MARKUP_CHANGED_DATETIME being a constant you can define in a config file.
Or alternatively add a markup_type
attribute to the model via a migration, and set all the previous one to be "html" and all future ones to be "textile" - this would have the benefit of allowing you to continue to use both side by side, or to gradually change the old ones over.
精彩评论