rails 代码结构详解
目录结构
这一节让我们走访一个 Rails的目录结构:
app/
app 目录是你主要工作的地方,不同子目录存储了 Models、Controllers、Views、Helpers和 Assets 等档案。
app/controllers
app/models
app/views
View 的样本(template)档案,依照不同Controllers分子目录存储。
app/helpers
app/assets
Assets 静态档案存放在这里,包括有JavaScript、Stylesheets样式表单和Images图档。详细的用法会在Assets一章中介绍。
config/
db/
doc/
lib/
如果你有一些共享的类别或模块档案,可以放在这里,然后用require加载。例如一个放在lib/foobar.rb的类别或模块档案,可以在要使用的.rb档案中这样加载:
require "foobar"
require "foo/bar"
lib/tasks
Rake 任务档案存放在这里,我们会在Rails锦囊妙计一章介绍 Rake。
log/
public/
这个目录对 Web服务器来说,就是文件根目录(document root),也就是唯一可以在网络上读取到的目录。
script/
test/
tmp/
vendor/
其他根目录下的档案
- config.ru 用来启动应用程序的 Rack配置文件
- Gemfile 设定你的 Rails应用程序会使用哪些 Gems
- README.rdoc 你的应用程序使用手册。你可以用来告诉其他人你的应用程序是做什么用的,如何使用等等。
- Rakefile 用来加载可以被命令行执行的 Rake任务
- developmentenvironment 开发模式,用在你的开发的时候
- test environment 测试模式,用在执行测试程序时
- production environment正式上线模式,用在实际的上线运作环境
staging 可以用来表示准上线模式,用来做正式上线前的 QA测试用途。
因为程序本身是不是写死是哪一种执行模式,那么要怎么区分呢?根据不同情况有不同方法,包括:
根据环境变量 RAILS_ENV或 RACK_ENV 来决定使用哪一种模式,例如使用rake时:
RAILS_ENV=production rake db:migrate
rails console production
rails server -e production
最后,应用程序服务器则看服务器配置文件,例如Passenger里会设定RackEnv
参数,布署一章会详细介绍。
generate 可缩写为 g
rails generate model person
rails g controller people
console 可缩写为 c
rails console
rails c
默认的环境是 developement,如果需要指定环境,请多输入环境名称即可,例如:
rails c production
Rails也有提供沙盒模式(Sandbox),任何数据库的修改都会在离开时回复(原理是数据库Transaction):
rails c --sandbox
server 可缩写为 s
rails s
默认是使用 Port 3000和 development 环境,如果需要指定:
rails s -p 4000 -e production
new
rails new my_app
将会建立一个叫做 MyApp的 Rails 项目在./my_app 目录下。加上--database
参数可以改变配置文件的默认值,例如:
rails new my_app --database=mysql
其他指令
- dbconsole 开起一个数据库控制台 (可简写为 rails db),让你直接输入 SQL 指令。
- destroy 删除 “generate”所产生的档案
- benchmarker 产生 benchmark信息,我们会在性能一章介绍如何使用
- profiler 产生 profiler信息,我们会在性能一章介绍如何使用
- runner 在 Rails环境中执行一段程序,例如 rails runner “puts Person.count”
不同的 Rails版本产生的配置文件可能会略有差异,这些配置文件也没有列出所有Rails设定,只有列出比较常用的。
# Custom directories with classes and modules you want to be autoloadable.
# config.autoload_paths += %W(#{config.root}/extras)
任何放在 app/models、app/controllers目录下的类别档案,Rails 都会根据类别的命名惯例来自动加载。如果你有其他类别档案需要加载,请在这个设定加入。例如通常我们会加入
config.autoload_paths += %W( #{config.root}/app/lib )
# Activate observers that should always be running.
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
设定 ActiveRecord的观察者类别,我们会在 ActiveRecord章节详述这个模式,简单来说,它会在 ActiveRecord数据变动时执行外部回呼,例如清除快取。
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
设定默认的应用程序语系,默认是:en。我们会在”I18n多国语系及时区”一章介绍如何使用。
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
设定 filter_paramsters可以避免任何叫做 password的参数值记录到log 中,有效防止用户的原始密码外泄到 log 档案。
# Use SQL instead of Active Record's schema dumper when creating the database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql
改用:sql的话,Rails 会倒出现有的 development 数据库,产生#{Rails.env}_structure.sql档案来作为测试数据库之用。
# Enforce whitelist mode for mass assignment.
# This will create an empty whitelist of attributes available for mass-assignment for all models
# in your app. As such, your models will need to explicitly whitelist or blacklist accessible
# parameters by using an attr_accessible or attr_protected declaration.
config.active_record.whitelist_attributes = true
預設打開
*Mass assignment*
的白名單設定,詳見安全性一章
。
其他初始配置文件(initialzers)
backtrace silencers
可以让你选择性地移除例外追踪(exceptionbacktrace)讯息,例如有些套件可能会很吵,妨碍你除错。
inflections
$ rails c
$ Loading development environment (Rails 3.2.8)
$ > "Business".singularize => "Busines" #
轉單數
$ > "moose".pluralize => "mooses" #
轉複
數
很不幸地这两个例子 Rails都没转对,这时候你就可以利用 inflections.rb来修正。
Rails 核心不接受有关单复数转换的单字错误回报,毕竟它不是想做字典。
mime_types
type/subtype |
respond_to symbol |
别名/说明 |
text/html |
:html, :xhtml |
application/xhtml+xml |
text/plain |
:text, :txt |
|
text/javascript |
:js |
application/javascript, application/x-javascript |
text/css |
:css |
|
text/calendar |
:ics |
iCalendar 格式 |
text/csv |
:csv |
|
application/xml |
:xml |
text/xml, application/x-xml |
application/rss+xml |
:rss |
|
application/atom+xml |
:atom |
|
application/x-yaml |
:yaml |
text/yaml |
application/x-www-form-urlencoded |
:url_encoded_form |
默认的 HTML forms 格式 |
multipart/form-data |
:multipart_form |
HTML forms 格式(包含二进制文件数据) |
application/json |
:json |
text/x-json application/jsonrequest |
secret_token
sesssion_store
我们在上一节”多重环境设定”曾经介绍不同环境会有不同的配置文件,让我们来更深入看看有哪些设定值,以及这些值是如果影响 Development、Production和 Test环境的不同:
Development 模式
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the webserver when you make code changes.
config.cache_classes = false
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
当你对 nil呼叫方法时,会出现 NoMethodError。whiny_nils= true会提示你更多讯息来除错。这个值在 production默认是 false。
# Show full error reports and disable caching
config.consider_all_requests_local = true
Rails只有在联机是来自本地端的时候,才会将发生错误时的Callstack trace信息给浏览器显示。这个设定将所有联机都当做本地端联机,好让开发模式时所有人联机都可以看到错误讯息。
config.action_controller.perform_caching = false
是否启用 Controller层级的快取(我们会在 Controller一章介绍到有哪些快取方法),一般来说在开发模式不会启用,除非你要测试它。
# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger
config.active_support.deprecation = :log
随着 Rails版本的升级,如果有方法会在之后的版本中移除,deprecation会提示你如何因应。这里的 :log表示会记录到log 档案中。
# Only use best-standards-support built into browsers
config.action_dispatch.best_standards_support = :builtin
http://code.google.com/chrome/chromeframe/
# Log the query plan for queries taking more than this (works
# with SQLite, MySQL, and PostgreSQL)
config.active_record.auto_explain_threshold_in_seconds = 0.5
当SQL查询超过0.5秒时,自动做SQLexplain在Log里。
# Do not compress assets
config.assets.compress = false
# Expands the lines which load the assets
config.assets.debug = true
以上这两行Asset Pipeline的设定会在Asset一章中介绍。
Production 模式
# The production environment is meant for finished, "live" apps.
# Code is not reloaded between requests
config.cache_classes = true
cache_classes = true 表示在 production 中,类别档案加载进内存中就快取起来了,大大获得性能。不像在 development环境中每一次HTTP 请求就会重载一次。
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
不同于 development,如果在 production环境出现例外错误,不会显示程序 call stack讯息,而是回传public/500.html页面。
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = false
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = false
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false
# Generate digests for assets URLs
config.assets.digest = true
# Defaults to nil and saved in location specified by config.assets.prefix
# config.assets.manifest = YOUR_PATH
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
# config.assets.precompile += %w( search.js )
# Specifies the header that your server uses for sending files
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
“X-Sendfile” 是网页服务器提供的功能,可以让下载文件的动作完全委派给网页服务器,Rails送出X-Sendfile 标头后就毋需再占住资源。
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# See everything in the log (default is :info)
# config.log_level = :debug
我们在 RESTful应用程序一章最后介绍了Logger。这里可以设定 Logger的层级。默认 production是:info,其他则是 :debug
# Use a different logger for distributed setups
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
可以更换掉 Rails内建的 Logger,例如换成使用syslog的SyslogLogger。
# Use a different cache store in production
# config.cache_store = :mem_cache_store
设定不同的快取储存库,默认是 :memory_store,也就是每个 Rails process各自用内存存放。业界最常用的则是memcached内存快取服务器。
# Enable serving of images, stylesheets, and javascripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
默认的静态档案位置是目前主机的 public目录,你可以透过修改 asset_host变更位置。例如你的静态档案放在不同台机器或 CDN(Content delivery network)上。
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
# config.threadsafe!
如果您是使用 JRuby,受益于 Java VM强大的 Thread 实现,那么就有值得打开 threaded 模式的理由。
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
如果 I18n翻译档找不到,则找用默认语系的文字。我们会在I18n一章详细介绍多国语系功能。
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
将 deprecation讯息传到Notifications频道,你可以用以下程序去订阅这个讯息:
ActiveSupport::Notifications.subscribe("deprecation.rails") do |message, callstack|
# deprecation message
end
Test 模式
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Raise exceptions instead of rendering exception templates
config.action_dispatch.show_exceptions = false
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test
# Print deprecation notices to the stderr
config.active_support.deprecation = :stderr
数据库配置文件 database.yml
development:
adapter: mysql
encoding: utf8
database: blog_development
username: root
password:
production:
adapter: mysql
encoding: utf8
database: blog_production
username: root
password:
test:
adapter: mysql
encoding: utf8
database: blog_test
username: root
password:
Bundler 与 Gemfile 配置文件
#
第二個參數可以指定版本
gem "rails", "3.2.8"
#
也可以不指定版本,這樣會安裝最新的穩定版本
(
不包括
.pre
或
.rc
結尾的版本
)
gem 'mysql2'
#
如果
require
的檔名不同,可以加上
:require
gem 'yajl-ruby', :require => 'yajl'
#
可以用
Git
當做來源
(
根目錄要有
.gemspec
檔案
)
,甚至可以指定
branch, tag
或
ref
。
gem 'authlogic', :git => 'git://github.com/odorcicd/authlogic.git',
:branch => 'rails3'
#
也可以直接用電腦裡的其他目錄
# gem "rails", :path => '/Users/ihower/github/rails'
# Group
功能可以讓特定環境才會載入
group :development, :test do
gem "rspec", "~> 2.0"
gem "rspec-rails", "~> 2.0"
end
安装及更新 Gems
bundle outdated
打包 Gems
执行以下指令,会将所有用到的 Gems打包进 vendor/cache目录。如此执行bundle install时就不会联机到 http://rubygems.org下载套件。
bundle package
什么时候需要用到这个功能呢?例如你希望布署的时候避免外部联机,或是你有非公开的 gems不会上传到http://rubygems.org网站上。
类别命名与自动加载
如果是有嵌套的类别或模块,例如Admin::OrderItem,则会多一层目录,它会自动加载admin/order_item.rb的档案,也就是 require“admin/order_item”。
Model 命名
类别名称使用大写、单数,没有底线。而档名使用小写、单数,用底线。数据库表格名称用小写且为复数。例如:
Controller 命名
如果需要将controllers档案做分类,这时候可以使用Mobules,将档案放在子目录下,例如后台专用的controllers:
View 命名
例如一个叫做 People的 controller,其中的index action:
- Action Pack
- Action Controller
- Action Dispatch
- Action View
- Action Mailer
- Active Model
- Active Record
- Active Resource
- Active Support
- Railties
Action Pack
Action Pack 是个包含 Action Controller、ActionView和 Action Dispatch的 gem。也就是“MVC”中的 “VC” 部分。
Action Controller
Action View
Action Dispatch
Action Dispatch 处理 HTTP请求的路由(routing),它把 HTTP请求发派(dispatch)到它该去的地方,也许是你的应用程序或其他 Rack程序。
Action Mailer
Action Mailer 是个建构 E-mail功能的框架。你可以使用Action Mailer来接收来信,或是使用样板来寄出纯文本或复杂的multipart信件。
Active Model
Active Record
Active Record 是 Rails应用程序中的Models 基础。它不依存特定的数据库系统,提供了 CRUD功能、先进的查询能力以及可以跟其他 Models关联的本事。
Active Resource
Active Resource 提供了与其他业务对象和 RESTful网络服务的链接框架。它实现了一种可以对应以 Web为基础的Resources 成为本地端支持 CRUD 的对象。
Active Support
Active Support 是 Rails里的工具函式库,它也扩充了一些 Ruby标准函式库。除了被用在Rails核心程序中,你也可以在你的程序中使用。
Railties
Railties 是 Rails的核心程序代码,用来把以上各种的框架函式库以及 Plugin全部组合在一起。
rails 代码结构详解相关推荐
- PHP扩展代码结构详解
PHP扩展代码结构详解 : 这个是继: 使用ext_skel和phpize构建php5扩展 内容 (拆分出来) Zend_API:深入_PHP_内核:http://cn2.php.net/manua ...
- Rails项目结构详解
为什么80%的码农都做不了架构师?>>> 应用程序根目录 Gemfile:应用程序的依赖关系配置(gem).修改后通过bundle install应用. README.rdoc ...
- Python项目代码结构详解
目录结构组织方式 简要解释一下: bin/: 存放项目的一些可执行文件,当然你可以起名script/之类的也行. luffy/: 存放项目的所有源代码.(1) 源代码中的所有模块.包都应该放在此目录. ...
- 微信小程序01【目录结构详解、视图与渲染、事件、input、scroll-view】
学习地址:https://www.bilibili.com/video/BV1sx411z77P 笔记01:https://blog.csdn.net/weixin_44949135/article/ ...
- angular 标准目录结构_Angular-cli新建项目目录结构详解
Angular-cli新建项目目录结构详解 在上一篇博客中我们已经通过Angular CLI命令行工具创建出来一个全新的Angular项目,要想写项目,首先我们要先搞清楚项目的目录结构是怎样的,每个文 ...
- [java] 虚拟机(JVM)底层结构详解[转]
[java] 虚拟机(JVM)底层结构详解[转] 本文来自:曹胜欢博客专栏.转载请注明出处:http://blog.csdn.net/csh624366188 在以前的博客里面,我们介绍了在java领 ...
- Android4.0源码目录结构详解
Android4.0源码目录结构详解 Android4.0与2.1目录差不多 alsa这块,注意external/tinyalsa下有: include/tinyalsa/asoundlib.h mi ...
- web标准 浏览器介绍 开发工具介绍 HTML介绍 HTML颜色介绍 规范 HTML结构详解 {前端之前端初识}...
前端之前端初识 前端初识 本节目录 一 web标准 二 浏览器介绍 三 开发工具介绍 四 HTML介绍 五 HTML颜色介绍 六 规范 七 HTML结构详解 一 web标准 web准备介绍: 1.w3 ...
- JVM之内存结构详解
对于开发人员来说,如果不了解Java的JVM,那真的是很难写得一手好代码,很难查得一手好bug.同时,JVM也是面试环节的中重灾区.今天开始,<JVM详解>系列开启,带大家深入了解JVM相 ...
最新文章
- 超燃!Apache Flink 全球顶级盛会强势来袭[视频+PPT]
- 李俊君信电保研面试发言稿及其分析总结
- python脚本打包rpm_python程序打包rpm包
- 你技术很强但薪资不涨?这门技术远比你想的更重要!
- C#语言和数据库基础
- dnf 服务器每周维护,DNF:7.22官方公告出炉,凌晨2点维护7小时,新增3个活动有玄机?...
- 统计学③——总体与样本的差异在哪里
- 2020.2.4记账
- 计算机可移动磁盘无法显示图片,移动硬盘显示不出来怎么办 移动硬盘不显示解决办法【详解】...
- 纯CSS 毛玻璃效果
- 头像上传(限制大小,格式,尺寸)
- 关于C语言和java变量赋值问题
- Android安全检测 - Janus签名漏洞
- Mask R-CNN完整翻译
- 2014校园招聘总结 .
- Robot Arm 机械臂源码解析
- 基于fuse文件系统的android sdcard存储方案:之二
- 手机做网卡,连接电脑上网
- 如何成为一个受“待见”的程序员?
- 一个电子发票开票平台的系统架构设计(01)