本文共 1112 字,大约阅读时间需要 3 分钟。
长微博就是把文字转换成图片,主要用到的gem是imgkit。
imgkit是一个通过open3来调用wkhtmltoimage生成图片的gem,源码不是很复杂,使用也很简单。
基本步骤如下:
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.erb
Create
写段简单的js
$(function(){
$("#create").click(function(){
var content = $("#content").val();
$.post("/create",{content:content},function(returnData){
$("#image").html("");
});
});
});
把controller改改
def index
end
def create
@weibo = Weibo.create(weibo:params[:content])
render :text=>"#{@weibo.image.url}"
end
把model改改
class Weibo
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 = "html>
#{self.weibo.gsub("\n"," ")}"file.write(IMGKit.new(weibo, quality: 50, width: 600,height:0).to_jpg)
file.flush
self.image = file
self.save
file.unlink
end
end
完成了,超级简陋的长微博生成工具。
转载地址:http://apqll.baihongyu.com/