Showing posts with label Rails Convention. Show all posts
Showing posts with label Rails Convention. Show all posts

Tuesday, March 20, 2007

Hashes in Rails method calls

With a knowledge of hashes as well as symbols, you’re now in a position to understand
this construct:
<%= link_to "Click here",:controller => "work",:action => "show",:id => work.id %>
This is the classic Rails method-call look and feel.
This is a method call with two arguments: the string “Click here” and a three-key hash.

You might expect to see curly braces around the hash, like this:
link_to("Click here", { :controller => "work", :action => "show", :id => work.id })
But as a special sugar dispensation, Ruby permits you to end an argument list, when you call a method, with a literal hash without the curly braces.

Why does Ruby allow this special usage?
To facilitate and “prettify” precisely the kind of labeling of method arguments by descriptive name that’s so common in Rails.
Passing arguments as key/value pairs allows you to indicate what the arguments are for.
The elimination of the curly braces gives the idiom a clean look.

Monday, March 19, 2007

Symbol in Ruby on Rails

Symbols are instances of the built-in Ruby class Symbol. They have a literal constructor: the leading colon.
:book, :"Here's how to make a symbol with spaces in it."
You can also create a symbol programmatically, by calling the to_sym method or intern method on a string, as irb shows:
$ "a".to_sym
$ :a

Indeed, symbols are very closely related strings. They share responsibility for representing units of text. However, strings and symbols differ in some important ways:
1, Every time you see the notation for a particularsymbol (:a), you’re seeing the same symbol object represented. If you see two identical-looking string literals"a""a" you’re seeing two different string objects.
2, Symbols,unlike strings, are immutable; you cannot add, remove, or change parts of a symbol. 就是说symbol是不可改变的,而string是可以改变内容的。

It’s worth knowing that symbols are efficient in terms of memory usage and processing time. Strings, on the other hand, come with an entourage of behaviors and capabilities that makes them more expensive to maintain and process (like being made longer than they started out, having their contents changed, and so on).

Using symbols in Rails

You’ll often see symbol literals used as arguments to methods and, especially, as hash keys. Hashes that serve as arguments to methods are a doubly likely candidate for symbol usage.

In the case of method calls in Rails applications, a consensus exists on the syntax of method calls whose arguments are symbols. Using symbol literals is second nature in Rails development.
<%= link_to "Click here", :controller => "book", :action => "show", :id => book.id %>
This is an example of a method argument hash: Each of the symbols is a key, and each of the values to the right is a value. This style of method call is common in Rails application code.

Wednesday, March 14, 2007

Rails Method without parentheses

The parentheses of a method are optional in most cases.
In cases where the syntax is more complex or you call more than one method in a row, you may need the parentheses to make it clear to Ruby what you mean. Most people use parentheses for method calls, but you’ll see method calls with no parentheses in most Rails applications.

dd

Sunday, March 11, 2007

Tell method from field/variable throught English semantic

我从前还想过:Rails的method如果不写(),而只写成belongs_to,怎么与一些variable(比如customer_one)区分呢?现在我想明白了,主要是通过英语语义(semantic)啊!——动词、名词不是很容易就区分开了吗?动词基本就是method,名词就是variable一类的东西了。至少我们可以作为一个编程规范来遵循。

我觉得,写得好的Rails程序,应该就像是读一篇叙事短文(essay)一样,很自然(natural),很顺畅,很易懂。写这样的Rails程序,难道不就是在写作吗?这就是一种Life Style。我希望的生活就是每周有几天坐在Starbucks里,在MacBook Pro 17上这样“写作”。I love Ruby on Rails! and on Mac, because Mac is also a kind of life style.

Saturday, March 10, 2007

The frequent use of symbol objects as method arguments or hash keys

Discussions of Rails coding style always come back to the frequent use of symbol objects (such as :editions) as method arguments and/or hash keys in Rails applications.

In many cases, symbols serves usually with longer argument lists:
<%= link_to "A hyperlink in a view template",:controller => "main",:action => "welcome" %>
In this example, each symbol is associated with a value: the symbol :controller with the string “main”, the symbol :action with the string “welcome”. (The two symbols are hash keys, and the two strings are the corresponding hash values. The entire hash is the second argument to the method; the first argument is the first string: “A hyperlink in a view template”.) This syntax is standard Ruby.

It’s worth noting that the tendency of Rails developers to adhere to certain stylistic conventions becomes more important as the code gets more complex.

Seeing Rails as a domain-specific language PART2: in syntax

A common Rails idiom we’ve already seen, and that you may have seen before, is this: has_many :editions
The syntax used here, with a verb-based directive on the left and what looks like a configuration spec on the right, seems like it could have been created specifically for a system like the Rails framework.
In fact, it’s a simple Ruby method call. The name of the method is has_many, and the argument is a Ruby symbol object. Every time anyone uses this method, it will look essentially the same.

You’ll almost certainly never see this send("has_many", "editions".intern) which is equivalent to the previous example (send is a do-it-yourself way to send a message to an object; intern converts a string object to a symbol object).
This send-based version is, admittedly, far-fetched enough not to be a close call. But you’ll probably never even see this much more slight variation on the original: has_many(:editions).
Many Ruby programmers like to put parentheses around method arguments, even when the parentheses are optional. But when writing Rails applications, even these programmers don’t use the parentheses—not because of Ruby (Ruby doesn’t care), but because leaving the parentheses off is a standard Rails convention.

The common idioms you use in Rails aren’t alternatives to Ruby; they’re alternatives within Ruby.
Long before Rails came along, it was possible to call a method with a symbol argument: method_from_ten_years_ago :symbol. And when Rails did come along, it—that is, its creator, core developers, and developer community—settled on this style of calling such a method. Ruby, mean while, is happy; this method-call style is a mainstream, idiomatic Ruby technique.

Part of learning Ruby as a Rails practitioner is recognizing what’s going on in your code, and the first lesson is that what’s happening is always Ruby. If you see thousands of has_many :editions and never see send("has_many", "editions".intern) or even has_many(:editions), it’s not because Rails has special syntax or rules, but because the Rails community has had the sense to rally around some coding conventions, gaining visual uniformity and a de facto language specificity for Rails development.

Friday, March 09, 2007

First, design a Basic Layout

PROCESS
当开始design views工作时,我们首先设计一个default layout,我个人更倾向于使用
Basic Layout。这个"基础版面"包含了我们在每个view上都需要显示的元素。然后,我们再开始设计每一个单独的view。

Basic Layouts are like meta-templates. They contain general template code that surrounds the specific template code of one or more views. Basic Layout generall contains all kinds of site-wide elements that it would be a nuisance to have to insert individually into every template file.
A typical basic layout might include a header bar, a menu bar, a copyright notice, etc.
The basic layout also contains appropriate XML declarations—again, saving you the trouble of putting them in every template file.

HOW-TO-USE basic layout?
The layout uses a “magic” variable @content_for_layout at the point where you want the specific view inserted.

创建一个文件application.rhtml,放到app/views/layouts 目录下,这就成了整个webapp的default layout。Rails默认application.rhtml为“全站默认版面”。COOL ! Convention over Configuration

Wednesday, March 07, 2007

Modeling the domain in database and Rails

第一步,Diagraming the domain:
1,先把domain都列出来,包括属性。
2,然后用一个个的方块表示出来,就像UML那样,但是不要那么复杂。而且不要用工具来做这件事情,就用铅笔在纸上画出来。

第二步,Initializing the databases:
1,使用root用户创建为该应用创建一个专门的用户,比如dillone。
2,创建一个schema,命名和application的名字一样,只不过字母都小写,比如comeback。
3,赋予dillone对于comeback的读写等权限。
4,使用dillone登陆MySQL,在comeback下创建三个库comeback_development, comeback_production, and comeback_test。遵循Ruby on Rails的命名规范。

第三步,Designing and creating the database tables:
1,创建一个create_tables.sql文件,把要创建的数据库表都用SQL写好。
2,创建一个insert_data.sql文件,把要注入的数据都准备这里,写好SQL语句。
3,创建一个drop_tables.sql文件,用来清除数据库表。
我把这三个文件SQL文件作为“标配”放在每个Rails app的db目录下。
注意:严格写Rails-friendly SQL:

  • Each entity gets a table in the database named after it, but in the plural.
  • Each such entity-matching table has a field called id, which contains aunique integer for each record inserted into the table.
  • Given entity x and entity y, if entity y belongs to entity x, then table y has a field called x_id.
  • The bulk of the fields in any table store the values for that entity’s simple properties (anything that’s a number or a string).
  • 数据库表名全部用小写,字段名全部小写,多词的名字中间用_连接,字段类型也用全部小写,例如:tagsiddescriptionpicturesvarchardatetimeopinion_idfk_op_picture
  • SQL语句中的关键字用全部大写,例如:CONSTRAINTPRIMARY KEYFOREIGN KEYCREATENOT NULLREFERENCESDROP

第四步,Composing the config/database.yml file:
development:
adapter: mysql
database: comeback_development
username: root
password:
host: localhost

test:
...

production:
...
注意:在使用rails appname命令创建一个新应用的时候,appname最好都是小写英文字母,不要首字母大写。这样在这个文件中生成的database: comeback_development 就会是小写的。如此,就与数据库名的大小写一致起来了。

第五步,Writing the Rails model files:
1,Rails creates models semi-automatically. From the top level of the application directory, issue the following commands:
$ ruby script/generate model work
$ ruby script/generate model edition
$ ruby script/generate model composer
You’ll find the three files work.rb, edition.rb, composer.rb in the app/models directory. 这些文件中的内容看上去只是empty definitions of Ruby classes,但实际上they have facilities for setting and retrieving all the entity properties. Rails endows them with those facilities automatically。
2,You need to add directives that tell Rails about the associations between entities—the details of the has and belongs_to relationships.