2009年5月3日 星期日

Rails templates

就是讓你把建project 的每次都會做的一些動作弄成script , 常用的gem ,plugin, git commit, 這樣就不用每次都要在手動建一次

高速開發的利器:Rails 2.3 之 Template & Engine
App Templates in Rails 2.3
Rails templates
rails-templates in github
rails-template in github2

Rails on Rack

Rails on Rack
Ruby on Rack #1 - Hello Rack!
Ruby on Rack #2 - The Builder 13
Introducing Rack
Rails meets Sinatra

What is Rack ?
Rack: a Ruby Webserver Interface
rack-contrib in github

Rack provides a minimal, modular and adaptable interface for developing web applications in Ruby. By wrapping HTTP requests and responses in the simplest way possible, it unifies and distills the API for web servers, web frameworks, and software in between (the so-called middleware) into a single method call.



Rack Specification

Rack specification specifies how exactly a Rack application and the web server should communicate :

A Rack application is an Ruby object (not a class) that responds to call. It takes exactly one argument, the environment and returns an Array of exactly three values: The status, the headers, and the body.



Rack Gem
Rack gem is a collection of utilities and facilitating classes, to make life easier for anyone developing Rack applications. It includes basic implementations of request, response, cookies & sessions. And a good number of usefult middlewares. In short, install the rack gem. You’re gonna need it :

$ sudo gem install rack



To summarize
Ruby on Rack #1 - Hello Rack!
* Rack is a framework to roll your own ruby framework.
* Rack provides an interface between different web servers and your framework/application. Making it very simple for your framework/application to be compatible with any webserver that supports Rack – Phusion Passenger, Litespeed, Mongrel, Thin, Ebb, Webrick to name a few.
* Rack cuts your chase. You get request, response, cookies, params & sessions for free.
* Makes it possible to use multiple frameworks for the same application, provided there is no class collision. Rails and sinatra integration is a good example of this.
* Middlewares ! Think of middlewares as Rails’s before_filter/after_filter that are reusable across different rack supported frameworks/applications. For example, you can use the same Anti-spamming rack middleware for your Rails app, Sinatra app and your custom Rack application too!



2.1 Rails Application’s Rack Object

ActionController::Dispatcher.new is the primary Rack application object of a Rails application. Any Rack compliant web server should be using ActionController::Dispatcher.new object to serve a Rails application.



2.2 script/server

script/server does the basic job of creating a Rack::Builder object and starting the webserver. This is Rails’ equivalent of Rack’s rackup script.

Here’s how script/server creates an instance of Rack::Builder



2.3 rackup

To use rackup instead of Rails’ script/server, you can put the following inside config.ru of your Rails application’s root directory:



3 Action Controller Middleware Stack
Rack Middleware railscast

Many of Action Controller’s internal components are implemented as Rack middlewares. ActionController::Dispatcher uses ActionController::MiddlewareStack to combine various internal and external middlewares to form a complete Rails Rack application.

ActionController::MiddlewareStack is Rails’ equivalent of Rack::Builder, but built for better flexibility and more features to meet Rails’ requirements.



3.2 Configuring Middleware Stack

Rails provides a simple configuration interface config.middleware for adding, removing and modifying the middlewares in the middleware stack via environment.rb or the environment specific configuration file environments/.rb.

3.2.1 Adding a Middleware


3.2.2 Swapping a Middleware

You can swap an existing middleware in the middleware stack using config.middleware.swap.




3.4 Customizing Internal Middleware Stack

It’s possible to replace the entire middleware stack with a custom stack using ActionController::Dispatcher.middleware=.



3.5 Using Rack Builder

The following shows how to replace use Rack::Builder instead of the Rails supplied MiddlewareStack.

Clear the existing Rails middleware stack
Add a config.ru file to RAILS_ROOT



4 Rails Metal Applications
Rails Metal railscast
Rails Metal: a micro-framework with the power of Rails
Introducing Rails Metal

Rails Metal applications are minimal Rack applications specially designed for integrating with a typical Rails application. As Rails Metal Applications skip all of the Action Controller stack, serving a request has no overhead from the Rails framework itself. This is especially useful for infrequent cases where the performance of the full stack Rails framework is an issue.

Rails 2.3 release notes

Ruby on Rails 2.3 Release Notes

1. Session stores are now lazy loaded. If you never access the session object during a request, it will never attempt to load the session data (parse the cookie, load the data from memcache, or lookup an Active Record object).

2. ActiveRecord::QueryCache middleware is automatically inserted onto the middleware stack if ActiveRecord has been loaded. This middleware sets up and flushes the per-request Active Record query cache.

3. The Rails router and controller classes follow the Rack spec. You can call a controller directly with SomeController.call(env). The router stores the routing parameters in rack.routing_args.

4. Instead of config.action_controller.session = { :session_key => 'foo', ... use config.action_controller.session = { :key => 'foo', ....



Nested Attributes, Nested Object Forms
Rails 2.3 前的 nested model/complex forms problem 都是這樣做
What's New in Edge Rails: Nested Model Mass Assignment

2.3 之後可以這樣做了
What's New in Edge Rails: Nested Object Forms
Nested Model Forms



Nested Transactions



Multiple Conditions for Callbacks
When using Active Record callbacks, you can now combine :if and :unless options on the same callback, and supply multiple conditions as an array:




Find with having
mysql group_by having
MYSQL GROUP BY 和 HAVING 子句

HAVING子句可以讓我們篩選成組後的各組數據.
WHERE子句在聚合前先篩選記錄.也就是說作用在GROUP BY 子句和HAVING子句前.
而 HAVING子句在聚合後對組記錄進行篩選。

Rails now has a :having option on find (as well as on has_many and has_and_belongs_to_many associations) for filtering records in grouped finds. As those with heavy SQL backgrounds know, this allows filtering based on grouped results:




Reconnecting MySQL Connections
mysql Controlling Automatic Reconnection Behavior
MySQL supports a reconnect flag in its connections – if set to true, then the client will try reconnecting to the server before giving up in case of a lost connection. You can now set reconnect = true for your MySQL connections in database.yml to get this behavior from a Rails application



Application Controller Renamed

If you’re one of the people who has always been bothered by the special-case naming of application.rb, rejoice! It’s been reworked to be application_controller.rb in Rails 2.3. In addition, there’s a new rake task, rake rails:update:application_controller to do this automatically for you – and it will be run as part of the normal rake rails:update process.



HTTP Digest Authentication Support

For those that may now know the difference, basic authentication only base 64 encodes the authenticating username and password (making it easily decoded) whereas digest authentication sends an MD5 hash of your username and password. To simplify, digest is more secure than basic.

What's New in Edge Rails: HTTP Digest Authentication



More Efficient Routing

Another big change is that Rails now supports multiple routing files, not just routes.rb. You can use RouteSet#add_configuration_file to bring in more routes at any time – without clearing the currently-loaded routes. While this change is most useful for Engines, you can use it in any application that needs to load routes in batches.



Rack-based Lazy-loaded Sessions

In addition, sessions are now lazy-loaded (in line with the loading improvements to the rest of the framework). This means that you no longer need to explicitly disable sessions if you don’t want them; just don’t refer to them and they won’t load.



MIME Type Handling Changes

There are a couple of changes to the code for handling MIME types in Rails. First, MIME::Type now implements the =~ operator, making things much cleaner when you need to check for the presence of a type that has synonyms:

The other change is that the framework now uses the Mime::JS when checking for javascript in various spots, making it handle those alternatives cleanly.



Asset Hosts as Objects

Asset hosts get more flexible in edge Rails with the ability to declare an asset host as a specific object that responds to a call. This allows you to to implement any complex logic you need in your asset hosting.



grouped_options_for_select Helper Method





Disabled Option Tags for Form Select Helpers

New in rails 2.3 – disabled option tags and lambdas for selecting and disabling options from collections



Swappable Parsers for XMLmini

The support for XML parsing in ActiveSupport has been made more flexible by allowing you to swap in different parsers. By default, it uses the standard REXML implementation, but you can easily specify the faster LibXML or Nokogiri implementations for your own applications, provided you have the appropriate gems installed:




Faster Boot Time in Development Mode with Lazy Loading/Autoload

Quite a bit of work was done to make sure that bits of Rails (and its dependencies) are only brought into memory when they’re actually needed. The core frameworks – Active Support, Active Record, Action Controller, Action Mailer and Action View – are now using autoload to lazy-load their individual classes. This work should help keep the memory footprint down and improve overall Rails performance.

You can also specify (by using the new preload_frameworks option) whether the core libraries should be autoloaded at startup. This defaults to false so that Rails autoloads itself piece-by-piece, but there are some circumstances where you still need to bring in everything at once – Passenger and JRuby both want to see all of Rails loaded together.

2009年5月2日 星期六

JavaScript Programming Patterns

JavaScript Programming Patterns

The Old-School Way
working example




singleton
working example




Module Pattern
working example






Revealing Module Pattern
working example






Custom Objects
working example

Using prototype, we can now add additional properties to the object “blueprint” so that these items are available for every instance of that object right from the start. I ended up with having 3 properties, namely: config, changeColor and init.

呼叫用法也不同




Lazy Function Definition
his pattern is particularly useful when you need to do computations on the page once and then reuse the output multiple times.
working example


用法

As stated above, this pattern is not that handy here, but consider a situation when there is some heavy and complex computing involved. You certainly do not want to do that each time the function gets called. Peter calls this kind of function definition a “promise”, which means the outer declaration can be viewed as some kind of promise that later on this function will get redeclared to provide something more useful.




Conclusion

There is no general solution on how such problems should be approached. For a task like this, I believe that the singleton pattern is the most convenient way of doing it. Mostly because less lines of code are required. But for other, more complex problems, using the module pattern or creating custom objects or the lazy function definition might be more appropriate.

The seven rules of Unobtrusive JavaScript

The seven rules of Unobtrusive JavaScript
[譯文]The seven rules of
Unobtrusive JavaScript


像這種全域式的有可能會造成跟人家命名相衝的結果


所以我們將他包成一個object


可是這樣的結果有可能會造成命名太長, 或者是我有些function 只是內部使用, 不想給外面用
就可以用下面的方式, 將想給外面用的方法放在return 裡





對於js 操控的 HTML 和 CSS 應該將其分離出來放到一個物件裡, 方便管理

2009年5月1日 星期五

ruby 中文

Use Regexp to handle String 用 Regexp 拯救字串處理
1.8, 1.9


Unicode codepoint
另一種在 Ruby 1.8 拯救 UTF-8 字串的方式
1.8 1.9

block, Proc , lambda AND module mixin AND method_missing

Ruby 程式語言簡介

帶參數的 code block


Proc object
將 code block 明確轉成物件




Module 和 Mixins




Method Missing


Introspection (反射機制)