Rails中文Podcasts【二】

来源:互联网 发布:matlab矩阵接近奇异值 编辑:程序博客网 时间:2024/05/03 21:03

一、使用Symbol的to_proc方法得到的便捷代码块

class Project < ActiveRecord::Base  has_many :tasks    def self.all_names    find(:all).collect(&:name)  endend

这里的

find(:all).collect(&:name)

显得比较奇怪,因为之前几乎没见过"&"加":"这么用的,在这里,self.all_names会返回一个包含了所有项目名字的集合比如 ["Rails Project","Homework"],上面的代码等价于下面这些代码

find(:all).collect{ |p| p.name }

得益于to_proc的特性,我们还可以做这种事情

find(:all).collect(&:name).collect(&:downcase)

它会返回这样的东西  ["rails project","homework"]


二、七七八八的layouts

如果你熟悉MVC,那么这里的layouts可以理解为View里面的东西,灵活的rails可以让你通过多种方式来渲染layouts。

全局layouts:在views/layouts中添加application.html.erb,写上html基本的东西,然后加上一句<%= yield%>就能召唤其他的view了,比如此时的views/posts中的所有view便会自动加上application.html.erb里面的内容,但是,如果你这个时候在views/layouts里面除了添加application.html.erb还加上一个posts.html.erb(当然要用<%= yield%>来召唤其他的view),那么在views/posts中的view便会加载posts.html.erb而不是application.html.erb里面的内容了。

你也能在controller中添加需要渲染的layouts

class PostsController < ApplicationController  layout "admin"  def index    @posts = Post.all  endend

这样的话,rails便会在views/layouts中寻找一个叫做admin.html.erb的文件并把它加到其他view中。

你也可以在选择layouts之前加一些判断,这样就能实现登陆与没有登陆的用户看见不同view的功能了:

class PostsController < ApplicationController  layout :user_layout  def index    @posts = Post.all  end  protected  def user_layout    if current_user.login?      "admin"    else      "application"    end  endend
当然,你更可以在action里面添加
  def index    @posts = Post.all    render :layout => "posts"  end

三、content_for来为html.erb添加指定的css

你需要在index.html.erb中添加

<% content_for :head do%>  <%= stylesheet_link_tag "project"%><% end %>
这样,rails就能到app/assets/stylesheets中去寻找一个叫project的css文件,但是,此时你还需要在application.html.erb中召唤一下,才能在刷新页面之后看见效果
<%= yield :head %>

四,过滤敏感的Log日志

Filter Sensitive Logs

为了安全可以在ApplicationController中添加

class ApplicationController < ActionController::Base  filter_parameter_logging "password"end
通过filter_parameter_logging你可以过滤所有你想过滤的字段