Ruby入門--Linux/Windows下的安裝、代碼開發及Rails實戰


Ruby入門--Linux/Windows下的安裝、代碼開發及Rails實戰

http://www.linuxidc.com/Linux/2014-04/100242.htm

Ubuntu 13.04下Ruby的安裝 http://www.linuxidc.com/Linux/2013-06/85734.htm

公司有項目組進行系統重構,采用了Ruby On Rails框架,我也抽出時間學習了一下,並對幾個原來用Java開發的定時任務、消息監聽進行了ruby改造,學習過程中主要參考兩本書:《Programming Ruby中文版(第二版)》 (下載見http://www.linuxidc.com/Linux/2014-04/100254.htm )、《Ruby on Rails教程》(PDF下載見 http://www.linuxidc.com/Linux/2014-04/100253.htm ),開發工具:vim、RubyMine。 

安裝 

Linux下:安裝RVM和GEM后,之后所有的安裝,都可以交給RVM和GEM了,安裝RVM默認會裝好GEM。

(1)curl -L https://get.rvm.io | bash -s stable

(2)source /etc/profile.d/rvm.sh ,這個腳本的目的是把rvm相關加入$PATH路徑

安裝完畢后界面如下(這個是從github下載代碼,國內非常慢,多嘗試幾次):

安裝RVM之后,安裝ruby組件:

(1)安裝ruby:rvm install ruby

這一步rvm會幫我們自動安裝很多linux依賴包(如果linx本身沒有的話),如果自動裝不上,也可以根據屏幕提示收到安裝,比如可能有提示進行如下安裝:

yum install -y libyaml-devel autoconf gcc-c++ readline-devel zlib-devel openssl-devel automake libtool bison

網速不好,機器太爛(比如我的單CPU1G內存虛擬機),可能會花很多時間(比如2個小時),先有個心理准備大笑

(2)安裝rails:gem install rails

輸入ruby -v ,顯示ruby的版本,可以看到ruby已經裝好。

我們也可以通過which ruby,查看ruby程序的位置。之所以直接輸入ruby就能運行,是因為rvm已經把ruby加到$PATH環境變量中了。

我們輸入echo $PATH,可以看到$PATH環境變量中已經包含ruby的路徑了,如下:/usr/local/rvm/bin 。 

HelloWorld 

使用irb,寫出第一行代碼:puts "Hello, World!"

也可以編輯一個文件:test.rb,內容也只有一行:puts "Hello,World",然后再命令行運行:ruby test.rb,可以看到輸出了正確的結果。

我們也可以這樣設置test.rb,內容如下:

#!/usr/local/rvm/bin/ruby

puts "Hello,World"

然后再命令行給test.rb可執行的權限:chmod 777 test.rb,然后我們在命令行輸入:./test.rb,可以看到,輸出了正確的結果。

Mysql devel&client組件 

(1)yum -y install mysql-devel

由於我的rhel6.2機器yum下面有錯誤的.repo文件,導致我一直連不上yum源服務器,執行了如下操作:

cd /etc/yum.repos.d/

rm -fr 無用的.repo文件

yum clean all

vim /etc/yum.repos.d/rhel-source.repo(這個文件的內容如下)

[rhel-source]
name=Red Hat Enterprise Linux $releasever - $basearch - Source
baseurl=http://192.168.1.11/yum/
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-RedHat-release

[rhel-source-beta]
name=Red Hat Enterprise Linux $releasever Beta - $basearch - Source
baseurl=ftp://ftp.redhat.com/pub/redhat/linux/beta/$releasever/en/os/SRPMS/
enabled=0
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-beta,file:///etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-release

(2)gem install mysql2 

經過以上兩步,就可以連接mysql數據庫了,例子代碼如下:

require 'mysql2'
class Test
        def initialize
        @db = Mysql2::Client.new(:host => "192.168.211.245",
                                        :port => 3306,
                                        :username => "mysql",
                                        :password => "mysql",
                                        :database => "yitian_b2c_db")
                puts "a"
        end
end
if __FILE__ == $0
        test = Test.new
end

定時任務組件 rufus-scheduler

支持cron表達式,參考網址:http://www.linuxidc.com/Linux/2014-04/100244.htm

先安裝:gem install rufus-scheduler

log4r

require 'logger' 就可以使用了,參考網址: http://www.linuxidc.com/Linux/2014-04/100249.htm

xml操作

例子代碼如下:

buffer = "";
x = Builder::XmlMarkup.new(:target => buffer, :indent => 1)
x.instruct! :xml,:version => '1.0',:encoding =>'UTF-8'
x.comment! "書本信息"
x.library("shelf" => "Recent Acquisitions") {
x.section("name" => "ruby"){
x.book("isbn" => "0672310001"){
x.title "Programming Ruby"
x.author "Yukihiro"
x.description"Programming Ruby-
The Pramatic Programmer's Guide"
}
}
}
puts buffer
fh = File.new("xml.xml","w")
fh.puts buffer
fh.close

參考網址:

http://builder.rubyforge.org/

http://www.linuxidc.com/Linux/2014-04/100243.htm

http://www.linuxidc.com/Linux/2014-04/100248.htm

hessian

安裝hessian:gem install hessian2

hessian代碼示例:

require 'hessian2'

client = Hessian2::HessianClient.new(url)

client.xxx

程序完成及部署

源代碼下載地址: http://pan.baidu.com/s/1dDejscx

歷時3天,完成我的第一個ruby程序,是改寫的一個定時xml生成程序,干的不錯!

一點小經驗積累,如下:

initialize里面,打開數據庫連接,是不可取的。如果程序執行很長時間,下次來用這個連接時,可能已經關閉了,最好用時open,用完close,不知道ruby里面有沒有連接池的概念,可以進一步提高性能;

測試環境實踐發現,hessian協議性能貌似低於dubbo協議,大約dubbo 2-3倍於 hessian,這個程序是2.6倍,很簡單的請求,平均dubbo一次是4-5毫秒,hessian一次是11-12毫秒;

生產環境實際運行,hessian協議性能貌似和dubbo協議基本一致,運行了約20萬次,總計消耗時間7分鍾和8分鍾的區別。

RabbitMQ的Ruby客戶端:bunny

安裝:gem install bunny

開始Rails之旅 

推薦PDF教程: http://www.linuxidc.com/Linux/2014-04/100253.htm 有這個可以說足夠了。 

sqllite 

Linux機器可能沒有安裝Sqllite-devel,安裝一下吧:yum install sqlite-devel 

JavaScript服務器解釋引擎 

linux機器可能沒有安裝JavaScript的服務器解釋引擎,安裝一下吧:gem install execjs gem install therubyracer,貌似這兩步之后也不行,我的機器是REHL6.2,需要安裝node.js才行,步驟如下:

wget http://nodejs.org/dist/v0.10.5/node-v0.10.5.tar.gz
tar xfv node-v0.10.5.tar.gz
cd node-v0.10.5
./configure
make
make install

參考文章:http://www.linuxidc.com/Linux/2014-04/100252.htm

Git 

Git安裝:

Getting Started - Installing Git

Installing Git

Let’s get into using some Git. First things first—you have to install it. You can get it a number of ways; the two major ones are to install it from source or to install an existing package for your platform.

Installing from Source

If you can, it’s generally useful to install Git from source, because you’ll get the most recent version. Each version of Git tends to include useful UI enhancements, so getting the latest version is often the best route if you feel comfortable compiling software from source. It is also the case that many Linux distributions contain very old packages; so unless you’re on a very up-to-date distro or are using backports, installing from source may be the best bet.

To install Git, you need to have the following libraries that Git depends on: curl, zlib, openssl, expat, and libiconv. For example, if you’re on a system that has yum (such as Fedora) or apt-get (such as a Debian based system), you can use one of these commands to install all of the dependencies:

$ yum install curl-devel expat-devel gettext-devel   openssl-devel zlib-devel

$ apt-get install libcurl4-gnutls-dev libexpat1-dev gettext   libz-dev libssl-dev

When you have all the necessary dependencies, you can go ahead and grab the latest snapshot from the Git web site:

http://git-scm.com/download

Then, compile and install:

$ tar -zxf git-1.7.2.2.tar.gz
$ cd git-1.7.2.2
$ make prefix=/usr/local all
$ sudo make prefix=/usr/local install

After this is done, you can also get Git via Git itself for updates:

$ git clone git://git.kernel.org/pub/scm/git/git.git

Installing on Linux

If you want to install Git on Linux via a binary installer, you can generally do so through the basic package-management tool that comes with your distribution. If you’re on Fedora, you can use yum:

$ yum install git-core

Or if you’re on a Debian-based distribution like Ubuntu, try apt-get:

$ apt-get install git

Installing on Mac

There are two easy ways to install Git on a Mac. The easiest is to use the graphical Git installer, which you can download from the Google Code page (see Figure 1-7):

http://code.google.com/p/git-osx-installer


Figure 1-7. Git OS X installer.

 

The other major way is to install Git via MacPorts (http://www.macports.org). If you have MacPorts installed, install Git via

$ sudo port install git-core +svn +doc +bash_completion +gitweb

You don’t have to add all the extras, but you’ll probably want to include +svn in case you ever have to use Git with Subversion repositories (see Chapter 8).

Installing on Windows

Installing Git on Windows is very easy. The msysGit project has one of the easier installation procedures. Simply download the installer exe file from the GitHub page, and run it:

http://msysgit.github.com/

After it’s installed, you have both a command-line version (including an SSH client that will come in handy later) and the standard GUI.

Note on Windows usage: you should use Git with the provided msysGit shell (Unix style), it allows to use the complex lines of command given in this book. If you need, for some reason, to use the native Windows shell / command line console, you have to use double quotes instead of simple quotes (for parameters with spaces in them) and you must quote the parameters ending with the circumflex accent (^) if they are last on the line, as it is a continuation symbol in Windows.

Git配置與使用:與 推送到GitHub:教程見

注意:你必須先注冊一個GitHub.Com賬戶,如果使用SSH方式進行推送,則需要創建SSH秘鑰,需要在GitHub中建立Repository。

SSH推送到GitHub的命令如下:

git remote add origin git@github.com:<username>/first_app.git
$ git push -u origin master

<username>要替換成你在GitHub注冊的用戶名,master是你的分支名稱,現在我們可以在GitHub中看到這個master分支了:

https://github.com/pumadong/first_app

關於Git,在Windows及Mac下面,都有GUI程序可用,在linux下面,貌似只有git命令可用了。

建立一個Raise項目並推送到GitHub

 
 

發布到雲部署平台heroku

 
heroku.com注冊一個賬戶
wget https://toolbelt.heroku.com/install.sh --no-check-certificate
chmod +x install.sh
./install.sh
echo 'PATH="/usr/local/heroku/bin:$PATH"' >> /etc/profile
通過以上步驟,安裝完成heroku的linux客戶端,下面開始部署:
 
heroku login
cd /data/ruby/rails_project/first_app
heroku create
注意:執行這些命令,會自動把~/.ssh/id_rsa.pub里面的公鑰,寫到您的heroku賬戶的SSH Keys里面,如果有過ssh重新生成等,需要到賬戶里面更新。貌似heroku和github用的是一個公鑰。
下面,我們發布程序:git push heroku master ,正常的話,已經部署成功了,我的url如下:
http://damp-citadel-7023.herokuapp.com/
 

使用scoffold快速建立一個用戶微博程序

 
 

演示從頭到尾建立一個大型的示例程序

 
 

Windows下安裝

rubyinstaller 

安裝包下載地址:http://pan.baidu.com/s/1dDejscx

官網下載:http://rubyinstaller.org/downloads

執行rubyinstaller-2.0.0-p353-x64.exe,進行安裝,安裝完畢后,cmd里面執行:ruby -v,顯示版本號,說明ruby安裝成功;

執行gem -v,顯示版本號,說明RubyGems(Ruby程序包管理器)也已經被默認安裝好了;

DevKit 

安裝DevKit-mingw64-64-4.7.2-20130224-1432-sfx.exe,解壓到一個固定的位置,使用后不能變換位置,更多參考:

https://github.com/oneclick/rubyinstaller/wiki/Development-Kit

步驟大致如下:

1) 將下載 DevKit 解壓到 D:\DevKit 目錄。
2) 打開 CMD 窗口,進入 D:\DevKit 目錄,輸入ruby dk.rb init 。#生成config.yml,這里會檢查將要添加DevKit支持的Ruby列表,只支持通過RubyInstaller安裝的Ruby。
3) 輸入 ruby dk.rb install #開始安裝。
4) 輸入 ruby dk.rb review #檢查要添加DevKit支持的Ruby列表是否有誤,可以略過。
5) 輸入 gem install rdiscount --platform=ruby 。#這一步只是驗證DevKit是否安裝成功,如果能安裝rdiscount成功說明安裝DevKit成功,也可以不做。 

Rails 

安裝完以上后,可以安裝rails了:

從CMD提示窗口輸入指令:gem install rails 開始安裝rails。
如不想安裝文檔文件,可以輸入:gem install rails --no-rdoc --no-ri 
程序自動下載並安裝rails, 耐心等待。
安裝完成后,你可以在路徑 D:\Ruby\lib\ruby\gems\1.9.1\gems 看到些東西,都是rails的包文件,與ruby安裝在同一目錄下。
這時在CMD提示窗口輸入指令: rails -v 顯示rails的版本號。

參考網址:http://www.linuxidc.com/Linux/2014-04/100250htm

Mysql2

 
拷貝libmysql.dll、libmysql.lib到 D:\Ruby\bin目錄下,執行:
gem install mysql2 -- '--with-mysql-lib="E:\Program Files\MySQL\MySQL Server 5.5\lib" --with-mysql-include="E:\Program Files\MySQL\MySQL Server 5.5\include"'
或者
gem install mysql2 -- '--with-mysql-dir="E:\Program Files\MySQL\MySQL Server 5.5"'
就可以安裝成功了,但是使用時(require 'mysql2')報錯,如下圖:
 
 
出現的原因是的libmysql.lib和mingw64-gcc不兼容導致的,於是卸載mysql2:gem uninstall mysql2。
 
gendef.exe,這個從https://structure-svm-map.googlecode.com/files/svm-map-win.zip下載,解壓后在python-mingw-lib目錄里面。
拷貝到devkit/mingw/bin下,我之所以考到這里,是因為dlltool.exe也在這里,都放到path里方便。
然后運行:gendef.exe libmysql.dll。
這條命令會生成libmysql.def文件。
生成這個libmysql.def文件之后���就可以生成新的lib了。
dlltool -v –dllname libmysql.dll –def libmysql.def –output-lib libmysql.lib。
拷貝libmysql.lib到D:\Ruby\bin目錄下面,重新安裝,
都OK了。
 

注意事項 

如果在Windows下面編輯的文件,拿到Linux下面未必能正確運行,因為Windows的換行符到Linux里面是^M,而Linux的是$,對於Windows下面編輯的文件,可以用如下命令進行處理:
dos2unix ruby_start
是否是這種情況,可以通過:cat ruby_start -A看到
 
到現在,再Ruby的環境中,應該也浸淫了至少2周的時間了吧,對Ruby基本語法,運行環境,生態環境,應該都有一定了解了吧。
 
開始進入IDE的世界吧。就用RubyMine,現在的版本是6了。經過前幾周記事本寫代碼的世界,現在改用IDE,是不是發現工作變得輕松起來了呢。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM