用rails做一个简单的长微博生成工具

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

<textarea id="content" name="content">
</textarea> 
<a id="create" href="#create">Create</a> 
<div id="image"> </div>

写段简单的js

$(function(){
   $("#create").click(function(){
         var content = $("#content").val();
         $.post("/create",{content:content},function(returnData){
                 $("#image").html("<img src='"+returnData+"'>");      
         });   
    }); 
});

把controller改改

  def index
  end   
  def create     
      @weibo = Weibo.create(weibo:params[:content])     
      render :text=>"#{@weibo.image.url}"   
  end

把model改改

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

完成了,超级简陋的长微博生成工具。

源码地址: long-weibo


Jerry Tao 一个流浪的要饭的

转载于:https://my.oschina.net/jerrytao/blog/201775

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值