Integrate simditor to ROR project with image upload
最近在开发一个用于自己写技术文章的平台,需要有一个让自己快乐写作的编辑器,之前使用的是pagedown的编辑器,使用pagedown-bootstrap-rails这个gem可以很方便在在rails上集成一个比较漂亮的markdown编辑器,但是有一个问题,markdown这种语法度很高的写作语言,还大部分的流行在IT程序员当中,工业领域的工程师是相对比较传统的,习惯使用传统的编辑器,这让我萌生了更换编辑的想法,于是在ruby-china发了一个帖子有推荐一下好用的 Rails editor 吗?,社区大大力推荐我使用simditor,惊艳啊!于是立马迁移!
ROR的环境
- 'rails', '4.1.8'
- 'Ruby'. '2.1.5'
- OSx 10.10.5
步骤
- 在
Gemfile
里面加入一行gem 'simditor'
bundle install
安装这个simditor这个gem,已经打包好所有simditor需要用的assets了在
application.js
里面加上://= require simditor //= require simditor/simditor-fullscreen
注:我还加了一个simditor-fullscreen的插件,使用esc
切换全屏,方法专注于写作- 在
application.css
里面加上*= require simditor
- 在
_form.html.erb
可以这么写:
{% highlight ruby %}
<%= form_for(@post) do |f| %>
<% end %>
<% end %>
{% highlight%}
注:在textfield里面一定要加一个:type=> 'hidden',要不然会有另外一个input显示出来。
集成图片上传
我的方案是需要在写文章的时候上传图片,容易写图文混排的技术文章,步骤:
- 新建一个
photosController.rb
,写一个upload
的action
用来处理图片上传 - 新建一个
migration
,创建一个photos
的table
用来存储图片信息 - 新建一个
photos.rb
- 在
routes.rb
里面加上图片上传的路由POSTpost 'photos' => 'photos#upload'
- 新建一个
photo_uploader.rb
,使用CarrierWave和MiniMagick用来处理文件上传和图片处理过程,需要两个gem:gem 'carrierwave','0.6.2'
和
gem 'mini_magick'
- 在
user.rb
里面加入has_many :photos
- 相关代码如下:
# PhotosController.rb
class PhotosController < ApplicationController
before_action :authenticate_user!
def upload
@photo = Photo.new
@photo.image = params[:upload_file]
@photo.user_id = current_user.id
success = true
msg = '上传成功'
file_path = ''
if @photo.save
success=true
render json: { :success=> success, :msg=>msg, :file_path=> @photo.image.url }
else
success=false
render json: { :success=> false }
end
end
end
#Createphotos.rb
class CreatePhotos < ActiveRecord::Migration
def change
create_table :photos do |t|
t.string :image
t.timestamps
end
add_column :photos,:user_id,:integer
add_index :photos, :user_id
end
end
#photo.rb
class Photo< ActiveRecord::Base
belongs_to :user
validates :user_id, presence: true
validates :image, presence: true
mount_uploader :image, PhotoUploader
end
#photo_uploader.rb
class PhotoUploader < CarrierWave::Uploader::Base
include CarrierWave::MiniMagick
storage :file
process resize_to_limit: [640, nil]
def store_dir
"photos/"
end
def filename
if super.present?
@name ||= Digest::MD5.hexdigest(current_path)
"#{Time.now.year}/#{@name}.#{file.extension.downcase}"
end
end
def extension_white_list
%w(jpg jpeg gif png)
end
end
智造师小密圈
Meet some of the people behind the new manufacturing revolution
与那些在智能制造新革命背后的人交流