写出来的都是shit,快关闭!

手把手教你在Rails中集成Simditor富文本编辑器

CKEditor,kindeditor,UEditor 功能复杂+丑.
So,Out of My Mind.

Simditor是一个基于浏览器的所见即所得富文本编辑器.
Tower(一个流行的项目管理web应用)在使用它.
轻量易用,毕竟功能太多了业务员不会用.
外观萌萌哒.
支持浏览器: IE10+、Chrome、Firefox、Safari.

Gemfile

1
  gem 'simditor-rails'

前端

app/assets/javascripts/application.js

1
  //= require simditor

app/assets/stylesheets/application.scss

1
  @import "simditor";

app/views/posts/_form.html.slim

1
= f.input :content, :as=> :text, input_html: { name: 'content'}
1
2
3
<textarea name="content" class="text required form-control" id="post_content">
  内容内容内容内容内容内容内容内容内容内容内容内容内容内容
</textarea></div>

app/assets/javascripts/post.js.coffee

1
2
3
4
5
6
7
8
9
10
$ ->
  editor = new Simditor(
    textarea: $('#post_content')  #textarea的id
    fileKey: 'upload_file'  #指定服务器获取上传文件数据的参数params["upload_file"]
    upload: {
      url: '/photos'  #对应的request routes
    }
    #toolbar: 更多选项参考 https://github.com/mycolorway/simditor
    toolbar: ['bold', 'italic', 'color', '|', 'ol', 'ul', '|', 'link', 'image', '|', 'indent', 'outdent', '|', 'hr', 'table']
  )

后端

app/controllers/photos_controller.rb

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class PhotosController < ApplicationController
  before_action :authenticate_user!

  def create
    @photo = Photo.new(image: params["upload_file"])
    if @photo.save
      success = true
      msg = '上传成功'
      file_path = "#{@photo.image.url}"
    else
      success = false
      msg = '上传失败'
      file_path = ""
    end

    render json: {:success=> success, :msg=>msg, :file_path=>file_path }
  end
end
1
{"success":true,"msg":"xxx","file_path":"/uploads/photo/image/xxx/xxx_xxx.jpg"}

config/routes.rb

1
  resources :photos, only: [:create]

app/models/photo.rb

1
2
3
4
5
6
class Photo
  include Mongoid::Document
  include Mongoid::Timestamps
  field :image
  mount_uploader :image, PhotoUploader
end

app/uploaders/photo_uploader.rb

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
26
27
28
29
30
31
32
33
34
# encoding: utf-8

class PhotoUploader < CarrierWave::Uploader::Base
  include CarrierWave::MiniMagick

  storage :file

  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  def filename
    time_format = '%Y%m%d%H%M%S%L'
    if original_filename
      @name ||= "#{Time.now.strftime(time_format)}_#{Digest::MD5.hexdigest(File.dirname(current_path))}"
      "#{@name}.#{file.extension.downcase}"
    end
  end

  process :resize_to_limit => [1200,nil]

  version :medium do
    process :resize_to_limit => [640,nil]
  end

  version :small do
    process :resize_to_limit => [400,nil]
  end

  def extension_white_list
    %w(jpg jpeg gif png)
  end

end

DONE

搞定