Module: HasMarkup::ActiveRecord::ClassMethods

Defined in:
lib/has_markup/active_record.rb

Overview

Methods that are added to ActiveRecord::Base

Instance Method Summary collapse

Instance Method Details

#has_markup(column, options = {}) ⇒ Object

Adds the following methods for dealing with markup, using has_markup :content as an example:

  • content_html for generating the html of :content.

Options are:

  • :required - column is required

  • :syntax - syntax of the markup. Currently supports only :markdown, which is the default.

  • :cache_html - html generated from the markup should be cached in a column. Following the example of using :content, it would require a column named :cached_content_html. It also adds a before_save hook :cache_content_html for generating the html before saving.

For adding additional syntaxes, see has_markup/markdown and has_markup/textile. Basically:

  • Create HasMarkup::SyntaxNameHere

  • Define sprinkle_syntax_name_here_magic which takes a column name, like :content

  • In sprinkle_syntax_name_here_magic, create "#{column}_html", which handles the actual generation



21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/has_markup/active_record.rb', line 21

def has_markup(column, options = {})
  options = HasMarkup::default_has_markup_options.merge(options)
  
  validates_presence_of column if options[:required]

  syntax = options[:syntax]
  if supported? syntax
    extend markup_syntax_module(syntax)
    send("sprinkle_#{syntax}_magic", column)
  else
    raise "Unsupported syntax #{syntax.inspect}."
  end
  sprinkle_html_caching_magic column if options[:cache_html]
end

#markup_syntax_module(syntax) ⇒ Object



46
47
48
# File 'lib/has_markup/active_record.rb', line 46

def markup_syntax_module(syntax)
  "HasMarkup::#{syntax.to_s.camelize}".constantize
end

#sprinkle_html_caching_magic(column) ⇒ Object

Sprinkles the magic for caching the html of the given



52
53
54
55
56
57
58
# File 'lib/has_markup/active_record.rb', line 52

def sprinkle_html_caching_magic(column)
  define_method "set_cached_#{column}_html" do
    html = self.send("#{column}_html")
    self.send("cached_#{column}_html=", html)
  end
  before_save "set_cached_#{column}_html".to_sym
end

#supported?(syntax) ⇒ Boolean

Is the given syntax supported?

Returns:

  • (Boolean)


37
38
39
40
41
42
43
44
# File 'lib/has_markup/active_record.rb', line 37

def supported?(syntax)
  begin
    markup_syntax_module(syntax)
    return true
  rescue NameError
    return false
  end
end