今天读完了rails recipes,书比较老了,很多东西也已经了解,所以只是粗略的看了下.
简单的记录下笔记.下面的记录是按照章节来的.
一,User Interface Recipes
1,In-Place Form Editing.plugin.
2,Making Your Own JavaScript Helper,实现自己的js helper.
3,Showing a Live Preview,显示实时预览.使用了observe_form方法.
4,Autocomplete a Text Field.plugin.
5,Creating a Drag-and-Drop Sortable List.plugin.
6,Update Multiple Elements with One Ajax Request.just rjs.
7,Lightning-Fast JavaScript Autocompletion.感觉实现的方法比较笨,首先在页面载入时,将检索结果存放到js中,在自动补全时,直接从js的array中查找,而不需要和后台交互.如果后台数据量太大如何处理?不可能将所有情况这样来做吧.Google prefetches the addresses and autocompletes them from an in-browser cache.google为什么这么快?难道就是in-browser cache.
8,Cheap & Easy Theme Support.
9,Trim Static Pages with Ajax.
10,Smart Pluralization.
11,Debugging Ajax.
12,Creating a Custom Form Builder.
13,Make Pretty Graphs.plugin.
二,Database Recipes
14,Rails without a Database.
15,Connecting to Multiple Databases.在ActiveRecord每个model可以指定数据库.
16,Integrating with Legacy Databases.
17,DRY Up Your Database Configuration.可以这样写.
defaults: &defaults
adapter: mysql
username: root
password: secret
socket: /tmp/mysql.sock
development:
database: DRYUpYourDatabaseConfig_development
<<: *defaults
test:
database: DRYUpYourDatabaseConfig_test
<<: *defaults
production:
database: DRYUpYourDatabaseConfig_production
<<: *defaults
[color=red]18,Self-referential Many-to-Many Relationships.见代码.[/color]
def self.up
create_table :people do |t|
t.column "name" , :string
end
create_table :friends_people, :id => false do |t|
t.column "person_id" , :integer
t.column "friend_id" , :integer
end
class Person < ActiveRecord::Base
has_and_belongs_to_many :friends,
:class_name => "Person" ,
:join_table => "friends_people" ,
:association_foreign_key => "friend_id" ,
:foreign_key => "person_id"
def be_friendly_to_friend(friend)
friend.friends << self unless friend.friends.include?(self)
end
def no_more_mr_nice_guy(friend)
friend.friends.delete(self) rescue nil
end
end
19,Tagging Your Content.acts_as_taggable,技术上比较简单,不过可以用别人写好的代码,不用造轮子.
20,Versioning Your Models.acts_as_versioned.一般的项目好像不太会用,毕竟数据量太大.
21,Converting to Migration-Based Schemas.
22,Many-to-Many Relationships with Extra Data.
23,Polymorphic Associations—has_many :whatevers.
24,Add Behavior to Active Record Associations.
25,Dynamically Configure Your Database.
development:
adapter: mysql
database: DynamicDatabaseConfiguration_development
username: root
password:
socket: <%= ["/tmp/mysqld.sock" ,
"/tmp/mysql.sock" ,
"/var/run/mysqld/mysqld.sock" ,
"/var/lib/mysql/mysql.sock" ].detect{|socket|
File.exist?(socket)
} %>
26,Use Active Record Outside of Rails.
27,Perform Calculations on Your Model Data.
28,DRY Up Active Record Code with Scoping.
29,Make Dumb Data Smart with composed_of().
30,Safely Use Models in Migrations.
三,Controller Recipes
31,Authenticating Your Users.plugin.
32,Authorizing Users with Roles.plugin.
33,Cleaning Up Controllers with Postback Actions.
34,Monitor Expiring Sessions.
[
def update_activity_time
session[:expires_at] = 10.minutes.from_now
end
<%= periodically_call_remote :url => {
:action => 'session_expiry'},
:update => 'header' %>
<% if @time_left < 1.minute %>
<span style='color: red; font-weight: bold'>
Your session will expire in <%= @time_left %> seconds
</span>
<% end %>
[color=red] 35,Rendering Comma-Separated Values from Your Actions.CSV::Writer.生成csv文件,有时候会很有用的.
[/color] 36,Make Your URLs Meaningful (and Pretty).
37,Stub Out Authentication.
38,Convert to Active Record Sessions.je上已经有人发帖,讨论了关于session的问题.http://www.iteye.com/topic/333642
39,Write Code That Writes Code.DRY.原来这样翻译,写一段生成代码的代码.很多插件就是根据ruby语言的可扩展性,来实现的.
40,Manage a Static Site with Rails.
四,Testing Recipes
41,Creating Dynamic Test Fixtures.
[color=red]42,Extracting Test Fixtures from Live Data.[/color]
desc 'Create YAML test fixtures from data in an existing database.
Defaults to development database. Set RAILS_ENV to override.'
task :extract_fixtures => :environment do
sql = "SELECT * FROM %s"
skip_tables = ["schema_info" ]
ActiveRecord::Base.establish_connection
(ActiveRecord::Base.connection.tables - skip_tables).each do |table_name|
i = "000"
File.open("#{RAILS_ROOT}/test/fixtures/#{table_name}.yml" , 'w' ) do |file|
data = ActiveRecord::Base.connection.select_all(sql % table_name)
file.write data.inject({}) { |hash, record|
hash["#{table_name}_#{i.succ!}" ] = record
hash
}.to_yaml
end
end
end
43,Testing Across Multiple Controllers.rspec
44,Write Tests for Your Helpers.rspec
五,Big-Picture Recipes
45,Automating Development with Your Own Generators.应该不会用到吧.玩玩还行.
46,Continuously Integrate Your Code Base.持续集成,记得上次在上海kongfu rails,介绍过一个很不错的持续集成的工具.
47,Getting Notified of Unhandled Exceptions.
48,Creating Your Own Rake Tasks.railscasts上有一篇是介绍的.
49,Dealing with Time Zones.
50,Living on the Edge (of Rails Development)
51,Syndicate Your Site with RSS
52,Making Your Own Rails Plugins.railscasts上有.上次上海rails会议上有提到好像.
53,Secret URLs.
before_create :generate_access_key
def generate_access_key
@attributes['access_key' ] = MD5.hexdigest((object_id + rand(255)).to_s)
end
before_filter :authenticate_access_key, :only => [:inbox]
def authenticate_access_key
inbox = Inbox.find_by_access_key(params[:access_key])
if inbox.blank? || inbox.id != params[:id].to_i
raise "Unauthorized"
end
end
def inbox
@inbox = Inbox.find(params[:id])
end
[color=red]54,Quickly Inspect Your Sessions’Contents.这个很实用.[/color]
#script/dump_sessions
#!/usr/bin/env ruby
require 'pp'
require File.dirname(__FILE__) + '/../config/environment'
Dir['app/models/**/*rb' ].each{|f| require f}
pp Dir['/tmp/ruby_sess*' ].collect {|file|
[file, Marshal.load(File.read(file))]
}
You can call it like this:
chad> ruby script/dump_sessions
[["/tmp/ruby_sess.073009d69aa82787", {"hash"=>{"flash"=>{}}}],
["/tmp/ruby_sess.122c36ca72886f45", {"hash"=>{"flash"=>{}}}],
["/tmp/ruby_sess.122f4cb99733ef40", {"hash"=>
{:user=>#<User:0x24ad71c @attributes={"name"=>"Chad", "id"=>"1"}>,
"flash"=>{}}}
]
]
55,Sharing Models between Your Applications.
56,Generate Documentation for Your Application.
57,Processing Uploaded Images.plugin.
[color=red]58,Easily Group Lists of Things.这个很不错,一直没用过,看起来还是很实用的.
[/color]
<%
employees = Employee.find(:all).group_by {|employee|
employee.title
}
%>
<% employees.each do |title, people| %>
<h2><%= title %></h2>
<ul>
<% people.each do |person| %>
<li><%= person.name %></li>
<% end %>
</ul>
<% end %>
<table class="calendar" >
<% (1..DAYS_IN_MARCH).to_a.in_groups_of(7) do |group| %>
<tr>
<% group.each do |day| %>
<td><%= day %></td>
<% end %>
</tr>
<% end %>
</table>
59,Keeping Track of Who Did What.用sweeper.
class AuditSweeper < ActionController::Caching::Sweeper
observe Person
def after_destroy(record)
log(record, "DESTROY" )
end
def after_update(record)
log(record, "UPDATE" )
end
def after_create(record)
log(record, "CREATE" )
end
def log(record, event, user = controller.session[:user])
AuditTrail.create(:record_id => record.id, :record_type => record.type.name,
:event => event, :user_id => user)
end
end
60,Distributing Your Application As One Directory Tree.freeze.
61,Adding Support for Localization.
62,The Console Is Your Friend.
63,Automatically Save a Draft of a Form.observe_form.
[color=red]64,Validating Non–Active Record Objects.
[/color]
class MySpecialModel < SomeOtherInfrastructure
include ActiveRecord::Validations
end
ValidatingNonARObjects/lib/validateable.rb
module Validateable
[:save, :save!, :update_attribute].each{|attr| define_method(attr){}}
def method_missing(symbol, *params)
if(symbol.to_s =~ /(.*)_before_type_cast$/)
send($1)
end
end
def self.append_features(base)
super
base.send(:include, ActiveRecord::Validations)
end
end
ValidatingNonARObjects/app/models/person.rb
class Person
include Validateable
attr_accessor :age
validates_numericality_of :age
end
65,Easy HTML Whitelists.
66,Adding Simple Web Services to Your Actions.
email部分一直没看rails,所以这部分暂时没没看,等到用的时候再看吧,就是一些类和方法的使用吧.