长微博就是把文字转换成图片,主要用到的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图片