诗歌rails之 小语法(添加中)

Syntax Sugar
Java代码
  1. if not version.empty?  
  2.   return version.gsub('_''.')  
  3. end  
  4.   
  5. unless version.empty?  
  6.   return version.gsub('_''.')  
  7. end  
Java代码
  1. return if version.valid?  
  2.   
  3. return if not version.valid?  
  4.   
  5. return unless version.valid?  
Java代码
  1. if person.xy?  
  2.   gender = 'M'  
  3. else  
  4.   gender = 'F'  
  5. end  
  6.   
  7. gender = person.xy? ? 'M' : 'F'  
Java代码
  1. for item in items  
  2.   puts item.to_s  
  3. end  
  4.   
  5. items.each do |item|  
  6.   puts item.to_s  
  7. end  
Java代码
  1. for i in 1..3  
  2.   quantity = gets.chomp.to_i  
  3.   
  4.   next if quantity.zero?  
  5.   redo if quantity > LIMIT  
  6.   retry if quantity == RESTART  
  7.   break if quantity == FINISHED  
  8.   
  9.   quantities[i] = quantity  
  10. end  
Java代码
  1. (1..5).collect { |i| i * i }  
  2. # [1491625]  
  3. (1..5).detect { |i| i % 2 == 0 }  
  4. 2  
  5. (1..5).select { |i| i % 2 == 0 }  
  6. # [24]  
  7. (1..5).reject { |i| i % 2 == 0 }  
  8. # [135]  
  9. (1..5).inject { |sum, n| sum + n }  
  10. 15  
Alternative Syntax
Java代码
  1. puts '"Hello World!"\n'  
  2.   # "Hello World!"\n  
  3. puts "\"Hello World!\"\n"  
  4.   # "Hello World!"  
  5. puts %q("Hello World!"\n)  
  6.   # "Hello World!"\n  
  7. puts %Q("Hello World!"\n)  
  8.   # "Hello World!"  
  9. puts %!"Hello World\!"\n!  
  10.   # "Hello World!"  
Java代码
  1. exec('ls *.rb')  
  2. system('ls *.rb')  
  3. `ls *.rb`  
  4. %x(ls *.rb)  
  5.   
  6. system('echo *')  
  7. system('echo''*')  
Java代码
  1. /[ \t]+$/i  
  2.   
  3. %r([ \t]+$)i  
  4.   
  5. Regexp.new(  
  6.   "[ \t]+$",  
  7.   Regexp::IGNORECASE  
  8. )  
Java代码
  1. ["one""two""three"]  
  2.   
  3. %w(one two three)  
Java代码
  1. 1..5  
  2. Range.new(15)  
  3.   # (1..5).to_a == [12345]  
  4.   
  5. 1...5  
  6. Range.new(15true)  
  7.   # (1...5).to_a == [1234]  
Variables
Java代码
  1. $global_variable  
  2.   
  3. @instance_variable  
  4.   
  5. @@class_variable  
  6.   
  7. CONSTANT  
  8.   
  9. local_variable  
Blocks & Closures
Java代码
  1. with_block a, b {  
  2.   ...  
  3. }  
  4. # with_block(a, b { ... })  
  5.   
  6. with_block a, b do  
  7.   ...  
  8. end  
  9. # with_block(a, b) { ... }  
Java代码
  1. puts begin  
  2.   t = Time.new  
  3.   t.to_s  
  4. end  
Java代码
  1. def capitalizer(value)  
  2.   yield value.capitalize  
  3. end  
  4.   
  5. capitalizer('ruby'do |language|  
  6.   puts language  
  7. end  
Java代码
  1. def capitalizer(value)  
  2.   value = value.capitalize  
  3.   
  4.   if block_given?  
  5.     yield value  
  6.   else  
  7.     value  
  8.   end  
  9. end  
Java代码
  1. def capitalizer(value)  
  2.   yield value.capitalize  
  3. end  
  4.   
  5. def capitalizer(value, &block)  
  6.   yield value.capitalize  
  7. end  
Java代码
  1. proc_adder = Proc.new {  
  2.   return i + i  
  3. }  
  4.   
  5. lambda_adder = lambda {  
  6.   return i + i  
  7. }  
Java代码
  1. visits = 0  
  2.   
  3. visit = lambda { |i| visits += i }  
  4.   
  5. visit.call 3  
Exceptions
Java代码
  1. begin  
  2.   # code  
  3. rescue AnError  
  4.   # handle exception  
  5. rescue AnotherError  
  6.   # handle exception  
  7. else  
  8.   # only if there were no exceptions  
  9. ensure  
  10.   # always, regardless of exceptions  
  11. end  
Java代码
  1. def connect  
  2.   @handle = Connection.new  
  3. rescue  
  4.   raise ConnectionError  
  5. end  
Classes
Java代码
  1. class Person  
  2.   attr_accessor :name  
  3.   
  4.   def initialize(first, last)  
  5.     name = first + ' ' + last  
  6.   end  
  7. end  
  8.   
  9. person = Person.new('Alex''Chin')  
Java代码
  1. class Person  
  2.   attr_accessor :name  
  3.   
  4.   class Address  
  5.     attr_accessor :address, :zip  
  6.   end  
  7. end  
  8.   
  9. address = Person::Address.new  
Java代码
  1. class Person  
  2.   attr_accessor :name  
  3. end  
  4.   
  5. class Student < Person  
  6.   attr_accessor :gpa  
  7. end  
  8.   
  9. student = Student.new  
  10. student.name = 'Alex Chin'  
Modules
Java代码
  1. module Demographics  
  2.   attr_accessor :dob  
  3.   
  4.   def age  
  5.     (Date.today - dob).to_i / 365  
  6.   end  
  7. end  
  8.   
  9. class Person  
  10.   include Demographics  
  11. end  
Java代码
  1. person = Person.new  
  2. person.extend Demographics  
Java代码
  1. module Demographics  
  2.   def self.included(base)  
  3.     base.extend ClassMethods  
  4.   end  
  5.   
  6.   module ClassMethods  
  7.     def years_since(date)  
  8.       (Date.today - date).to_i / 365  
  9.     end  
  10.   end  
  11. end  

  什么时候对象会存到数据库?

  1st case:

  new_subcomponent = Subcomponent.new

  new_standard = Standard.new

  new_subcomponent.standard = new_standard     (此步之后new_standard取不到subcomponents)

  new_standard.subcomponents << new_subcomponent (当都没有存到数据库之前,需要进行双相关联才能互取)

  2nd case:

  subcomponent = Subcomponent.find(1)

  new_standard = Standard.new

  subcomponent.standard = new_standard     (此步之后new_standard可取到subcomponents,此时subcomponent需要一个standard的id,standard被迫存到数据库)

____________________________________________________________________________________

how to set rails environment variable? it's just easy to add a constant in environment.rb.
Ruby代码
  1. LINGKOU_ENV = {  
  2.           :image_root => "/images"   
  3.  }  

    and you can then access this environment anywhere else

____________________________________________________________________________________________________________________________

1. model validates相关

 

    model的validates先于before_save, before_create等。

 

    validates_acceptance_of :terms_of_service    # 对于checkbox的印证,再合适不过了。

 

    validates_associated  #对assocation的validates。

 

    如何定制你自己的validates?

 

    validates_positive_or_zero :number  #在lib/validations.rb里面加上这个方法即可。

 

    或者 validates :your_method  #在这个methods里面加上印证,如果失败,往erros里面添加错误信息。

 

2. integrate_views

 

    对于rspec controller测试,在必要的地方加上integrate_views,否则页面上的错误将被忽视。

 

    比如,你想验证在某种条件下,页面上会出现某些text,可以用这种方法:

 

    response.should include_text("")

 

 

3. helper 中的方法用于view

 

    根据rails的convention,相应的helper会自然的被view include。

 

4. self[:type]

 

    为什么不能用self.type?因为type是ruby的保留方法,它会返回类型信息。所以,要取得对象内的type attribute,就得用self[:type]。可以看出,所有的attributes,都可以用hash的方式取出。

 

5. attributes_protected  attributes_accessible

 

    如果你想让某些值可以被mass assign,比如这样person = Person.new(params[:person]),那么你得把它们声明在attributes_accessible里。当然,你也可以不声明任何的attributes,不过这样会给你带来可能的安全问题。

 

    显而易见,如果只有少部分attributes不允许被mass assign,那么把这些放在attributes_protected里更加方便。

 

6. has_many和has_one的validate默认值不同。

 

    比如有两个对象之间的关联是这样的:

 

 

Ruby代码
  1. class Company  
  2.   
  3.     has_many :people  
  4.     has_one :address  
  5.   
  6. end  

 

    当我们在controller里面这样创建它们时:

 

Ruby代码
  1. def create  
  2.   
  3.    @person = Person.new(params[:person])  
  4.    @company = Company.new(params[:person][:company])  
  5.    @address = Address.new(params[:person][:company][:address])  
  6.   
  7.    @company.people << @person  
  8.    @company.address = @address  
  9.      
  10.    @company.save!  
  11.      
  12. end  

 

    不要以为address会被验证,其实对于has_one关联,默认的validate为false。

 

    所以,我们要显示得指定:

 

Ruby代码
  1. has_one :address:validate => true  

 

7. 不要忘了escape用户的输入数据。为了正确显示以及安全问题。

 

Ruby代码
  1. <%=h @user.email %>  

 

8. has_one 和 belongs_to

 

    has_one关联,对应的外键在对方表中。

 

    belongs_to关联,外键在自身表中。

 

9. ActiveRecord::Base中的inspect方法

 

   看源码

 

 

Ruby代码
  1. # File vendor/rails/activerecord/lib/active_record/base.rb, line 2850  
  2. def inspect  
  3.        attributes_as_nice_string = self.class.column_names.collect { |name|  
  4.         if has_attribute?(name) || new_record?  
  5.              "#{name}: #{attribute_for_inspect(name)}"  
  6.           end  
  7.          }.compact.join(", ")  
  8.         "#<#{self.class} #{attributes_as_nice_string}>"  
  9. en  
 

 

    明白了么,如果是不在数据库中的attribute,它是不会打出来给你看的~~~

 

10. FormHelper  FormBuilder

 

      好吧,原来FormHelper已经取代FormBuilder。代码里面的FormBuilder只是为了向后兼容。

 

11. label

 

      这个跟rails无关,html中的label之所以要ID对应,是因为

 

      The label element does not render as anything special for the user. However, it provides a usability improvement for mouse users, because if the user clicks on the text within the label element, it toggles the control.

 

 

Html代码
  1. <label for="male">Male</label>  
  2. <input type="radio" name="sex" id="male" />   

Caching multiple javascript into one

    javascript_include_tag :all, :cache => true

    javascript_include_tag "prototype", "cart", "checkout", :cache => "shop"

posted @ 2009-07-10 12:17  麦飞  阅读(311)  评论(0编辑  收藏  举报