railscasts.net的相关内容 - tianlu1677/tianlu1677.github.io GitHub Wiki

主要简单记录一下,rails的技巧。

E1 Caching with Instance Variables

class ApplicationController < ActionController::Base
  def current_user
    @current_user ||= User.find(session[:user_id])
  end
end

这里主要是把存在session里面的user_id取出来,然后赋值给实例变量,这样在view 和 controller 都可以访问到,同时 ||= 实现了避免重复赋值的问题。

E2

E6 Shortcut Blocks with Symbol to_proc

def self.all_names
  find(:all).collect(&:name)
end

##8 Layouts and content_for

<% content_for :not_authorized do %>
  alert('You are not authorized to do that!')
<% end %>

<%= content_for :not_authorized if current_user.nil? %>
content_for?(name) # 用于判断当前 页面是否有name的content_for 方法

13 Dangers of Model in Session

不要把model存储来session里面。主要是会产生两个问题,每次调用的时候都会产生请求。二是,修改时候并不会走validate验证。所以只需要存储关键字段,用到的时候查询读取。

##16 Virtual Attributes

class User < ActiveRecord::Base
  # Getter
  def full_name
    [first_name, last_name].join(' ')
  end

  # Setter
  def full_name=(name)
    split = name.split(' ', 2)
    self.first_name = split.first
    self.last_name = split.last
  end
end

把一个字段切割长两个来显示。但在现实中尽量不要采用这种方式,ugly!

##22 Eager Loading rails 4 中已经解决这个问题

24 The Stack Trace

需要具体报错信息,一般都会显示在第一行。

25 sql injection

tasks = Task.find(:conditions=> [ "name LIKE ?", "%#{params[:query]}%" ]

还里还需要了解一下rails的安全机制

27 Cross Site Scripting

需要对用户输入的内容进行转义

##28 29 分组

in_groups_of(number, fill_with = nil)
in_groups(number, fill_with = nil)

%w(1 2 3 4 5 6 7 8 9 10).in_groups(3, '&nbsp;') {|group| p group}
["1", "2", "3", "4"]
["5", "6", "7", "&nbsp;"]
["8", "9", "10", "&nbsp;"]
(1..6).group_by { |i| i%3 }   #=> {0=>[3, 6], 1=>[1, 4], 2=>[2, 5]}

30 Pretty Page Title

module ApplicationHelper
  def title(page_title)
    content_for(:title) { page_title }
  end
end

<title>ASCIIcasts - <%= yield :title %></title>

#17 使用 check_box_tag 标签来实现多选

<% for category in Category.find(:all) %>
    <div>
      <%= check_box_tag "product[category_ids][]", category.id, @product.categories.include?(category) %>
      <%= category.name %>
    </div>
<% end %>

31格式化时间

Date.current
DateTime.now
DateTime.current
DaTeTime.now.at_beginning_of_day
DaTeTime.now.at_beginning_of_hour
DaTeTime.now.at_beginning_of_minute
DaTeTime.now.at_end_of_day
DaTeTime.now.at_end_of_hour
DaTeTime.now.at_end_of_minute

DaTeTime.now.at_middle_of_day
DaTeTime.now.at_midnight
DaTeTime.now.to_i
atetime = DateTime.civil(2007, 12, 4, 0, 0, 0, 0)   # => Tue, 04 Dec 2007 00:00:00 +0000

datetime.to_formatted_s(:db)            # => "2007-12-04 00:00:00"
datetime.to_s(:db)                      # => "2007-12-04 00:00:00"
datetime.to_s(:number)                  # => "20071204000000"
datetime.to_formatted_s(:short)         # => "04 Dec 00:00"
datetime.to_formatted_s(:long)          # => "December 04, 2007 00:00"
datetime.to_formatted_s(:long_ordinal)  # => "December 4th, 2007 00:00"
datetime.to_formatted_s(:rfc822)        # => "Tue, 04 Dec 2007 00:00:00 +0000"
datetime.to_formatted_s(:iso8601)       # => "2007-12-04T00:00:00+00:00"

#42 用with_options 来消除冗余代码

with_options :if => :should_validate_password? do |user|
  user.validates_presence_of :password
  user.validates_confirmation_of :password
  user.validates_format_of :password, :with => /^[^\s]+$/
end

attr_accessor :updating_password

def should_validate_password?
  updating_password || new_record?
end

#46 变化的路由

irb

pluralize

#56 在输出的时候,显示写的logger 信息

require 'logger'

logger = Logger.new(STDOUT)
logger.level = Logger::WARN

logger.debug("Created logger")
logger.info("Program started")
logger.warn("Nothing to do!")

path = "a_non_existent_file"

begin
  File.foreach(path) do |line|
    unless line =~ /^(\w+) = (.*)$/
      logger.error("Line in wrong format: #{line.chomp}")
    end
  end
rescue => err
  logger.fatal("Caught exception; exiting")
  logger.fatal(err)
end

#57 在选择的时候,再新建,更加友好

⚠️ **GitHub.com Fallback** ⚠️