Windows下安装Ruby和InstantRails
去http://instantrails.rubyforge.org/wiki/wiki.pl下载InstantRails并解压到一个目录
由于InstantRails自身就包含了Ruby解释器,所以不用另外再下载Ruby的Windows安装程序
运行InstantRails.exe,提示是否更改路径配置,选择是。
创建一个新程序
点击InstantRails窗口左上角的"I"->Rails Applications->Open Ruby Console Window
这时会打开一个位于InstantRails/rails_apps目录的Console,输入命令:
- rails demo
<script type="text/javascript">render_code();</script>
该命令创建了一个叫demo的程序,并创建了demo目录
demo目录下有README和Rakefile文件和app/compoments/config/db/doc/lib/log/public/script/test/tmp/vendor子目录
运行cd demo进入demo目录,然后运行以下命令:
- ruby script/server
<script type="text/javascript">render_code();</script>
你将看到Ruby自带的WEBrick服务器在localhost的3000端口启动了,现在打开浏览器看看效果http://localhost:3000
创建Controller
现在让我们创建一个Controller,运行以下命令:
- ruby script/generate controller Say
<script type="text/javascript">render_code();</script>
我们会看到系统又生成了一堆文件和目录,其中主要的文件为app/controllers/say_controller.rb
让我们编辑该文件:
- class SayController < ApplicationController
- def hello
- @time = Time.now
- end
- def goodbye
- end
- end
创建rhtml模板
Ruby的MVC框架中URL、Controller和模板映射很直接
如http://xx.xx.xx/aa/bb这个URL将访问aa这个Controller的bb方法,而bb方法的页面模板为views/aa/bb.rhtml
这是Rails默认配置下的映射
我们在SayController类中定义了hello和goodbye方法,下面我们创建它们对应的模板
1,views/say/hello.rhtml
- <html>
- <head>
- <title>Hello, Rails!</title>
- </head>
- <body>
- <h1>Hello from Rails!</h1>
- <p>
- It is now <%= @time %>
- </p>
- <p>
- Time to say
- <%= link_to "Goodbye!", :action => "goodbye" %>
- </p>
- </body>
- </html>
<script type="text/javascript">render_code();</script>
2,views/say/goodbye.rhtml
- <html>
- <head>
- <title>See You Later!</title>
- </head>
- <body>
- <h1>Goodbye!</h1>
- <p>
- It was nice having you here.
- </p>
- <p>
- Say <%= link_to "Hello!", :action => "hello" %> again.
- </p>
- </body>
- </html>
<script type="text/javascript">render_code();</script>
其中link_to()辅助方法将创建到一个action的链接,如<%= link_to "Hello!", :action => "hello" %>将被ERB解析成<a href="/say/hello">Hello!</a
启动Rails自带服务器WEBrick测试
由于刚才已经启动了WEBrick,现在直接访问http://localhost:3000/say/hello即可