天天看點

ruby trickes(keep adding)

some ruby tricke:

1.shorter regular expression

string = "I am strong..."
puts string[/(.*?)(\.+)/, 1]   # => I am strong
           

2.add methods to class

class String
  def test1
     "test1"
  end
end
puts "".test1   # => test1
           

3.rescue in method

def test
   ss
 rescue
   puts "undefine ss"
 end
 test   # => undefine ss
           

4.symple rescue

a.downcase rescue puts "something is wrong"  # => something is wrong
           

5.rake task with params

desc 'For test'
namespace :gary do
  task :test => :environment do
    puts "I am strong I am #{ENV['type']}"
  end
end
           

#use rake gary:test type="gary"

6.source annotations

good way to mark annotations

class PagePart < ActiveRecord::Base
  #TODO
  #code TODO
  #FIXME
  #code FIXME
  #OPTIMIZE
  #code OPTIMIZE
  end      

 run "rake notes" in console will get:

app/models/page_part.rb:

  * [  2] [TODO]

  * [  4] [FIXME]

  * [  7] [OPTIMIZE]