`
orcl_zhang
  • 浏览: 243275 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

Rails Recipes读书笔记

阅读更多
      今天读完了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

       18,Self-referential Many-to-Many Relationships.见代码.
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 %>

     35,Rendering Comma-Separated Values from Your Actions.CSV::Writer.生成csv文件,有时候会很有用的.
      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.
      42,Extracting Test Fixtures from Live Data.
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

      54,Quickly Inspect Your Sessions’Contents.这个很实用.
#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.
      58,Easily Group Lists of Things.这个很不错,一直没用过,看起来还是很实用的.
<%
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.
      64,Validating Non–Active Record Objects.
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,所以这部分暂时没没看,等到用的时候再看吧,就是一些类和方法的使用吧.
0
0
分享到:
评论

相关推荐

    Rails Recipes英文版(清晰文字pdf+源码)

    From the latest Ajax effects to time-saving automation tips for your development process, "Rails Recipes" will show you how the experts have already solved the problems you have. Use generators to ...

    Rails recipes

    Rails Recipes是一本针对Ruby on Rails框架的实用书籍,它收集了一系列高效解决问题的技巧和方法,也被称为“Rails开发者的宝典”。作者们通过分享自己的经验和见解,为Rails程序员提供了一本既有实际操作指导又有...

    Rails Recipes Final.pdf

    ### Rails Recipes Final.pdf 知识点解析 #### 标题:Rails Recipes Final.pdf - **核心概念**:本书名为《Rails Recipes》,旨在提供一系列针对Ruby on Rails开发过程中的实用技巧和解决方案。 #### 描述:...

    Rails Recipes英文版(随书源码)

    From the latest Ajax effects to time-saving automation tips for your development process, "Rails Recipes" will show you how the experts have already solved the problems you have. Use generators to ...

    Advanced Rails Recipes(随书源码)

    "Advanced Rails Recipes" is filled with pragmatic recipes you'll use on every Rails project. And by taking the code in these recipes and slipping it into your application you'll not only deliver your...

    Rails Recipes (2006) .pdf

    ### Rails Recipes (2006) - 关键知识点解析 #### 标题解析:Rails Recipes (2006) - **Rails**:Rails 指的是 Ruby on Rails,一种流行的 Web 开发框架,基于 Ruby 语言。 - **Recipes**:在编程书籍中,...

    Advanced Rails Recipes(英语清晰文字pdf+源码)

    "Advanced Rails Recipes" is filled with pragmatic recipes you'll use on every Rails project. And by taking the code in these recipes and slipping it into your application you'll not only deliver your...

    Advanced Rails Recipes

    ### 关于《Advanced Rails Recipes》的关键知识点解析 #### 标题与描述中的核心知识点 **标题:“Advanced Rails Recipes”** 本书名为《高级Rails食谱》,旨在为Ruby on Rails开发者提供一系列高级开发技巧与...

    advanced rury on rails recipes

    从给定的文件信息来看,我们探讨的主题是“高级Ruby on Rails食谱”(Advanced Rails Recipes),这是一本旨在为专业Ruby on Rails(RoR)开发者提供深入指导的专业参考手册。尽管该书尚处于开发阶段,但其目标是...

    Pragmatic.Rails.Recipes.Rails.3.Edition.Mar.2012.pdf

    - **书籍背景**:Rails Recipes 是一本由 Chad Fowler 编写的关于 Ruby on Rails 的书籍,该书于 2012 年出版了针对 Rails 3 的版本。此书被视为官方推荐的 Ruby on Rails 开发指南之一。 - **目标读者**:本书面向...

    Rails Recipes

    《Rails Recipes》是一本专注于Ruby on Rails开发实践的书籍,旨在提供一系列针对不同问题和场景的解决方案,犹如烹饪中的各种食谱。Rails是基于Ruby语言的流行Web应用框架,它以其DRY(Don't Repeat Yourself)原则...

    rails查询学习笔记

    标题 "rails查询学习笔记" 涉及的是Ruby on Rails框架中的数据库查询技术。Ruby on Rails,简称Rails,是一款基于Ruby语言的开源Web应用程序框架,它遵循MVC(模型-视图-控制器)架构模式,使得开发Web应用更加高效...

    Rails.Recipes.Rails.3rd和源码

    《Rails Recipes》是针对Ruby on Rails框架的一本实用指南,主要涵盖了Rails 3版本的相关内容。这本书通过一系列的“配方”(recipes),为开发者提供了在实际开发中可能会遇到的问题及其解决方案,旨在帮助开发者...

    rails 入门详细笔记

    rails官网入门笔记的翻译,非常不错的rubyonrails入门教程!

    Rails.Recipes(Rails.3.Edition,2012) 英文版PDF

    - **书籍定位**: 《Rails Recipes: Rails 3 Edition》是一本面向初级到中级Ruby on Rails开发者的指南。它包含了70个最常见的编程难题解决方案,旨在帮助开发者解决实际工作中可能遇到的问题。 - **内容更新**: 本书...

    Rails_Recipes_with_Source_Code

    《Rails Recipes with Source Code》是一本专注于Ruby on Rails框架实践技巧和源代码解析的书籍。Rails是基于Ruby语言的Web开发框架,以其“约定优于配置”(Convention over Configuration)的理念和“开发人员的...

    ruby rails recipes

    ### Ruby on Rails Web Development Recipes #### 重要知识点概述 本篇文档主要介绍了一本名为《Ruby on Rails Web Development Recipes》的书籍,该书由 Chad Fowler 编写,并由 The Pragmatic Bookshelf 出版。...

    Pragmatic.Bookshelf.Advanced.Rails.Recipes.May.2008

    《Pragmatic Bookshelf Advanced Rails Recipes May 2008》是一本专注于Rails高级开发实践的书籍,由Pragmatic Bookshelf出版社于2008年5月出版。这本书主要面向已经熟悉Ruby on Rails基础的开发者,旨在通过一系列...

Global site tag (gtag.js) - Google Analytics