如何修改Ruby的gem源

Python0156

如何修改Ruby的gem源,第1张

Ruby环境下的gem sources地址默认是国外网络地址,所以在使用gem的过程中经常会出现找不到资源的Error。那么如何解决这种Error?方法很简单:要么就多次尝试执行gem命令,要么就修改gem源地址

下面由小河给大家分享:如何修改Ruby的gem源地址。

注:无论是在windows系统上还是在linux系统上其修改方式一样,以CentOS6.4为例。

工具/原料

Ruby

gem源(gem sources)

CentOS6.4

方法/步骤

进入Centos6.4系统。

◆示例是以Centos6.4系统为例。

◆若是windows系统则进入“命令提示符”做修改。

查看当前使用的源地址。

◆输入:gem sources

删除默认的源地址。

◆输入:gem sources -r url地址

注:默认的url地址后必须有”/”,否则删不掉。

添加淘 宝的源地址。

◆输入:gem sources -a url地址

注:国内使用淘 宝的源比较稳定,且安装或更新网速都比较快。

新源的缓存

◆输入:gem sources -u

更新源的缓存后即完成了Ruby的gem源修改。

说是使用pdfkit,其实做工作的还是wkhtmltopdf。

一、新建项目

rails new mypdf --skip-bundle

进入项目:cd mypdf,打开Gemfile:vim Gemfile

修改source为https://ruby.taobao.com

添加:gem 'pdfkit'

运行bundle install

二、配置

在项目目录下的config/initializers里加上pdfkit.rb文件,修改内容为:

PDFKit.configure do |config|

config.wkhtmltopdf = '/path/wkhtmltopdf'

end

config.wkhtmltopdf配置的是wkhtmltopdf的路径,要确保pdfkit能找到它。

其它的配置请参考:http://wkhtmltopdf.org/usage/wkhtmltopdf.txt,里面的横杠用下划线代替。

三、使用

在controller里的相应位置加入:

用渲染的模版内容生pdf:

html = render_to_string(:template =>"pdf_template.erb",:layout =>false)

kit = PDFKit.new(html)

kit.stylesheets <<"#{Rails.root}/app/assets/assets/stylesheets/pdf.css"

#kit.to_pdf # inline PDF

#kit.to_file('/path/pdf.pdf')

send_data(kit.to_pdf, :filename =>"mypdf.pdf", :type =>"application/pdf")

#render :text =>kit.to_pdf

用url的内容生成pdf:

url = "http://www.baidu.com"

kit = PDFKit.new(url)

# kit.stylesheets <<"#{Rails.root}/app/assets/assets/stylesheets/pdf.css" # 用url时就不可以用css样式了。

#kit.to_pdf # inline PDF

#kit.to_file('/path/pdf.pdf')

send_data(kit.to_pdf, :filename =>"mypdf.pdf", :type =>"application/pdf")

注: kit = PDFKit.new(url, cookie: {"cookie_name"=>"cookie_content"}),如果需要登录的话,可以用cookie。cookie可以自己获取。

另外,如果你的页面里有js需要运行,最好在设置文件里设置如下:

javascript_delay: 1000

它的默认值是200毫秒。把加大一些,以便让js运行完成。

这样就可以用了。