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

    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  
class Company
has_many :people
has_one :address
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  
def create
@person = Person.new(params[:person])
@company = Company.new(params[:person][:company])
@address = Address.new(params[:person][:company][:address])
@company.people << @person
@company.address = @address
@company.save!
end

 

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

 

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

 

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

 

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

 

Ruby代码
  1. <%=h @user.email %>  
<%=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  
# File vendor/rails/activerecord/lib/active_record/base.rb, line 2850
def inspect
attributes_as_nice_string = self.class.column_names.collect { |name|
if has_attribute?(name) || new_record?
"#{name}: #{attribute_for_inspect(name)}"
end
}.compact.join(", ")
"#<#{self.class} #{attributes_as_nice_string}>"
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" />   
<label for="male">Male</label>
<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"

转载于:https://www.cnblogs.com/orez88/articles/1520446.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值