長微博就是把文字轉換成圖片,主要用到的gem是imgkit。html
imgkit是一個經過open3來調用wkhtmltoimage生成圖片的gem,源碼不是很複雜,使用也很簡單。git
基本步驟以下:github
rails new long-weibo #Add imgkit and carrierwave to Gemfile and run bundle rails g model weibo weibo:string image:string rake db:migrate rails g controller home index create
修改一下routes.rb工具
post "create" =>'home#create' root 'home#index'
寫個簡單的界面home/index.html.erbpost
<textarea id="content" name="content"> </textarea> <a id="create" href="#create">Create</a> <div id="image"> </div>
寫段簡單的jsurl
$(function(){ $("#create").click(function(){ var content = $("#content").val(); $.post("/create",{content:content},function(returnData){ $("#image").html("<img src='"+returnData+"'>"); }); }); });
把controller改改code
def index end def create @weibo = Weibo.create(weibo:params[:content]) render :text=>"#{@weibo.image.url}" end
把model改改htm
class Weibo < ActiveRecord::Base after_create :generate_image mount_uploader :image,ImageUploader private def generate_image file = Tempfile.new(["template_#{self.id.to_s}", 'jpg'], 'tmp', :encoding => 'ascii-8bit') #不加html標準標籤中文會亂碼 #由於textarea中的換行是\n 須要替換成br標籤 weibo = "<!DOCTYPE html><html><head><meta charset='UTF-8'></head><body>#{self.weibo.gsub("\n","<br />")}</body></html>" file.write(IMGKit.new(weibo, quality: 50, width: 600,height:0).to_jpg) file.flush self.image = file self.save file.unlink end end
完成了,超級簡陋的長微博生成工具。blog
源碼地址: long-weibo圖片