Ruby on Rails介紹

Harry Yuan
Title Text
Ruby?

>> 直譯式
>> 物件導向
>> 日本松本行弘開發的(1995年)
>> 因為Rails而紅起來
融合Lisp、Perl等語言的要素
主要是希望可以站在人的角度寫
Ruby


1. indentation、end來表示區塊(似python)
Ruby


Ruby



2. 只有單引數,可以不用括號
Ruby

3. 最後一行是return值就可以不用寫return

puts “會換行”
print “不會換行”
Ruby - HelloWorld


Ruby的變數:弱型別
Ruby - 變數

| 區域變數 | a=5 | 
| 全域變數 | $a=5 | 
| class instance變數 | @a=5 | 
| class全域變數 | @@a=5 | 
Title Text
Ruby - 條件


if cond
...
elsif cond
...
else
  ...
end
1. 單個 if可以寫後面
2. 三元運算子
Ruby - 條件


Title Text
Ruby - 條件

case 變數
when 值1
when 值2
else
end

Title Text
Ruby - 常用型態

int
boolean
symbol = hash的key
Array
Hash

Who gives a Fuck about rails??????

方便性還是屌打個方
>> 第三方api的component很多
>> 開發快速(rails new/rails generate/....)
>> 資料庫存取方便
>> 支援很多frontend套件
>> 資源管理方便(javascript/內建scss)
...
Gems還是有很多人開發

MVC架構
Text
| 元件 | 功能 | 在ruby裡面誰負責 | 說明 | 
|---|---|---|---|
| Model | 定義資料結構/資料庫聯繫 | ActiveRecord | 內建ORM,不用下sql | 
| View | 顯示畫面來給使用者看 | index.html.erb | >> 在html中可以使用ruby語法 >> 很像ejs | 
| Controller | 處理網址要求/運算 | xxx_controller.rb | 要先定義路由才能用 | 



Rails檔案架構
...
...
剛裝完東西很多,但不要怕!

Rails檔案架構
>> 找到MVC所用到的檔案


←這個
←這個
←這個

Controller

內建有一個application_controller.rb
所有controller執行都會經過他

Controller
使用前要定義routes(外面的人網址怎麼連進來)
>> app/config/routes.rb


Controller - 基礎路由(route)
root "你的controller#你的action"
get "/", controller:"home", action: "index"
post "/", controller: "home", action: "add_something"


Controllers
Text
| 物件 | 說明 | 
| controller | 處理要求的檔案 | 
| action | 實際上處理要求的動作 | 
| params | 要求的參數物件 | 

Controllers
Text

rails generate controller Home

View
剛剛有controller之後,會產生 app/views/controller名稱


View


View - ERB檔案


View - ERB檔案
想要自己設計view
可以來定義我們的view檔案
在/home裡面建立index.html.erb
打上hello world就好
‼️ 檔案的名字,會對應到home controller的index這個action


View - ERB檔案
若你今天想要用自己的view檔案
在index那個action那邊
記得要把render刪除
不然render會搶先印他的畫面
就不會理你的index.html.erb

View - ERB檔案




View - ERB檔案




View - ERB檔案




Model有點多下次講

brew install ruby
gem install rails
rails new app_名稱
實作

裝好之後,建一個自己的route跟頁面就好
實作
Ruby on Rails介紹
By Harry Yuan
Ruby on Rails介紹
- 215
 
  