2008年6月15日 星期日

中文字比較

一個中文字利用3byte表示,
因此若要比較a="我愛妳"和b="妳愛我"的字首,
要比較  a[0]==b[0] && a[1]==b[1] && a[2] == b[2]

2008年6月11日 星期三

rails API

api.rubyonrails.org

included & extend

included:
the method defines the action to do when the class or module get included 

extend:
extend the class's ability by including module
ex:
module M
end
Class C
end
c= C.new
c.extend(M)

note:  use object to extend, get instance method, 
           use class to extend, get class method

class_eval

define method for class
ex:
A=Class.new
A.class_eval do
      def  test
          puts "test"
      end
end
a=A.new
a.test
--->  test

2008年6月10日 星期二

partial

include the view in other file

ex:
render :partial=> "books"
render the view in _books.html.erb (  the partial view file must 
start with _ )

ex:
render :partial => "rabbit/list"
render the view in different directory

note: the variable partial view can access is the variable the master view can access 

2008年6月8日 星期日

self & method

when there is a method ending with =,  such as test=, 
and there is another method  run
In the definition of run, there are two conditions:
(1)  test=3
      this means test is a local variable
(2) self.test=2
      this will call test method with parameter 2

Hence, when calling the method ending with = in the method definition, we can not omit self

association

use class methods( has_one, belongs_to, has_many,  has_and_belongs_to_many)
to create instance methods

has_one & belongs_to

has_many & belongs_to

has_and_belongs_to_many

the parameter for these methods:
:dependent => true
for delete.  
ex:
class Customer <>
         has_many  :orders,
                             :dependent=>true
end
if the customer A is deleted, its orders are also deleted

:order
ex:
:order=>"created_at ASC"
ascending order according to created_at field




2008年5月26日 星期一

symbol

change string to symbol:
use to_sym or intern
ex:
"test".to_sym
--->  :test

change symbol to string
method 1: use to_s
method 2: use #{ }
ex:
"#{:abc}"
---> "abc"

2008年5月25日 星期日

methods

methods:
A.methods:
show class methods
A.methods(false):
only show class methods of A, not including inherited methods
a.methods:
show instance methods of a

instance_methods:
A.instance_methods equals a.methods
A.instance_methods(false):
show only instance_methods 0f A, not including inherited methods

private_methods, public_methods, protected_methods, singleton_methods



compare: equal?, Comparable module

check  whether  two objects are the same object

define how to compare
use Comparable module & define <=> method
the return value of method <=> ,  1, 0 , & -1 decides greater than, equal than, & less than
ex:
class Rabbit
     include Comparable 
     attr_accessor  :name

     def  <=> (other_rabbit)
          if  self.name <>
                  -1
          elsif  self.name > other_rabbit.name
                  1
          else
                  0
          end 
     end
end

if the thing to compare know how to compare, there is a shorter definition
ex:
def  <=> (other_rabbit)
       self.name<=> other_rabbit.name
end


true, false & nil

In Ruby, nil & false  are the only two objects have boolean value of false

2008年5月24日 星期六

for, each

for
ex:
for a in [1,2,3]
puts a
end

each
ex:
[1,2,3].each do |i|
puts i
end

loop, while, until

loop
ex:
loop do
    a=a+1
    break if a>3
end

loop do 
     a=a+1
     next if a <3
     break
end

while
ex:
while a<3
end

until:
ex:
until a>3
end



case

ex:
case  name
when "peter"
puts "peter"
when "andy"
puts  "andy"
else
puts  "others"
end

how it works
translate to 
if "peter" === name

note: the === method can be customarily defined

private & protected methods

private method:
(1) use private  with argument
ex:
private  :test,  :run

(2) use private
ex:
private
def  test
end

def run 
end
the methods after private are private

protected method:
use protected

can call the object's protected method as long as self is an instance of the same class  as the object whose protected method is called


global variable

start with $

built-in global variables:
$: the directories that make up the path Ruby searches for external file

$0: name of the file Ruby is executing

$$: process id of Ruby process
ps:  use English.rb to replace these built-in global variables with meaningful names

2008年5月22日 星期四

instance variable

In the class definition, the instance variable insides method & outside method are not the same

the instance variable inside method belongs to object
the instance variable outside method belongs to class

class & self

In the class definition, self = class
so Rabbit.run = self.run

In the class-method definition,  self = class

:: access

(1) access constant

(2) access nested class
ex:
module ActionController
       module  Routing
              class Route
....
end

ActionController::Routing::Route.new

ex:
class  Rabbit <>
end

class ApplicationController <>
end

(3) access nested module

method_missing

If the message sent to object is the message object can't understand, it will trigger execution of method_missing

Rails use method_missing to look up database & create methods 

2008年5月20日 星期二

super keyword

call the method of superclass or module

ex:
class A
    def test(num)
           puts "A test #{num}"
    end
end

class B  <>
     def test( num)
           super
   puts "B test #{num}"
     end
end
b= B.new
b.test(2)
--->  A test 2
         B  test 2

super will pass the parameters to superclass or module

another usage:  call super will parameters to pass specific parameters


root module & root class

root class:  Object
root module:  Kernel

attr_reader, attr_writer,

the getter:
ex:
attr_reader  :name

the setter:
ex:
attr_writer :name

getter & setter:
ex:
attr_accessor :name

2008年5月18日 星期日

respond_to?

check if the object has specific method
ex:
test.respond_to?("methods")
---> true

object_id

Object's method
return the id of the object
ex:
a=3
b=a
now a & b have the same object id 

2008年5月14日 星期三

the data controller can access

CGI data:
access @params  via params method
ex:
params[:id],  params[:user][:age]

session information:
access @session via session method
ex:
session['user']

model's data
ex: 
model Car has a name field
car is an instance of model Car
car.name


2008年5月13日 星期二

mysql command

start mySQL:
sudo /usr/local/mysql/bin mysqld_safe

stop mySQL:
sudo /usr/local/mysql/bin mysqladmin shutdown

create an account for a database:
grant  all on *.*  to 'deeplove'@'localhost'  identified by  '111';
create new user account "deeplove", with password 111, 
connect to database from "localhost", all  means you can do anything( SELECT, INSERT, ...)
*.* means you can connect to every database ( Dog.* means you can only connect to Dog database)

join:
collect information from two or more tables & present it as a single table
left join  ...  on ...  :
return all matching rows from first table, even if there are no matching rows in the second table

group by
combine two tables using the filed both tables have 

select syntax
select columns from table where condition

2008年5月12日 星期一

rails source code location in mac

/Library/Ruby/Gems/1.8/gems/rails-2.0.2

/Library/Ruby/Gems/1.8/gems/actionpack-2.0.2/lib
action_controller.rb & action_view.rb are in this folder

/Library/Ruby/Gems/1.8/gems/activerecord-2.0.2

require vs load

ex:
require  'test'
require  'test'
second require is useless

ex:
load  'test'
load  'test'
second load will load test again 

puts and print

puts will print new line
print will not

gets

get a line of input( in string)

paginate

divide large collections into pages

ex:
in the controller:
def  car_list
     @car_pages,  @cars = paginate ( :cars,  :order_by => 'name')
end
@car_pages is a paginator object.
@cars contain 10 rows.  ( default is 10 rows)

in the view:
table
  for car in @cars
       tr  td  car.name  td  tr
  end
table
hr
   pagination_links(@car_pages) 
hr
pagination_links  show the current page, two page numbers on either side of current page, first page & last page 

2008年5月11日 星期日

helper

remove the logic from view to helper

ex:
module   TestHelper
              def  run
                       "test_title"
              end
end

in the test controller
<%=  run  %>

originally the function in the helper file can only be accessed by related view,
but there is method for sharing helper

sharing helper:
method 1:
define the method in application_helper.rb

method  2:
ex:
add  TestHelper  to controller
helper  :test

h( )

escape html tag
ex:
<%= "<b>test</b>"% >
show test in bold
<%= h("<b>test</b>") %>
show  <b%>test</b>

xml template

builder template:

xml builder:
xml.tagName

ex:
xml.productName ( "car")
-->   <productName>car</productName>

cache

the page is cached .
Hence,  after first request, the same URL's response is deliver from cache, rails is no involved 

3 caches:
page caching,  action caching  & fragment caching

page caching:
ex:
caches_page  :test

action caching:
execute filter before return cached pages
ex:
before_filter  :test_filter
caches_action  :test2

turn on caching( in environment.rb) :
ActionController::Base.perform_caching = true


removing cache:
expire_page
ex:
expire_page  :action=>test

expire_action:
ex:
expire_action :action=>test2

sweeper:
observe the model. When the model is changed, the sweeper expire the cached pages that 
depend on the model

ex:
in app/models
class  TestSweeper <>
         observe  Car
         def  after_create(car)
                   expire_car_page
         end
end

in app/controllers
class Test <>
    cache_sweeper  :test_sweeper
end

the location to store cached pages:
ex:
http://localhost:3000/content/show/1  is stored in app/public/content/show/1.html




verification

verify that certain conditions are met

verify:
ex:
verify   :session => :user_id,
             :add_flash => { :note=> "you are wrong" }
             :redirect_to => index
if the session does not contain key :user_id,  
a note is added to flash & request is redirected to index

2008年5月10日 星期六

redirect_to

three forms:

1. redirect_to ( options ... )
ex:
redirect_to (:action=>jump)

2. redirect_to (path)
ex:
redirect_to ("/test/run")
show /view/test/run.html.erb

3. redirect_to( url)
ex:
redirect_to("http://www.google.com")

logger

4 levels:
warn,  info,  error,  fatal
ex
logger.warn("invalid number")

log file:
/log/development.log,  /log/test.log,  /log/production.log

group controllers into module

For example,  two directories  Test1  & Test2,
controller Rabbit1Controller in Test1,  Rabbit2Controller in Test2

url_for( :controller=> "rabbit1", :action=>"jump")
--->  http://localhost:3000/test1/rabbit1/jump

2008年5月8日 星期四

rails program load sequence

ex:  http://localhost:3000/rabbit/list
when getting request above, the load sequence is as follows:
1. load rabbit_controller.rb

2. instantiate an object of class RabbitController

3. look in app/helpers for rabbit_helper.rb.
    If found, the module RabbitHelper is mixed into RabbitController

4 look in app/models for rabbit.rb. If found, load it

define the models used in controller:
ex:
model  :car,  :clothes

define the observers used in controller:
ex:
observer   :car_observer

define the model used in controller 

flash

the value stored in the flash in the first request is available in the second request.
After processing 2nd request, the value is removed from flash

main use:
error message

ex:
def  test
    flash[:note] = "error"
    redirect_to :action=>test2
end

test2.html.erb
<%= @flash[:note] %>

session & cookie

controller action, view tempelate, render

controller裡定義的action(method)會對應到view下的templelate
例如index對應到index.html.erb
所以如果controller要做的action是index,
browser顯示的網頁即是index.html.erb

為何action是index,即顯示index.html.erb ?
一般在controller定義的action,
例如index,
預設都會呼叫如下的render 指令,
所以controller在做index action時,
即會顯示index.html.erb

render command:
ex:
render :template => “test/index”
顯示 view/test/index.html.erb
:template後接的path是相對於view
如果改成:file,之後的path是絕對路徑

如果render顯示的是另一個page,
改變的是顯示的內容,
URL還是原page的URL,
若要連URL一起改變,
要代用redirect_to

ex:
render  :action=>”index”
顯示 index.html.erb
(注意render不會做action,只會顯示頁面,
若要做action,要用redirect_to) 

ex:
render :text=> “hello”
顯示hello

:status
ex:
render  :status=>404
html response的status

可以不定義action,但一定要定義顯示的頁面
例如index action沒定義,
但index.html.erb有定義,
則browser還是可以顯示正確的頁面。

the instance variable of the controller is available in the template
the template can access instance variable set in the controller action. Hence, rabbit's view can access dog's controller's instance variable if it is triggered from dog's action

form helper

form_tag:   和model無關
ex:
<% form_tag do %>
<p><label for=”login”>Login</label>
<%= text_field_tag  ‘login’ %></p>
<p><%= submit_tag ‘Log in’ %> </p>
<% end %>

1.如果form_tag後沒有接action,那麼action就是form目前所在的
  頁面對應到的method
2存取使用者輸入的資料,例如param, such as params[:login], log對應
  到text_filed_tag的值

ex:
<% form_tag  :action=>'play'  do %>
<p><label for=”login”>Login</label>
<%= text_field_tag  'car',  ‘login’ %></p>
<p><%= submit_tag ‘Log in’ %> </p>
<% end %>
1. text_field_tag後接的car是model name,login是car的attribute
   , the controller can access it using  params[:car][:login]


submit_tag 後接的字串是submit button上的文字

form_for : 和model有關
ex:
 <% form_for :person, @person, 
    :url => { :action => "create" } do |f| %>
      <%= f.text_field :first_name %>
      <%= f.text_field :last_name %>
      <%= submit_tag 'Create' %>
  <% end %>

對應的html
 <form action="/persons/create" method="post">
      <input id="person_first_name" name="person[first_name]" size="30" type="text" />
      <input id="person_last_name" name="person[last_name]" size="30" type="text" />
    <input name="commit" type="submit" value="Create" />
    </form>

存取使用者輸入的資料:
以上面為例子,Person.new(params[:person] )

ex:
<% form_for :rabbit ,  url=>{ :controller=>:rabbit, :action=>create},
      :html=> {:id=>’peter’ } do |t| %>
對應的html
<form action="/rabbit/create" id="peter" method="post">

text_field & text_field_tag
regular form helper is usually end with tag
model form helper is usually not end with tag 
ex:
text_field :customer, :name
create customer in the action of controller:
@customer = Customer.new(params[:customer])

text_field:
hidden_field:
password_field:
text_area:
radio_button(:variable, :attribute,  tag_value,  options):
check_box:


select:
selection list
ex:



save & save!

save object into database

save! will raise a exception if the save is not successful 
save only return false when save is not successful 

update_attributes, updat & update_all, save

update column of table
update will change the state of object and database

update_attributes
ex:
rabbit.update_attributes( :name=> "peter",  :age=> 13)

update
ex:
Rabbit.update( 5, :name=>"peter", :age=>13)
update rabbit with id =5

update_all:
Rabbit.update_all(:name=>"peter")
all rabbits' names become "peter"

use save:
ex:
rabbit.name="peter"
rabbit.save
use save to update database

2008年5月7日 星期三

find method in rails


without dynamic find_by_all

@task = Task.find( :all, :conditions=> [‘complete= ?’ ,false] )

with dynamic find_by_all
@task = Task.find_all_by_complete(false)

without dynamic find_by
@task = Task.find( :first, :conditions=> [‘complete= ?’ ,false],
                                :order=>’created_at DESC’ )

with dynamic find_by
@task = Task.find_by_complete(false,   :order=>’created_at DESC’)

find by id
find( params[:id], :conditions=>[“name=?”, “peter” ] )

find through association
ex:
project has many tasks
task belongs to project

without association:
@task = Task.find(:all, :conditions=> [ ‘proect_id=? AND complete =?’  , @project_id,  false] )
with association:
@project = Project.find(params[:id])
@task = @project.tasks.find(:all,     :conditions=>[‘complete=?’,   false])
or
@task = @project.tasks.find_all_by_complete(false) 

find method in model
將find method定義在model比較好
ex:
Task的model
def  self.find_incompletet 
    find_all_by_complete(false, :order=>’created_at DESC’ )
end    
 注意: 此find method要定義成class method
          到時候可呼叫 @project.tasks.find_incomplete
          若定義成instance method,則會error

find_by_sql:
use sql syntax in the find_by_sql
pros:  faster

ActionMailer & gmail

use ActionMailer to send email ( with gmail)
ex:
require 'rubygems' 
require 'action_mailer' 
require 'smtp_tls'

class Emailer <>
  def test_email(email_address, email_body) 
    recipients(email_address) 
    from "peter@gmail.com" 
    subject "This is a test e-mail" 
    body email_body 
  end 
end

ActionMailer::Base.smtp_settings = { 
  :address => "smtp.gmail.com", 
  #25 ,465
  :port => 587, 
  #:domain => "localhost.localdomain",
  :authentication => :plain, 
  :user_name => "peter", 
  :password => "xxxxxx", 
}

Emailer.deliver_test_email('jack@yahoo.com', 'this is a test email')

smtp_tls is for sending email from gmail

send by gmail in rails:
1. add smtp_tls.rb in configure directory
2. add  require 'smtp_tls'  in environment.rb

access table's column in the model

ex:
the table rabbits has column  name
the model  rabbit can access name by  self.name

before_create

like before_filter,  but before_create is used in the model

is executed when the record is created

filter

define the actions to do before(after) some actions

two define syntaxes:
1. use method to define filter
2. use class to define filter

before_filter:
define the actions to do before some actions
ex:
before_filter :check
do check before any action. 
If check return false,  the action is not done

after_filter:
define the actions to do after some actions

filter & inheritance :
B extends A, then A's filter is done first, then B's filter is done

filter's scope:
only for some actions:
ex:
before_filter :check,  :only=>:index
before_filter :check,  :only=>[:index,  :new]

not for some actions:
before_filter :check,  :except=>:index

around_filter:
the combination of before_filter & after_filter
ex:
class TestFilter
    def  before(controller)
         @name="peter"
    end

    def  after(controller)
         @name ="andy"
    end
end

around filter  TestFilter.new

2008年5月6日 星期二

mongrel

a web server 

faster than WEBrick

install:
sudo gem install mongrel

start:
mongrel_rails  start

start options:
-d:  run in background 
-e:  rails environment to run

stop:
mongrel_rails stop

restart:
mongrel_rails restart

link

link to css
stylesheet_link_tag   'test'
test.css is in /public /stylesheets

link to image
image_tag  'test.jpg'
test.jpg is in  /public/images

link to page
link_to  "go to" ,  :controller=>"test", :action=>"index"

link to javascript:
javascript_indclude_tag  :defaults
link to prototype, effects, dragdrop, controls, application in /public/javascripts

url_for:
generate url according to route.rb
ex:
url_for ( :controller=>"rabbit", :action=>jump )
-->  http://localhost:3000/rabbit/jump 

layout

the layout for all website:
method 1:
use application.html.erb, it is the layout for all website
method 2:
ex:
define the layout test.html.erb
add following line to app/controllers/application.rb
layout "test"

yield:
render the template.  The template is rendered at this location within layout

layout can access variable defined in the template 


rails routing

config/route.rb

set the page of webSite root:
map.root  :controller => "test"
note: remember to remove  /public/index.html

default route
map.connect  ':controller/:action/:id'
map.connect  ':controller/:action/:id.:format'
ex: 
http://localhost:3000/test/apple/3.xml
test map to :controller,  apple map to :action, 3 map to :id, xml map to :format
the parameter get from default route:
params[:controller],  params[:action],  params[:id]

set controller & action:
map.connect  'test/:var',  :controller=>rabbit,  :action=>jump
ex: 
http://localhost:3000/test/apple
apple map to :var

:requirements
set the requirement the component must match
ex:
map.connect  ":day",  :requirements => { :day => /[0-3]?\d }

the pattern for remaining components in the URL ( not specify in the URL)
use * with a name
ex:
map.connect  "*anything",  :action=> "unknown_action"

named route:
replace map.connect with map.routeName,
replace  url_for with routeName_url
ex:
 map.run  :controller=>"test", :action=>"run"
 redirect_to (run_url)
 link_to(" run" , run_url )




generate command, rails command, rake command, console

rails:
rails -d mysql  test
create files for rails project, using mysql  
( default is sqlite)

generate:
script/generate  controller rabbit index 
create rabbit controller with index action,  rabbit test, rabbit helper  & index template in the rabbit view

rake:
rake db:migrate
create the table in the database based on the migration file

script/console:
-s:  Any modifications you make will be rolled back on exit

erube

deal with the file includes html & ruby code

install:

set link:
sudo ln -s /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/eruby /usr/local/bin/eruby

combine apache & erube:
set link:
     ln -s /usr/local/bin/eruby /Library/WebServer/CGI-Executables/eruby
edit /etc/apache2/httpd.conf
(1) red part
    
    AllowOverride None
    Options FollowSymLinks
(2) add following to 
    AddHandler rubypage .erb .rhtml
    Action rubypage /cgi-bin/eruby

run eruby:
eruby  test.html.erb

erb 

cgi

require 'cgi'

cgi's method name equals the tag it create
Hence, cgi.h1 create h1 tag

use + to combine the same level tag

ex:
cgi = CGI.new('html4')
cgi.out do
    cgi.html do
          cgi.head  do
                 "test head"
          end  +
          cgi.body do
                cgi.h1 {  "hello" } 
          end
    end
end

--->
<HTML><HEAD>test head </HEAD><BODY><H1>hello</H1></BODY></HTML>

cgi.params:
represent query string
ex:
http://localhost/cig-bin/test.cgi?name=peter&age=3
cgi.params =  { 'name'=>'peter',   'age'=>'3' }


2008年5月5日 星期一

send

dynamically call a method with unknown name
ex:
def  test_rabbit(name)
       puts name
}
a="rabbit"
send("test_#{a}", "peter")
---->  peter
1st parameter is method name,  second parameter is parameter

usage: get method from user input

note:
some_object.send(  function_name,  args )  is the same as 
some_object.function_name(args )

2008年5月4日 星期日

show message with debug

write to stand error
ex:
warn "error"  if ($DEBUG)

enable $DEBUG
ruby -d 

xml library

require 'rexml/document'

<=>

ex:
3 <=> 3
--->  0
3 <=> 4
---> -1
4 <=> 3
--->  1

2008年5月3日 星期六

test

require  'test/unit'

assert_equal
if two parameter are equal, return true
ex:
assert_equal("dd", "ee")

ri command

read the information about ruby API
ex:
ri  Test::Unit

alias

define another method name

ex:

alias  :puts_2  :puts

puts_2  “ hello”

--->  “hello”

system

call extern program 


ex:

System( “ls”)


method naming ( end with ? or ! )

method that returns true or false ends with ?

ex: 

empty?


method that changes the state of the object ends with!

ex: 

save!


built-in methods with !

upcase!,  chomp!,  sort!,  reverse!


change value to string( interpolation)

use  “#{  }”

ex:

a= 123

b= “#{a}”+ “4”

--->  b= “1234”

file methods

read  a file:

input_file =File.new (filename, ‘r’)


write a file:

output_file= File.new( filename, ‘w’)


‘w+’: 

read and write.  When creating the file, the old file is overwritten 


'a':

append


read:

return the content of the file in the string


readlines:

output_file.readlines()

return an array with each line of the file


puts:

output_file.puts(“hello”)

write “hello” to output_file


close:

output_file.close()

close the file


show the files and directories under directory:

ex:

Dir.open("Desktop").entries

---> [ "." , "..", "test.c", "book"]


directory?

ex:

File.directory?("test")


extname:

ex:

File.extname("test.exe")

--> ".exe"


environment variable

ENV[‘HOME’] (for unix-like)

ENV[‘HOMEDRIVE’]+ ENV[‘HOMEPATH’] (for windows)

return the path of home directory

ex:

on my mac , output is “/Users/Pan”




ARGV

the parameter to the ruby program

ex:

ruby test.rb  123

ARGV[0]  is 123


comment

start with #


=begin  & =end

use in multiple-line

if , else, elsif, unless

if and else:
ex:
if a==3
    puts “a==3”
else
    puts “a!=3”
end

elsif
use elsif,  not elseif

unless
if ! (x==1)  
equals
unless x==1

plugin install

install for ruby
remote install:
ex:
gem  install sqlite3-Ruby

local install:
ex:
1. get gem file from  http://rubyforge.org
2. gem install  scruffy-0.2.2.gem 
    ( in the directory with scruffy-0.2.2.gem)

install for rails project
remote install:
ex:
script/plugin  install  http://svn.techno-weenie.net/projects/plugins/acts_as_authenticated/

local install:
1. 用svn抓plugin下來
    ex:
    svn checkout http://svn.techno-weenie.net/projects/plugins/acts_as_authenticated/
2. 將plugin放到rails project下的vendor/plugins/



2008年5月2日 星期五

textmate & rails 2.0

install rails 2.0 bundle
1.  download rails 2.0 bundle  rails 2.0 bundle

2.  move rails 2.0 bundle to  Library/Application Support/TextMate/Bundles,
     rename the bundle as  Ruby on Rails.tmbundle

3.  reload bundle in textmate

4. mv Builder.rb Builder.rb.off   
    in  Applications/TextMate.app/Contents/SharedSupport/Support/lib

textmate shortcut

select word:
ctrl + w

show bundle list
ctrl + esc

select bundle item:
ctrl + command + t

show bundle editor:
ctrl + option+ command + b

ToDo bundle:
show ToDo list
ctrl + shift + t
Define TODO: ,  FIXME: ,  CHANGED:   in the comment of the file.
Then show ToDo list will find there lines in the files

html  bundle:
insert open & close tag with current word
ctrl + <
ex:
enter head, then with this short cut,  it becomes
ex:
enter this short cut, then enter abc, it becomes

wrap selection in open & close tag
ctrl + shift + w
ex:
enter hello, then enter this short cut,  then enter head, it becomes hello

tab completion :
1. head:   
    head+ meta + title
2. style:
3. script:
4. doctype:

insert a link(with the word in the clipboard)
ctrl + shift + L

webpage preview:
ctrl + option+ command + p

ruby  bundle:
run ruby program
command + r

# =>  mark
add # => mark
# + tab
execute the line with # => mark
ctrl + shift + command + e

find doc about the word
ctrl + h

tab completion :
1. cla :
    for class
2. def :
     for method
3.  r ,  w,  rw
     for attr_reader(),  attr_writer(),  attr_accessor()
4. while 
5.  if
6.  inj: 
     for inject
7. ea:
    for each
8. tim:
    for times
9. sorb:
    for sort_by
10. eawi:
      each_with_index

rubyOnRails bundel:
activate rubyOnRails bundle:
ctrl + option + shift + r + 3

params completion:
ctrl + p

session completion:
ctrl + j

call generate script:
ctrl + | + 1

tab completion:
for model: 
1. mccc 
    for model create column continue
2.  t.
     提示column type
3. mcol
    create column

visor : terminal access

1. install SIMBL

2. install visor
provides a systemwide terminal window accessible via a hotkey 
my hot key:  command + 1


date and time method

require 'date'
require 'time'

Time.now  or Time.new
-->  Fri May 02 16:50:08 +0800 2008

Time.now.strftime('%Y-%m-%d')
-->  "2008-05-02"

SECOND_IN_A_DAY

兩個時間相減得到的單位是秒 


Date.today:


%Y, %y:  year

%b, %B: month

%m : month(number)

%d, %e:  day of month

%a, %A: dat name( such as Tue)

%H, %I: hour

%M: minute

%S: second

%c:  equals "%a %b %d %H:%M:%S %Y"

%x:  equals "%m/%d/%y"

2008年5月1日 星期四

block and yield

yield: 
run what block defines
ex:
def  test(*args, &block)
        yield(*args)
end
test("hello"){ |i| puts i }
---> hello

note:
yield(*args)  = block.call(*args)

when defining a method that receives blocks,
there are two ways
(1)  define method with block arguments
ex:
def test( &block)
end

(2)define method without block arguments
ex:
def test
end

pass arguments to blocks
in the method definition, call yield with arguemtns
ex:
yield (a, b, c)

in the block, use | | to receive arguments 
ex:
| a, b, c|

return value from call block
the return value is last expression evaluated in block
ex:
in the method definition
a= yield

here doc

build up a long string


ex:

NAME= <<END_MY_STRING

      hello

      how are you

END_MY_STRING


puts NAME

--->   hello

         how are you