Rails + YUI Editor でRailsのテキストエリアをWYSIWYG化
たまには技術的な事も書かないとね。
というワケでRails + YUI Editorでリッチなエディターを作ってみよー。
YUI Editor:
http://developer.yahoo.com/yui/editor/
プラグインで簡単導入
YUI Editorを簡単導入できる"YUI Editorプラグイン"があるのでそれをインストール
YUI Editorプラグイン: http://github.com/larsklevan/yui_editor/tree/master
ruby script/plugin install git://github.com/larsklevan/yui_editor.git
gitがわからないとかうまくインストールできないという方は、サイトからダウンロードして解凍したフォルダを"RAILS_ROOT\vendor\plugins\"にコピペ。
プラグインのフォルダ内にある"yui_editor.yml.tpl"を"yui_editor.yml"にリネームして"RAILS_ROOT\condig"フォルダにコピー。
yui_editor.ymlの以下の部分を編集
javascript_base_uri: //yui.yahooapis.com
↓
javascript_base_uri: http://yui.yahooapis.com
これで導入はオッケー。
scaffold作成
ruby script/generate scaffold bookmark url:string title:string memo:text
今回は"memo"をテキストエリアにしました。
このmemo欄をリッチにします。
bookmarks_controller.rb
indexメソッド上に"uses_yui_editor"を記述
class BookmarksController < ApplicationController uses_yui_editor # GET /bookmarks # GET /bookmarks.xml def index @bookmarks = Bookmark.all (以下、略) end
layouts\bookmarks.html.erb
head内にYUIエディタ設定を記述
Bookmarks: <%= controller.action_name %> <%= stylesheet_link_tag 'scaffold' %> <%= include_yui_editor_if_used %>
new.html.erb, edit.html.erb
classを"rich_text_editor"にしたテキストエリアが自動的にリッチになる
<%= f.text_area :memo, :class => 'rich_text_editor' %>
index.html.erb, show.html.erb
hメソッドからsanitizeメソッドにしてタグを有効にする
(sanitizeメソッドでscriptタグなど危険なタグを無効化する)
<%=h @bookmark.memo %>
↓
<%=sanitize @bookmark.memo %>
YUIエディタの見た目は"RAILS_ROOT\condif\yui_editor.yml"で設定できます。
サンプルソースはこちらから
YUI Editorサンプル - h-nakaoの日記 - hiroshinakaoグループ