HeadFirst Ruby 第十四章总结 Web apps: Serving HTML

前言

这一章节主要讲了如何利用 Ruby 中的 Sinatra 这个 gem 来创建一个 Web app 的具体流程,其中的要点包括了:

  1. Sinatra, a third party library for writing web applications
  2. RubyGems,a platform which can download and install libraries automatically.
  3. erb, a HTML type of file which has Ruby's functions 

HTTP 相关知识

Ruby 与 HTTP 的关系

In the early day of the Web, the server usually read the contents of an HTML file on the server's hard drive, and sent that HTML back to the browser.

But today, it's much common for the server to communicate with a program to fulfill the request, instead of reading from a file.

 

URL 和 port

关于 WEBrick

定义:WEBrick 属于 Ruby Standard library,它的功能是创建一个 Web Server
当我们运行我们的 Sinatra app 的时候, 这个 Web server 也随之启动.
性质:它的 Host 名为 localhost, 即自己的电脑成为 Web Server, port 号默认为 4567,可进行改动.

关于 Sinatra routes

定义: 即 Web 应用程序的反馈程序段.
要求:需要得到两个信息:

  1. type of HTTP request: 四种 HTTP 请求中的一种: GET、POST、PUT、DELETE
  2. path: URL 的 path 部分

格式:

require 'sinatra'

get('/hello') do
'Hello, web!'
end

其中的 get 为对应的 HTTP 中的 get 请求的所提供的 response 的方法.
(‘/hello') 为对 Ruby 程序 的 request 的内容.

关于 RubyGems & 下载安装 Sinatra

原因:曾经安装 Ruby 的 Library 需要经过解压、找放置的文件夹等重复的操作,于是 RubyGems 应运而生.
RubyGems 伴随着 Ruby 一起安装,因此是免安装的.
使用方法: 在 Command-line tool 中进行下载,自动完成解压和存放的任务.
格式: (sudo) gem install sinatra
术语:gem, RubyGems 中的一个 Library.

关于 erb(Embedded Ruby) 这个 method

定义 & ERB library

erb: 是 Sinatra 中的一个 method, 这个 method 可以让我们通过能够通过 Ruby 程序(即 SInatra) 来显示 HTML 网页
ERB library: 是 part of Ruby standard library, 它能够 let you embed Ruby code with the HTML file
要求:

  1. In default, erb method 会在名为 views 这个 subdirectory 中寻找对应的 HTML 文件,并且==》
  2. HTML 文件的后缀应该为 .erb

格式

get('/movies') do
erb :index
end

ERB embedding tags

起因:在 .erb 文件中,不能直接将 Ruby 代码写入 HTML 代码中,而应该使用 ERB embedding tags.
功能:在加载 ERB templates 的同时, erb 这个 method 同时也会计算 ERB embedding tags 所包含的内容.

第一种:ERB output embedding tag

格式:<%= %>,示例如下

<li><%= "A string" %> </li>
<li><%= 15.0 / 6.0 %> </li>
<li><%= Time.now %> </li>

步骤:

  1. 当 erb 进行运行的时候,看到“<% = >" 格式的 tag 的时候,就会 evaluate 其中的 code
  2. 返回结果, 并将其 convert into a string
  3. 最后插入这个 string 来代替这个 tag

第二种: The regular embedding tag

格式: <% %>,示例如下:

<% [1,2,3].each do |number| %>
<li><%= number %></li>
<% end %>

与 output tag 不同之处:

  1. the results of the code will not be directly insert into the ERB output
  2. 通常用于循环语句和条件语句中.





猜你喜欢

转载自www.cnblogs.com/FBsharl/p/10616440.html