auto_html plugin

If you don’t want to bother visitors with rich HTML editor or markup code, but you still want to allow them to embed youtube video, images, links and stuff like that on your site, purely by pasting URL, check out auto_html Rails plugin. See the live demo.


script/plugin install git://github.com/dejan/auto_html.git

Let’s say you have model Comment with attribute body. Create another column in database called body_html. Now have something like this:


class Comment < ActiveRecord::Base
auto_html_for(:body) do
html_escape
youtube(:width => 400, :height => 250)
image
link(:target => "_blank", :rel => "nofollow")
simple_format
end
end

… and you’ll have this behaviour:


Comment.create(:body => 'Hey check out this cool video: http://www.youtube.com/watch?v=WdsGihou8J4')
=> #Hey check out this cool video: '>

Note that order of invoking filters is important, ie. you want html_escape as first and link amongst last, so that it doesn’t transform youtube URL to plain link.

Now all you have to do is to display it in template without escaping, since plugin took care of that.


< % for comment in @comments %>

  • < %= comment.body_html %>
  • < % end %>

    If you need to display preview, no problem. Have something like this as action in your controller:


    def preview
    comment = Comment.new(params[:comment])
    comment.auto_html_prepare
    render :text => comment.body_html
    end

    Plugin is highly customizable, and you can easily create new filters that will transform user input any way you like. For instance, this is the filter for youtube that comes bundled with plugin:


    AutoHtml.add_filter(:youtube).with(:width => 390, :height => 250) do |text, options|
    text.gsub(/http:\/\/www.youtube\.com\/watch\?v=([^&\n]+)/) do
    youtube_id = $1
    %{}
    end
    end

    If you want to contribute new filters or enhance existing ones, you can do that on github.

    2 Comments

    1. Posted February 17, 2009 at 11:29 am | Permalink

      great idea, i’m going to test it now
      thanks

    2. Posted March 30, 2009 at 11:54 pm | Permalink

      Diggin’ this.

    Post a Comment

    Your email is never published nor shared. Required fields are marked *

    *
    *

    You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">