Posts match “ gem ” tag:

ruby代码检查器rubocop

什么是RuboCop

Rubocop 是基于 ruby-style-guide / Ruby 风格指导 实现的一个静态代码分析工具。
使用rubocop有助于个人/团队写出风格统一的代码

如何安装

$ gem install rubocop

或使用bundle安装

gem 'rubocop', require: false

如何使用

$ rubocop

或指定目录或文件

$ rubocop app spec lib/tasks/something.rb

ruby-china为例

$ rubocop app/models/user.rb
app/models/user.rb:364:25: C: Prefer single-quoted strings when you don't need string interpolation or special symbols.
        description: a1["description"]
                        ^^^^^^^^^^^^^
app/models/user.rb:367:29: C: Space missing after comma.
    items = items.sort { |a1,a2| a2[:watchers] <=> a1[:watchers] }.take(14)
                            ^
app/models/user.rb:368:81: C: Line is too long. [85/80]
    Rails.cache.write(user.github_repositories_cache_key, items, expires_in: 15.days)
                                                                                ^^^^^
app/models/user.rb:371:3: C: Use only ascii symbols in comments.
  # 重新生成 Private Token

  ^^^^^^^^^^^^^^^^^^^^

1 file inspected, 181 offenses detected

竟然有181个地方需要修改!
其中有很多是 {:a => :b} 修改为 {a: :b}使用类似的问题
可以使用
rubocop自动化修复一部分, 加上-a`参数

$ rubocop -a app/models/user.rb

1 file inspected, 206 offenses detected, 149 offenses corrected

跑测试确认一下

rspec spec/models/user_spec.rb

✌,继续修改

app/models/user.rb:368:81: C: Line is too long. [85/80]
    Rails.cache.write(user.github_repositories_cache_key, items, expires_in: 15.days)
                                                                                ^^^^^
app/models/user.rb:371:3: C: Use only ascii symbols in comments.
  # 重新生成 Private Token

  ^^^^^^^^^^^^^^^^^^^^

又是警告, 但我想写中文注释,一行80个字太短了,我们修改一下rubocop配置。

.rubocop.yml

AllCops:

  RunRailsCops: true

Include:

  - '**/Gemfile'

  - '**/Rakefile'

Exclude:

  - 'bin/*'

  - 'db/migrate/*'

  - 'db/seeds.rb'

  - 'db/schema.rb'

  - 'vendor/bundle/**/*'

  

Metrics/LineLength:

  Max: 120

Style/AsciiComments:

  Enabled: false

再看一下

$ rubocop app/model/user.rb

app/models/user.rb:343:3: C: Assignment Branch Condition size for fetch_github_repositories is too high. [29.9/15]
  def self.fetch_github_repositories(user_id)
  ^^^
app/models/user.rb:343:3: C: Method has too many lines. [23/10]
  def self.fetch_github_repositories(user_id)
  ^^^

1 file inspected, 23 offenses detected

这样, 要修复的就少多了。

剩下的问题如Method has too many lines. [23/10]的警告就看你自己的想法了。
可以参考官方配置
.rubocop.yml里进行配置.

编辑器支持

vim, emacs, sublime, atom, rubymine全部支持
参考第三方支持

如何在slim中添加空格

在slim中如果想在两端代码中间添加一个空格,可以通过下面的方式

= link_to "btn1", "#", :class => "btn"
'
= link_to "btn2", "#", :class => "btn"

加一个'

但代码好丑~

增加carrierwave对rails_admin的支持

由于rails_admin默认只是支持paperclip, 所以使用carrierwave的话, 需要手动做些修改.

一共3个文件

#app/views/rails_admin/main/_form_carrier_wave_file.html.haml

= label_tag "#{field.abstract_model.to_param}_#{field.name}", field.label
.input
  - if field.bindings[:object].send("#{field.name}_url")
    .row
      = link_to field.bindings[:object].send("#{field.name}_url")
      %br
      = form.check_box "remove_#{field.name}"
      = form.label "remove_#{field.name}", "Remove existing #{field.label.downcase}", :class => "inline"
  .row
    = form.file_field field.name, :class => "fileUploadField #{field.has_errors? ? "errorField" : nil}"
    = form.hidden_field "#{field.name}_cache"
#app/views/rails_admin/main/_form_carrier_wave_image.html.haml


= label_tag "#{field.abstract_model.to_param}_#{field.name}", field.label
.input
  - image = field.bindings[:object].send(field.name)
  - if image.path # the most direct check of an assets existence I could see

    .row
      -# load a default 'version' if it exists. should really be set through rails_admin's DSL:

      - default_version = image.versions[:main]
      = image_tag default_version && default_version.url || image.url
      %br
      = form.check_box "remove_#{field.name}"
      = form.label "remove_#{field.name}", "Remove existing #{field.label.downcase}", :class => "inline"
  .row
    = form.file_field field.name, :class => "fileUploadField #{field.has_errors? ? "errorField" : nil}"
    = form.hidden_field "#{field.name}_cache"
#config/initializers/rails_admin.rb


# Register a custom field factory and field type for CarrierWave if its defined

if defined?(::CarrierWave)
  module RailsAdmin::Config::Fields::Types
    # Field type that supports CarrierWave file uploads

    class CarrierWaveFile < RailsAdmin::Config::Fields::Types::FileUpload
      register_instance_option(:partial) do
        :form_carrier_wave_file
      end
    end
    
    # Field type that supports CarrierWave file uploads with image preview

    class CarrierWaveImage < CarrierWaveFile
      register_instance_option(:partial) do
        :form_carrier_wave_image
      end
    end
    
    # Register field type to the types registry

    register(:carrier_wave_file, CarrierWaveFile)
    register(:carrier_wave_image, CarrierWaveImage)
  end
  RailsAdmin::Config::Fields.register_factory do |parent, properties, fields|
    model = parent.abstract_model.model
    if model.kind_of?(CarrierWave::Mount) && model.uploaders.include?(properties[:name])
      type = properties[:name] =~ /image|picture|thumb/ ? :carrier_wave_image : :carrier_wave_file
      fields << RailsAdmin::Config::Fields::Types.load(type).new(parent, properties[:name], properties)
      true
    else
      false
    end
  end
end

修复安装gems时Errno::ETIMEDOUT: Operation timed out - connect(2)的错误

这两天更新gems出现下面的错误

➜  ~  gem install rails      
ERROR:  Could not find a valid gem 'rails' (>= 0) in any repository
ERROR:  While executing gem ... (Gem::RemoteFetcher::FetchError)
    Errno::ETIMEDOUT: Connection timed out - connect(2) (http://rubygems.org/latest_specs.4.8.gz)

经检查和GFW无关,是rubygems的DNS
调整问题

问题解决的最好方法方法

使用google的DNS
8.8.8.8 / 8.8.4.4

另一种解决方式

修改rubygems的source源

#删除原有gem source

gem source -r http://rubygems.org/
gem source -r http://production.s3.rubygems.org/ 

#增加新source源

gem source -a  http://production.s3.rubygems.org.s3.amazonaws.com/

建立sproutcore应用

sproutcore是通过rubygems来安装的

gem install sproutcore

建立应用

sc-init HelloWorld

启动应用

cd HelloWorld
sc-server

便会通过启动thin在locahost:4020提供应用服务

ubutnu配置rvm,nginx和passenger的生产环境

下述内容参考了A Guide to a Nginx, Passenger and RVM Server

首先, 使用 root 帐号登录,

安装git和curl

apt-get install curl git-core

使用脚本安装rvm

bash < <(curl -L http://bit.ly/rvm-install-system-wide)

脚本会自动创建一个rvm组,并将root用户加入

编辑 /root/.bashrc和/etc/skel/.bashrc

[ -z "$PS!"]  && return 

替换为

if [[ -n "$PS1" ]]; then

在文件最后加入

fi
if groups | grep -q rvm ; then
  source "/usr/local/lib/rvm"
fi

配置用户

#增加zool用户

adduser zool
#将zool加入rvm组

adduser zool rvm

登录zool用户并测试

type rvm | head -n1

如果显示 rvm is a function 则表示安装正确

安装ree依赖组件

aptitude install build-essential bison openssl libreadline5 libreadline-dev \

curl git-core zlib1g zlib1g-dev libssl-dev vim libsqlite3-0 libsqlite3-dev \

sqlite3 libreadline-dev libxml2-dev git-core subversion autoconf

安装ree

rvm install ree

设为默认环境

rvm use ree --default

安装passenger和nginx

gem install passenger
rvmsudo passenger-install-nginx-module

配置nginx里的ruby环境

passenger_root /usr/local/rvm/gems/ree-1.8.7-2010.02/gems/passenger-3.0.0;
passenger_ruby /usr/local/rvm/wrappers/ree-1.8.7-2010.02/ruby;

设置nginx开机脚本

curl -L http://bit.ly/nginx-ubuntu-init-file > /etc/init.d/nginx
chmod +x /etc/init.d/nginx
update-rc.d nginx defaults
/etc/init.d/nginx start

原文中后面的step6,7关于Capistrano的环境配置以后再另文详述

rails的定时任务插件whenever

在做web应用时,有时会需要定时做一些操作,如发邮件,统计信息等。
这些都是需要放在后台来执行, whenever就是这样的一个插件,使用ruby强大的DSL, 高效的配置生成定时任务。
注意,whenever使用的是crontab定时器,所以这个gem在windows上无效。

github地址

安装

gem 'whenever', :require => false

开始配置

cd /path/to/myapp/
wheneverize .
#会在config目录下生成一个schedule.rb文件

配置文件说明

每个配置都是在一个叫every的block里面配置
运行频率 .minutes, .hours, .days, .months
可以运行任务 runner rake command 三种

例子

#每隔10分钟运行一次

every 10.minutes do
  #等同于 rails runner MyModel.some_process

  runner "MyModel.some_process"
  #等同于 rake my:rake:task

  rake "my:rake:task"  
  #等同于在终端执行 /usr/bin/my_great_command

  command "/usr/bin/my_great_command" 
end

whenever默认使用production环境,可以在配置文件里另外定义

  set :environment, :autotest
  #或单独指定

  runner "MyModel.some_process", :environment => :autotest

高级配置

使用at参数来指定分钟

#每隔两个小时23分钟

every 2.hours, :at => 23 do
#每隔两天在上午4:30

every 2.days, :at => '4:30am' do
#每周五晚从05:00到23:45每隔15分钟

every :friday, :at => ('05'..'23').to_a.collect {|x| ["#{x}:00","#{x}:15","#{x}:30","#{x}:45"]}.flatten do

与Capistrano结合

编辑Capistrano的配置文件config/deploy.rb, 加入

require "whenever/capistrano"
...
after "deploy:symlink", "deploy:update_crontab"
  namespace :deploy do
    desc "Update the crontab file"
    task :update_crontab, :roles => :db do
      run "cd #{release_path} && whenever --update-crontab #{application}"
    end
  end

rails中对时间的操作方法

做web应用,和时间打交道是不可免的。rails对ruby的时间模块做了扩展。
本文作于2011年1月29日, ruby版本为1.8.7, rails版本为3.0.3

基本的时间转换

>> now=Time.now
=> Sat Jan 29 21:47:07 0800 2011
#utc秒数互相转换

>> now.to_i
=> 1296308827
>> Time.at(1296308827)
=> Sat Jan 29 21:47:07 0800 2011
#当前时间的一些变量

>> now.sec
=> 7
>> now.min
=> 47
>> now.hour
=> 21
>> now.month
=> 1
>> now.year
=> 2011
#现在是星期几(注意!!!周日是返回 0 )

>> now.wday
=> 6
#现在是本月第几天

>> now.day
=> 29
#现在是今年第几天

>> now.yday
=> 29
#时间参数的数组

>> now.to_a
=> [7, 47, 21, 29, 1, 2011, 6, 29, false, "CST"]

时间化输出

>> now.strftime("%Y-%m-%d %H:%M:%S")
=> "2011-01-29 21:47:07"

参数解释如下

  %a - 星期几的英文简写 (``Sun'')
  %A - 星期几的英文全称 (``Sunday'')
  %b - 月份的英文简写 (``Jan'')
  %B - 月份的英文全称 (``January'')
  %c - 默认的首选本地时间输出格式
  %d - 本月第几天 (01..31)
  %H - 24小时制的小时 (00..23)
  %I - 12小时制的小时 (01..12)
  %j - 今年的第几天 (001..366)
  %m - 月份 (01..12)
  %M - 分钟 (00..59)
  %p - 上午还是下午 (``AM''  or  ``PM'')
  %S - 秒数 (00..60)
  %U - 从星期天算一周开始的本年第几周 (00..53)
  %W - 从星期一算一周开始的本年第几周 (00..53)
  %w - 现在是星期几 (周日是0 , 0..6)
  %x - 默认的日期输出格式 ("01/29/11")
  %X - 默认的时间输出格式 ("21:47:07")
  %y - 年份的后两位 (00..99)
  %Y - 年份
  %Z - 时区名
  %% - 输出%字符

以上是ruby的基本方法,rails对其做了更多的扩展

#重写了to_s方法,能够接受参数

>> now.to_s
=> "Sat Jan 29 21:47:07 +0800 2011"
>> now.to_s(:db)
=> "2011-01-29 21:47:07"
>> now.to_s(:number)
=> "20110129214707"
>> now.to_s(:time)
=> "21:47"
>> now.to_s(:short)
=> "29 Jan 21:47"
>> now.to_s(:long)
=> "January 29, 2011 21:47"
>> now.to_s(:long_ordinal)
=> "January 29th, 2011 21:47"
>> now.to_s(:rfc822)
=> "Sat, 29 Jan 2011 21:47:07 +0800"

如果要自己设计时间输出格式,按下面方法来,新建一个配置文件

  # config/initializers/time_formats.rb

  Time::DATE_FORMATS[:month_and_year] = "%B %Y"
  Time::DATE_FORMATS[:short_ordinal] = lambda { |time| time.strftime("%B #{time.day.ordinalize}") }

rails对日期的一些扩展

#指定时间

>> now.change(:year=>2012, :month=>12, :day => 21, :hour => 0, :min => 0, :sec => 0, :usec => 0)
=> Fri Dec 21 00:00:00 0800 2012

#begginning家族

>> now.beginning_of_day
=> Sat Jan 29 00:00:00 0800 2011
>> now.midnight
=> Sat Jan 29 00:00:00 0800 2011
>> now.beginning_of_week
=> Mon Jan 24 00:00:00 0800 2011
>> now.beginning_of_month
=> Sat Jan 01 00:00:00 0800 2011
>> now.beginning_of_quarter
=> Sat Jan 01 00:00:00 0800 2011
>> now.beginning_of_year
=> Sat Jan 01 00:00:00 0800 2011
#end家族

>> now.end_of_day
=> Sat Jan 29 23:59:59 0800 2011
>> now.end_of_week
=> Sun Jan 30 23:59:59 0800 2011
>> now.end_of_month
=> Mon Jan 31 23:59:59 0800 2011
>> now.end_of_quarter
=> Thu Mar 31 23:59:59 0800 2011
>> now.end_of_year
=> Sat Dec 31 23:59:59 0800 2011
#时间的魔术方法

>> now.yesterday
=> Fri Jan 28 21:47:07 0800 2011
>> now.tomorrow
=> Sun Jan 30 21:47:07 0800 2011
>> now.next_week
=> Mon Jan 31 00:00:00 0800 2011
>> now.next_month
=> Mon Feb 28 21:47:07 0800 2011
>> now.next_year
#注意没有prev_week

>> now.prev_month
=> Wed Dec 29 21:47:07 0800 2010
>> now.prev_year
=> Fri Jan 29 21:47:07 0800 2010
#今日已过秒数

>> now.seconds_since_midnight
=> 78427.615017
#日期输出

>> now.to_date
=> Sat, 29 Jan 2011
>> now.to_datetime
=> Sat, 29 Jan 2011 21:47:07 0800
#按秒数计算

>> now.ago(3600)
=> Sat Jan 29 20:47:07 0800 2011
>> now.since(3600)
=> Sat Jan 29 22:47:07 0800 2011

实际上还有很多方法没有列出,具体使用还是参考rails的api手册为准。

另外有一个rails插件bystar对此做了更多的扩展, 后面会另外写一篇文章来说明

使用to_lang翻译ruby字符串

github地址

我的博客就是用这个gem来翻译文章标题的

安装

gem install to_lang

使用

ToLang必须初始配置一个google api key

api key 获取地址

require to_lang
ToLang.start(YOUR_GOOGLE_TRANSLATE_API_KEY)

然后就可以变魔术了

 > '你好'.to_english
 => "Hello" 
 > 'hotfix'.to_simplified_chinese
 => "修复" 
 > "Rails 有非常強大的路徑指派功能,讓我們看看有哪些設定方式吧".to_simplified_chinese_from_traditional_chinese
 => "Rails 有非常强大的路径指派功能,让我们看看有哪些设定方式吧" 

也可以直接用String#translate方法

hello world.translate(es)
=> hola mundo
a pie.translate(es, :from => en)
=> un pastel

所有支持的语言

to_afrikaans
to_albanian
to_arabic
to_basque
to_belarusian
to_bulgarian
to_catalan
to_simplified_chinese
to_traditional_chinese
to_croatian
to_czech
to_danish
to_dutch
to_english
to_estonian
to_filipino
to_finnish
to_french
to_galician
to_german
to_greek
to_haitian_creole
to_hebrew
to_hindi
to_hungarian
to_icelandic
to_indonesian
to_irish
to_italian
to_japanese
to_latvian
to_lithuanian
to_macedonian
to_malay
to_maltese
to_norwegian
to_persian
to_polish
to_portuguese
to_romanian
to_russian
to_serbian
to_slovak
to_slovenian
to_spanish
to_swahili
to_swedish
to_thai
to_turkish
to_ukrainian
to_vietnamese
to_welsh
to_yiddish

生成rails项目的实体关系图

实体关系图 == Entity-Relationship Diagrams

插件官网

首先安装Graphviz

% brew install cairo pango graphviz    # Homebrew on Mac OS X

% sudo port install graphviz           # Macports on Mac OS X

% sudo aptitude install graphviz       # Debian and Ubuntu

然后在开发环境中使用

group :development do
  gem "rails-erd"
end

安装

% bundle install

生成PDF

% rake erd

我的autotest配置

放在 ~/.autotest里, 起到统一配置

其中我没有用mac,所以注释掉了growl的相关配置

#require "autotest/growl"

#require 'redgreen/autotest'

require "autotest/restart"
require 'autotest/timestamp'
require 'autotest_notification'
SPEAKING = false
DOOM_EDITION = false
BUUF = false
PENDING = false
STICKY = false
SUCCESS_SOUND = ''
FAILURE_SOUND = ''


Autotest.add_hook :initialize do |autotest|
  %w{.git .svn .hg .DS_Store ._* vendor tmp log doc}.each do |exception|
    autotest.add_exception(exception)
  end
end
#

#module Autotest::Growl

#

#  def self.growl title, msg, img, pri=0, stick="" 

#    system "growlnotify -n autotest --image #{img} -p #{pri} -m #{ msg.inspect} #{title} #{stick}" 

#  end

#  #

#  Autotest.add_hook :ran_command do |autotest|

#    results = [autotest.results].flatten.join("\n")

#    output = results.slice(/(\d+)\s+examples?,\s*(\d+)\s+failures?(,\s*(\d+)\s+pending)?/) 

#    if output  =~ /[1-9]\sfailures?/

#      growl "FAIL:", "#{output}", "~/Library/autotest/fail.png", 2, "-s" 

#    elsif output  =~ /[1-9]\spending?/

#      growl "PENDING:", "#{output}", "~/Library/autotest/pending.png", 2, "-s" 

#    else

#      growl "PASS:", "#{output}", "~/Library/autotest/pass.png" 

#    end

#  end

#

#end

使用sitemap_generator来为rails网站生成Sitemap

github地址

sitemap描述了网站的页面架构,请看 维基百科

  • 安装

编辑Gemfile

gem 'sitemap_generator'

bundle install安装完成之后, 执行

rake sitemap:install

会在config目录下生成sitemap.rb

*配置

将SitemapGenerator::Sitemap.default_host = “http://www.example.comurl改为自己的网站url”里的

通过下列方法,可以将所有文章生成出去

Post.all.each do |a|
    sitemap.add post_path(a), :lastmod => a.updated_at
  end

*生成

在crontab定时器里运行下列命令

rake sitemap:refresh

就会生成sitemap并且向搜索引擎进行提交

使用bullet来处理rails开发中的N + 1查询问题

github地址

在开发中,有时会碰到N + 1查询问题。

比如说,在Blog显示文章时, 文章的作者是由关联查询得出

#home_controller

@posts = Post.paginate :page => params[:page], :order => 'created_at DESC'

#views

@posts.each do |post|
..............
post.user.username
............

这样,每一篇文章都会有一个查询,怎么来改进代码呢?

首先,先安装bullet

group :development do
 gem 'bullet'
end

然后在config/environments/development.rb加入下面代码

  Bullet.enable = true
  Bullet.alert = true
  Bullet.bullet_logger = true
  Bullet.console = true
  Bullet.growl = false
  Bullet.rails_logger = true
  Bullet.disable_browser_cache = true

重启服务器

之后重新访问页面时就会弹出页面来提示你,当前页面有N+1问题,可以用:include => [:user]来解决

重新编辑home_controller

@posts = Post.paginate :page => params[:page], :order => 'created_at DESC', :include => [:user]

问题解决

使用Annotate为rails项目生成model的大纲

有时候在写代码时,想不起来当前model的字段属性了,annotate帮你忙。

annotate可以以注释的方式在你model文件的底部生成model的大纲(schema)信息

安装

gem install annotate

生成

cd /path/to/app/
annotate

便会生成下面的注释

# == Schema Information

#

# Table name: users

#

#  id                   :integer(4)      not null, primary key

#  email                :string(255)     default(""), not null

#  encrypted_password   :string(128)     default(""), not null

#  username             :string(255)     not null

#  reset_password_token :string(255)

#  remember_created_at  :datetime

#  sign_in_count        :integer(4)      default(0)

#  current_sign_in_at   :datetime

#  last_sign_in_at      :datetime

#  current_sign_in_ip   :string(255)

#  last_sign_in_ip      :string(255)

#  password_salt        :string(255)

打造你的加强版irb控制台

github地址

安装步骤

下载

git clone git://github.com/logankoester/irbrc.git

安装相关gems

(cd irbrc; rvm gemset import irbrc.gems)

如果没有装rvm,直接运行

 sudo gem install awesome_print bond hirb looksee map_by_method net-http-spy sketches what_methods wirble 

做文件连接

ln -s ~/irbrc/irbrc ~/.irbrc

运行irb

功能介绍

  1. 输出代码高亮

  2. irb运行历史记录,下次打开仍保留

  3. 将irb命令行提示缩短为 '>>'

  4. 输入'c'或'clear'清屏

  5. 可以通过tab实现代码补全

  6. 使用 fl(file_name) 命令来快速打开文件, rl 命令来重新打开最近文件, rt命令来打开最近文件并重新执行上一条语句

  7. pm方法,可以很漂亮的列出Object的所有methods

  8. 自动加载rubygems, 并加载下面几个gems

  • map_by_method
>a = ["1", "2", "3"]

>a.map_by_to_i

> => [1, 2, 3]

   实际上相当于 a.map &:to_i, 但更dsl点不是更好?
  • what_methods

猜方法名专用

>3.14.what? 3  #什么方法返回3?                                             

> 3.14.to_int == 3                                              
> 3.14.floor == 3                                               
> 3.14.round == 3                                               
> 3.14.to_i == 3                                                
> 3.14.prec_i == 3                                              
> 3.14.truncate == 3                                            
> => ["to_int", "floor", "round", "to_i", "prec_i", "truncate"] 
  • pp

用法 ap Object, 把一个Object格式华高亮输出

  • Sketches

可以在irb中使用文字编辑器, 可以参看 ihower的这篇文章

经实际测试,在使用what_methods时不知什么原因会自动打开sketches,可以编辑~/.irbrc,将135-136的sketeches代码注释掉

gem install mysql2 报错

在服务器上安装mysql时,报错,安装失败, 内容如下

> sudo gem install mysql  
> Building native extensions.  This could take a while...   
> ERROR:  Error installing mysql:  
> ERROR: Failed to build gem native extension.  
> /usr/local/bin/ruby extconf.rb install mysql     
> checking for mysql_query() in -lmysqlclient... no      
> checking for main() in -lm... yes   
> checking for mysql_query() in -lmysqlclient... no   
> checking for main() in -lz... yes   
> checking for mysql_query() in -lmysqlclient... no   
> checking for main() in -lsocket... no   
> checking for mysql_query() in -lmysqlclient... no   
> checking for main() in -lnsl... yes   
> checking for mysql_query() in -lmysqlclient... no   
> extconf.rb failed  
> Could not create Makefile due to some reason, probably lack of   
> necessary libraries and/or headers.  Check the mkmf.log file for more   
> details.  You may need configuration options.   

> Provided configuration options:   
>    --with-opt-dir   
>    --without-opt-dir   
>    --with-opt-include   
>    --without-opt-include=${opt-dir}/include   
>    --with-opt-lib   
>    --without-opt-lib=${opt-dir}/lib   
>    --with-make-prog   
>    --without-make-prog 
>    --srcdir=. 
>    --curdir 
>    --ruby=/usr/local/bin/ruby 
>    --with-mysql-config 
>    --without-mysql-config 
>    --with-mysql-dir 
>    --without-mysql-dir   
>    --with-mysql-include   
>    --without-mysql-include=${mysql-dir}/include   
>    --with-mysql-lib   
>    --without-mysql-lib=${mysql-dir}/lib   
>    --with-mysqlclientlib   
>    --without-mysqlclientlib   
>    --with-mlib   
>    --without-mlib   
>    --with-mysqlclientlib   
>    --without-mysqlclientlib   
>    --with-zlib   
>    --without-zlib   
>    --with-mysqlclientlib   
>    --without-mysqlclientlib   
>    --with-socketlib   
>    --without-socketlib   
>    --with-mysqlclientlib   
>    --without-mysqlclientlib   
>    --with-nsllib   
>    --without-nsllib   
>    --with-mysqlclientlib   
>    --without-mysqlclientlib    

经检查,是由于我将mysql调整了安装目录导致, 执行下面代码后安装成功.

sudo gem install mysql -- --with-mysql-config=/usr/local/mysql/bin/mysql_config