诗歌rails之 小语法(添加中)
- if not version.empty?
- return version.gsub('_', '.')
- end
- unless version.empty?
- return version.gsub('_', '.')
- end
- return if version.valid?
- return if not version.valid?
- return unless version.valid?
- if person.xy?
- gender = 'M'
- else
- gender = 'F'
- end
- gender = person.xy? ? 'M' : 'F'
- for item in items
- puts item.to_s
- end
- items.each do |item|
- puts item.to_s
- 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
- (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
- 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!"
- exec('ls *.rb')
- system('ls *.rb')
- `ls *.rb`
- %x(ls *.rb)
- system('echo *')
- system('echo', '*')
- /[ \t]+$/i
- %r([ \t]+$)i
- Regexp.new(
- "[ \t]+$",
- Regexp::IGNORECASE
- )
- ["one", "two", "three"]
- %w(one two three)
- 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]
- $global_variable
- @instance_variable
- @@class_variable
- CONSTANT
- local_variable
- with_block a, b {
- ...
- }
- # with_block(a, b { ... })
- with_block a, b do
- ...
- end
- # with_block(a, b) { ... }
- puts begin
- t = Time.new
- t.to_s
- end
- def capitalizer(value)
- yield value.capitalize
- end
- capitalizer('ruby') do |language|
- puts language
- end
- def capitalizer(value)
- value = value.capitalize
- if block_given?
- yield value
- else
- value
- end
- end
- def capitalizer(value)
- yield value.capitalize
- end
- def capitalizer(value, &block)
- yield value.capitalize
- end
- proc_adder = Proc.new {
- return i + i
- }
- lambda_adder = lambda {
- return i + i
- }
- visits = 0
- visit = lambda { |i| visits += i }
- visit.call 3
- begin
- # code
- rescue AnError
- # handle exception
- rescue AnotherError
- # handle exception
- else
- # only if there were no exceptions
- ensure
- # always, regardless of exceptions
- end
- def connect
- @handle = Connection.new
- rescue
- raise ConnectionError
- end
- class Person
- attr_accessor :name
- def initialize(first, last)
- name = first + ' ' + last
- end
- end
- person = Person.new('Alex', 'Chin')
- class Person
- attr_accessor :name
- class Address
- attr_accessor :address, :zip
- end
- end
- address = Person::Address.new
- class Person
- attr_accessor :name
- end
- class Student < Person
- attr_accessor :gpa
- end
- student = Student.new
- student.name = 'Alex Chin'
- module Demographics
- attr_accessor :dob
- def age
- (Date.today - dob).to_i / 365
- end
- end
- class Person
- include Demographics
- end
- person = Person.new
- person.extend Demographics
- 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被迫存到数据库)
____________________________________________________________________________________
- 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默认值不同。
比如有两个对象之间的关联是这样的:
- class Company
- has_many :people
- has_one :address
- end
当我们在controller里面这样创建它们时:
- 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。
所以,我们要显示得指定:
- has_one :address, :validate => true
7. 不要忘了escape用户的输入数据。为了正确显示以及安全问题。
- <%=h @user.email %>
8. has_one 和 belongs_to
has_one关联,对应的外键在对方表中。
belongs_to关联,外键在自身表中。
9. ActiveRecord::Base中的inspect方法
看源码
- # 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.
- <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"