Ruby
textilize model helper
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
module ModelHelpers
def self.included(base)
base.extended ClassMethods
end
module ClassMethods
def textilize(*columns)
methods = []
suffix = columns.last.is_a?(Hash) ? columns.pop.values.last : 'html'
columns.each do |column|
define_method "#{column}_to_html" do
self["#{column}_#{suffix}"] = RedCloth.new(self[column] || '').to_html
end
methods << "#{column}_to_html".to_sym
end
methods.each { |method| before_save method }
end
end
end
module ModelHelpers
def self.included(base)
base.extended ClassMethods
end
module ClassMethods
def textilize(*columns)
methods = []
suffix = columns.last.is_a?(Hash) ? columns.pop.values.last : 'html'
columns.each do |column|
define_method "#{column}_to_html" do
self["#{column}_#{suffix}"] = RedCloth.new(self[column] || '').to_html
end
methods << "#{column}_to_html".to_sym
end
methods.each { |method| before_save method }
end
end
end
Refactorings
No refactoring yet !
November 2, 2007,
November 02, 2007 03:20,
permalink
No rating.
Login to rate!
November 2, 2007,
November 02, 2007 03:32,
permalink
No rating.
Login to rate!
OK, so I just realized there was an acts_as_textilized plugin, but ignore that for right now. I wrote a textilize helper that I'm using in a lot of my models. Without adding to what the functionality, how would you do it?
One thing that stumped me was generating the list of methods for the before_save filter. I wanted this:
before_save :about_to_html, :body_to_html
from an array that has [:about_to_html, :body_to_html] instead of calling before_save for each method separately.