`
Hooopo
  • 浏览: 329159 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

ruby编码规范

    博客分类:
  • Ruby
阅读更多


Ruby编码规范

File Names

目录、文件名、扩展名

Ruby 源代码

目录名和文件名要用小写字母命名,类和模块以.rb为结尾

例如:

Foo class => foo.rb
Bar module => bar.rb
FooBar class => foobar.rb (Normal Rule)
                foo_bar.rb (Rails Rule)
Foo::Bar class => foo/bar.rb

:Libraries((any arguments?))

non-standard multiple files required by a script should be in one directory, and they should be installed to the standard site-ruby directory or a script’s library directory.

don’t use a current directory for libraries-it is dangerous. since the directory in which script exists can not be specified portably, it is also not suited for libraries.

(你的程序加载的非标准类库文件应该放在一个文件夹内,并且安装到site-ruby文件夹或者是程序的lib文件夹。别用当前文件夹做库文件-这是危险的。既然你的程序所在的目录不能指定,那么lib目录里面也同样。)

File Organization(文件组织)

require (if necessary)
include (if necessary)
classes and modules definition
main
testing code(?) usingFILEidiom
ex:

if FILE == $0
  
end

Beginning Comment(注释)

begin – end style(begin-end型注释)

for file header or footer.(放在文件头或文件结尾)

=begin
  * Name:
  * Description   
  * Author:
  * Date:
  * License:
=end

using ’#’ style(“#”类型注释)

for class/module and method definitions(用在类或模块或方法定义中)

 
# using foo bar
  #
  # foo bar buz.
  # 
  class Foo

    # bar.bar.bar.
    #
    class Bar

       # constructor of Bar.
       #
       def initialize(bar = nil)
         super(bar)
       end 

       def bar
         self
       end

    end

    def initialize()
    end

  end

Indentation(代码缩进)

Line length(每行代码长度)

Max length is about 80 characters.(最大宽度为80字符)

Wrapping Line(wrapping 行)

Break after comma(在逗号处换行)
Break after operator(在操作符处换行)
Comments(注释)

Ruby has two comments style: =begin…=end and ’#’. You should use =begin…=end for Documentation Comments, and ’#’ for both Documentation Comments and Implementation Comments.(ruby有两种注释方式:=begin…=end and ’#’。=begin…=end用于文档注释,而‘#’既可以用于文档注释又可以用于类和模块或者方法的实现注释)

Implementation Comments

h4. Block Comments(块注释)
 
# Here is block comment.
  #
  #  foo, bar, buz.

h4. Single-Line Comments(单行注释)
 
# this is single line comment.

  ## this is also single line comment.

h4. Tailing Comments(行尾注释)
 
if a == 2
    true        # special case
  else
    prime?(a)   # work only for odd a
  end

h3. Documentation Comments h4. Header/Footer(文档注释,放在头部或尾部)
 
=begin

  = FooBar library

  == What's New?
  .....
  ....

  == Installation
  .....
  ....

  ....

  =end

h4. In Class/Module(在类或模块中)
 
# .....
  # ....
  #
  def foo()
    ..
or
  ##
  # .....
  # ....
  #
  def foo()
    ..

h3. Way of no commenting(如何不需要注释)
If you can write simple, short and light scripts, comments may not be necessary.(如果你的代码简短易懂你可以不必注释)

You can let ((the script itself tell everything)), instead of embedding documentation that may confuse readers of your script.(如果你能让你的程序自己说明一切,而不是嵌入让使用你的程序的人抓狂的文档那就更好)

Definitions(声明)

Initialization(初始化)

Ruby variables have no ‘definitions’. So, you should initialize variables.(Ruby变量不需要声明,所以你应该初始化变量)

One initialization per line(每行初始化一个变量)

level = 0
size  = 0

is preferred over(这样是更好的)

level = size = 0

Placement(布局)

Statements(表达式)

Simple Statements(简单的表达式)

Each line should contain at most one statement.(每行应该至少包含一个表达式)

foo = 1  ## Correct
bar = 2  ## Correct
foo = 1; bar = 2  ## AVOID!

Compound Statements(复合表达式)

if-end, if-else-end, if-elsif-else-end Statements(if-end, if-else-end, if-elsif-else-end表达式)

simple example:(简单举例:)

if 
  
end

more complex example:(更复杂一点的例子)

if 
  
elsif 
  
else
  
end

You can put on after when is one-line.(如果表达式只有一行,你可以把if放在后面(puts “Hooopo” if true))

if
block methods(模块方法)

`{...}’ style:(‘{}’类型)

bar.foo(vars){|vars2|
  
}

`do…end’ style:(‘do...end’类型)

bar.foo(vars) do |vars2|
 
end
one-line block:(一行的代码块:)

bar.foo(){|var|   }

case-when Statements(case-when表达式)

Ruby’s case-when (not when-case) does not need ‘break’.(ruby的case-when(不是when-case)不需要break)

case foo
when condition1
  
when condition2
  
else
  
end

begin-rescue-end Statements(regin-rescue-end表达式)

It handles errors (Exceptions).(它是用来处理异常的)

begin
  
rescue FooError => e
  
rescue BazError => e2
  
rescue
  
end

White Space(留白)

Blank Lines(空行)

Between sections of a source file(在几部分源代码之间)
Between class and module definitions(在类和模块定义之间)
Between methods(在方法之间)
Before blocks or single-line comments(在代码块和单行注释之前)
Between logical sections inside a method to improve readability(在方法中用空行来表示算法逻辑以提高可读性)
Blank spaces(空格)

A keyword followed by a parenthesis should be separated by a space.(关键字和后面的括号之间应该用空格分开)

ex:

while (foo.end?) {
  
}

The number of spaces should be balanced.(空格的数量应该保持一致)

a+b      ## Correct
a + b    ## Correct
a+ b     ## AVOID!
a +b     ## AVOID! (Erroneous: interpreted as a(+b))
a += b + c
a = (a + b) / (c * d)
a = b
foo("foo" + buz + bar)

Naming Conventions(命名规范)

Classes/Modules(类和模块)

class and module names should be nouns; in mixed case with the first letter of each internal word capitalized.(类名和模块名用名词;如果是多个词,用每个词首字母大写后链接)

ex:

class Raster,  class Raster::ImageSprite

Methods(方法)

Methods should be verbs. All lower caseASCIIletters with words separated by underscores (’_’)(方法名用动词,用小写ASCII字符以下划线相连)

ex.

run(), run_fast(), obj.background_color()

Variables(变量)

variable names should be all lower caseASCIIletters with words separated by underscore (’_’)(变量名用小写字母和下划线)

ex:
i = 1 some_char = SomeChar.new() table_width = 0.0


Constants(常量)

constants should be all upper case with words separated by underscores (’_’). ((Huh, is there a reasonable background to distinguish constants from a class name which is a constant at the same time?))(常量是由大写字母和下划线组成)

ex:

MIN_LENGTH = 1
DEFAULT_HOST = "foo.example.com"

Omission(补充)

Speaking of ‘Connection Pool’ as a variable, you should decide to prefer name by scope such as the following…(说到想把‘Connection Pool’当做变量,变量形式是由下面哪种上下文决定的)

‘conpool’ for local scope (such as local variable)(‘conpool’在全局范围做全局变量)
’@connection_pool’ for class scope (such as instance variable)(‘@connection_pool’在类内部用做实例变量)
Pragmatic Programming Practices(编码实践)

Using attr_* to access

def foo()
  @foo
end
attr_reader :foo

Without Parenthesis(省略括号)

Some methods are used without parenthesis.(一些方法可以省略括号)

require

ex.

require 'foo/bar'
include
ex.

include FooModule
p

ex.

p foo
attr_*

ex.

attr_reader :foo, :bar

Reduce repetition(减少重复)

When successive lines of a script share something,(当连续的代码有公用的内容时)

x = ModuleA::ClassB::method_c( a )
y = ModuleA::ClassB::method_d( b )

(- ‘function’ => ‘method’ -)

you should make it like this:(你可以这样)

cb = ModuleA::ClassB
x = cb::method_c( a )
y = cb::method_d( b )

You can also do:(也可以这样)

include ModuleA
x = ClassB::method_c(a)
y = ClassB::method_d(b)

Code Example(代码示例)

h3. Ruby Source File Example
 
=begin
    blahdy/blah.rb
    $Id:$

    Copyright (c) 2001 TAKAHASHI Masayoshi

    This is free software; you can copy and distribute and modify
    this program under the term of Ruby's License
    (http://www.ruby-lang.org/LINCENSE.txt)

  =end

  #
  # module description goes here.
  #
  # @version: 1.82
  # @author: TAKAHASHI Masayoshi
  #

  module Blahdy

    class Blah < SomeClass
      # A class implementation comment goes here.

      # CLASS_VAR1 documentation comment
      CLASS_VAR1 = 1;

      # CLASS_VAR2 documentation comment that happens
      # to be more than one line length.
      #
      CLASS_VAR2 = 1;

      # ...constructor Blah documentation comment...
      #
      def initialize()
        ## ...implementation goes here...
      end

      # ...method do_something documentation comment...
      #
      def do_sometiong()
        ## ...implementation goes here...
      end

      # ...method do_something_else documentation comment...
      #
      # @param some_param  description
      #
      def do_something_else(some_param)
        ## ...implementation goes here...
      end

    end

  end


原文地址:http://ruby-programming.learnhub.com/lesson/5017-ruby-coding-convention
在线文档:http://docs.google.com/View?docid=ddf5zdwx_3czk7jhf7
分享到:
评论
4 楼 qxt 2009-09-09  
hooopo翻译的不错
3 楼 shuchaoo 2009-09-07  
哈哈!翻译得确实!不过有原文地址就行了!
2 楼 Hooopo 2009-04-19  
blackwolf1983 写道
老兄,你连贯着翻译行不,看着累死人了。


I See,以后注意。
1 楼 blackwolf1983 2009-04-19  
老兄,你连贯着翻译行不,看着累死人了。

相关推荐

Global site tag (gtag.js) - Google Analytics