2010年12月13日 星期一

fb comment

http://developers.facebook.com/docs/reference/plugins/comments

Unique ID 填了反而不行用 是怎樣 = =

2010年6月30日 星期三

rails 設定多個 smtp account 寄信

Using multiple SMTP accounts with Rails & ActionMailer

可利用此技巧, 達到多SMTP 寄信的目的

2010年6月24日 星期四

haproxy nginx passenger munin

step1: nginx need stub_status_module
compile with [--with-http_stub_status_module]

step2: install munin
sudo apt-get install munin munin-node

 
#/etc/munin/munin.conf
#This will tell munin to connect to munin-node at 127.0.0.1 on the same machine.
[foo.net]
address 127.0.0.1
use_node_name yes


#Edit the file /etc/munin/munin-node.conf and change # Which port to bind to set
host 127.0.0.1

#Make sure that this is present in the file

allow ^127\.0\.0\.1$



http://github.com/barttenbrinke/munin-plugins-rails
http://www.alfajango.com/blog/how-to-monitor-your-railspassenger-app-with-munin/
http://github.com/jnstq/munin-nginx-ubuntu

 
#haproxy setting
reqisetbe ^Host:\ munin.foo.net foomunin

#nginx config
server {
listen 6166;
server_name munin.foo.net;
root /home/foo/deploy/shared/directory/munin;
}


#/etc/munin/plugin-conf.d/munin-node
[foo_*]
env.log_file '/home/foo/app/production.log'
user foo
command /opt/ruby-enterprise-1.8.7-2010.02/bin/ruby %c
env.graph_category Foo



2010年6月22日 星期二

rails ip 辨識國家

how-to-know-user-location-with-rails
github geoip
Super fast IP to lat/lng in Rails

下載點 http://geolite.maxmind.com/download/geoip/database/

haproxy rails ip

haproxy不能正確記錄客戶端的IP
關於 rails 的扔remote_ip
http://kkito.cn/index.php/blog/getArticle/102/rails%E4%B8%AD%E5%BA%94%E6%B3%A8%E6%84%8F%E5%8F%AF%E8%83%BD%E5%AE%A2%E6%88%B7%E7%AB%AFip%E5%9C%B0%E5%9D%80%E6%98%AF%E4%BC%AA%E8%A3%85%E7%9A%84

2010年6月21日 星期一

capistrano path rake fail

http://blog.zerobearing.com/2009/04/27/capistrano-rake-command-not-found/
http://stackoverflow.com/questions/588934/using-ruby-enterprise-edition-gems-are-not-installed-where-i-would-expect
http://forum.slicehost.com/comments.php?DiscussionID=3657
http://stackoverflow.com/questions/257616/sudo-changes-path-why
http://groups.google.com/group/emm-ruby/browse_thread/thread/d0c685bbd096823a#msg_effa7d6ad42c541c
http://www.f15ijp.com/2009/11/30/sudo-no-tty-present-and-no-askpass-program-specified/

/etc/ssh/sshd_config:

PermitUserEnvironment yes
/etc/init.d/sshd restart


~/.ssh/environment
PATH=/opt/ruby-enterprise-1.8.7-2010.02/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games


http://formatinternet.wordpress.com/2009/07/06/sudo-rake-command-not-found/
~/.bashrc
alias sudo='sudo env PATH=$PATH'


sudo ln -s `which rake` /usr/local/bin/

#sudo: no tty present and no askpass program specified error
the /etc/sudoers file.
#commend sudo visudo
Defaults visiblepw

2010年6月13日 星期日

delayed_job capistrano production fail

主要參考
http://railscasts.com/episodes/171-delayed-job
http://www.magnionlabs.com/2009/2/28/background-job-processing-in-rails-with-delayed_job

不知道哪邊弄錯了用capistrano deploy 想啟動delayed_job 卻好像都沒反應
後來終於看到 有script/delayed_job run的指令 這個動作才可以讓你看到你錯在哪, start 只會無聲無息

2010年6月3日 星期四

nginx passenger config

nginx, worker_processes, and passenger_max_pool_size
Production Rails Tuning with Passenger: PassengerMaxProcesses

 
worker_processes 4; <= Setting the number of Nginx workers to the number of CPU cores should be sufficient.

http {
passenger_max_pool_size 20; # memory 256M should be 2, 2G should be 30, max_pool 不要設太大, 不要讓它吃到swap, free -ml ; vmstat 2 都可以看到現在memory 的情況
passenger_max_instances_per_app 15; #每種ap 能用到最多的instance, 所以如果跑兩個app 就會再少一點

# PassengerPoolIdleTime
# Recommended to be avg time per page * 2
# In Google Analytics... (Avg time on site / Avg page views) * 2
# Default: 300
passenger_pool_idle_time 144

}


超小型web server 設定
How to save MUCH RAM when running rails (linode/slicehost) and mod_rails passenger

2010年5月7日 星期五

改變預設的cache 目錄

http://railsforum.com/viewtopic.php?id=11033

2010年4月20日 星期二

[Ptt][心得] Restful下遇到params[:id]含有.的解法

在restful的前提下, 遇到class的to_param是字串, 而剛好某筆
紀錄的to_param欄位含有.

一般情形下會發生錯誤, 因為restful會把.後的東西當成format
這時的解法, 變成要在routes.rb中的xxx.resources加上參數

ex:

paramter change permanently, header status

2010年4月16日 星期五

Practical Rails Social Networking Site memo (2)

2010年4月15日 星期四

Practical Rails Social Networking Site memo

2010年4月6日 星期二

check timezone valid

2010年3月21日 星期日

migration

2010年3月10日 星期三

rjs page

page['foo']['style']
# => $('foo').style;
page['foo']['style']['color']
# => $('blank_slate').style.color;
page['foo']['style']['color'] = 'red'
# => $('blank_slate').style.color = 'red';
page['foo']['style'].color = 'red'
# => $('blank_slate').style.color = 'red';

respond_to jsonp

respond_to recognizes • JSON.
render :json => @person.to_json automatically sets the content type and takes a :callback option to specify a client-side function to call using the rendered JSON as an argument. #4185 [Scott Raymond, eventualbuddha]

Bootstrap Initializer

Bootstrap Initializer
The files in config/initializers are loaded after Rails' environment is loaded (including environment.rb). However, there's a pre-environment
hook provided for you should you need to do things prior to Rails' environment getting in the mix: just create a config/preinitializer.rb file.

This file is loaded after the Rails classes are loaded but before the environment file and the environment configuration.

2010年3月9日 星期二

rescue_from Exception Handlers

rescue_from Exception Handlers

2010年3月5日 星期五

Top 8 SQL Best Practices

Top 8 SQL Best Practices

1) Always use explicit joins. If I mean INNER JOIN, then I use INNER JOIN. No use of just plain "JOIN". Never, ever, ever use a comma join -- I consider that a mistake. If I explicitly state "CROSS JOIN" then I know I have consciously made that decision. Also, keep join conditions in an ON or USING clause; they should not go in the WHERE clause. I also put my join conditions in parentheses; for whatever reason, I find:
ON (foo=bar AND baz=bop) WHERE a=b
is easier to see that the join condition contains 2 conditions than
ON foo=bar AND baz=bop WHERE a=b

SQL Server TSQL Coding Conventions, Best Practices, and Programming Guidelines

SQL Server TSQL Coding Conventions, Best Practices, and Programming Guidelines

Try to avoid wildcard characters at the beginning of a word while searching using the LIKE keyword, as that results in an index scan, which defeats the purpose of an index. The following statement results in an index scan, while the second statement results in an index seek:

SELECT LocationID FROM Locations WHERE Specialities LIKE '%pples'
SELECT LocationID FROM Locations WHERE Specialities LIKE 'A%s'

Also avoid searching using not equals operators (<> and NOT) as they result in table and index scans.






Use 'Derived tables' wherever possible, as they perform better. Consider the following query to find the second highest salary from the Employees table:

SELECT MIN(Salary)
FROM Employees
WHERE EmpID IN
(
SELECT TOP 2 EmpID
FROM Employees
ORDER BY Salary Desc
)

The same query can be re-written using a derived table, as shown below, and it performs twice as fast as the above query:

SELECT MIN(Salary)
FROM
(
SELECT TOP 2 Salary
FROM Employees
ORDER BY Salary DESC
) AS A

This is just an example, and your results might differ in different scenarios depending on the database design, indexes, volume of data, etc. So, test all the possible ways a query could be written and go with the most efficient one.





While designing your database, design it keeping "performance" in mind. You can't really tune performance later, when your database is in production, as it involves rebuilding tables andindexes, re-writing queries, etc. Use the graphical execution plan in Query Analyzer or SHOWPLAN_TEXT or SHOWPLAN_ALL commands to analyze your queries. Make sure your queries do an "Index seek" instead of an "Index scan" or a "Table scan." A table scan or an index scan is a very bad thing and should be avoided where possible. Choose the right indexes on the right columns.





Use the more readable ANSI-Standard Join clauses instead of the old style joins. With ANSI joins, the WHERE clause is used only for filtering data. Where as with older style joins, the WHERE clause handles both the join condition and filtering data. The first of the following two queries shows the old style join, while the second one shows the new ANSI join syntax:

SELECT a.au_id, t.title
FROM titles t, authors a, titleauthor ta
WHERE
a.au_id = ta.au_id AND
ta.title_id = t.title_id AND
t.title LIKE '%Computer%'

SELECT a.au_id, t.title
FROM authors a
INNER JOIN
titleauthor ta
ON
a.au_id = ta.au_id
INNER JOIN
titles t
ON
ta.title_id = t.title_id
WHERE t.title LIKE '%Computer%'

rails performance memo

2010年3月3日 星期三

That’s Not a Memory Leak, It’s Bloat; refactor

That’s Not a Memory Leak, It’s Bloat

respond_to

Restful memo

2010年3月2日 星期二

Rails Best Practices

Rails Best Practices

2010年3月1日 星期一

Advanced Active Record Techniques: Best Practice Refactoring

Advanced Active Record Techniques: Best Practice Refactoring

Rails Code Review PDF

http://peepcode.com/products/rails-code-review-pdf

2010年2月26日 星期五

Enable or fix logging for HAProxy load balancer

Enable or fix logging for HAProxy load balancer

On a RedHat/CentOS server, edit the value of SYSLOGD_OPTIONS in /etc/sysconfig/syslog:

SYSLOGD_OPTIONS=”-m 0 -r”


On a Debian/Ubuntu server, edit the value of SYSLOGD in /etc/default/syslogd:

SYSLOGD=”-r”


/etc/syslog.conf:

local0.* /var/log/haproxy.log


restart syslog service to apply changes:

service syslog restart

2010年2月22日 星期一

request host, query paramters, header

登入登出轉址設計

2010年2月21日 星期日

multi-step

RoR Multi-step forms

2010年2月8日 星期一

render outside your controller

Rails: Calling render() outside your Controllers
Calling Rails Render Partial in a Model or Background Task


2010年2月7日 星期日

Turning web server configuration

Setting Static Asset Expires Headers with nginx and Passenger

Nginx
location ~* \.(ico|css|js|gif|jpe?g|png)(\?[0-9]+)?$ {
expires max;
break;
}

2010年2月4日 星期四

redirect permanent

Permanent Redirect with HTTP 301

#Apache
RewriteCond %{HTTP_HOST} 17\.ooxx\.com [NC]
RewriteRule ^/(.*) http://17.ooxx.com.tw/$1 [L,R=permanent]

#Nginx
if ($host ~* ^17.ooxx\.com) {
rewrite ^/(.*) http://17.ooxx.com.tw/$1 permanent;
}

2010年2月3日 星期三

META HTTP-EQUIV="refresh" 實現網頁自動跳轉

META HTTP-EQUIV="refresh" 實現網頁自動跳轉

2010年2月2日 星期二

rails default environment

~/.bashrc

export PATH=$PATH:/opt/ruby-enterprise/bin
export RAILS_ENV=production

nginx memo

Nginx泛域名解析及Rewrite重定向普通頁面及帶參數的頁面
Nginx "how to" - Fast and Secure Web Server
Nginx Location



靜態地址重定向到帶參數的動態地址
rewrite "^(.*)/service/(.*)\.html$" $1/service.php?sid=$2 permanent;


帶參數的動態地址重定向到靜態地址
if ($query_string ~* id=(.*)) {
set $id $1;
rewrite "^(.*)/article.asp$" $1/article/$id.htm last;
}


舉例:
abc.domian.com/sort/2 => abc.domian.com/index.php?act=sort&name=abc&id=2

if ($host ~* (.*)\.domain\.com) {
set $sub_name $1;
rewrite ^/sort\/(\d+)\/?$ /index.php?act=sort&cid=$sub_name&id=$1 last;
}


Nginx Rewrite Flags
* last 相當於Apache裡的[L]標記,表示完成rewrite
* break 終止匹配, 不再匹配後面的規則
* redirect 返回302臨時重定向
* permanent 返回301永久重定向

Nginx正則表達式匹配
* ~ 為區分大小寫匹配
* ~* 為不區分大小寫匹配
* !~和!~*分別為區分大小寫不匹配及不區分大小寫不匹配

Nginx文件及目錄匹配
* -f和!-f用來判斷是否存在文件
* -d和!-d用來判斷是否存在目錄
* -e和!-e用來判斷是否存在文件或目錄
* -x和!-x用來判斷文件是否可執行

Nginx全局變量
$args
$content_length
$content_type
$document_root
$document_uri
$host
$http_user_agent
$http_cookie
$limit_rate
$request_body_file
$request_method
$remote_addr
$remote_port
$remote_user
$request_filename
$request_uri
$query_string
$scheme
$server_protocol
$server_addr
$server_name
$server_port
$uri

2010年2月1日 星期一

restart nginx

 
alias startnginx='sudo /opt/nginx/sbin/nginx'
alias stopnginx='sudo kill `cat /opt/nginx/logs/nginx.pid `'
alias restartnginx='stopnginx; startnginx'

transcation

Transaction in Rails
Working with transactions in Rails

2010年1月29日 星期五

ssl apache nginx configuration

http://articles.slicehost.com/2010/1/11/managing-ssl-certificates-1
http://articles.slicehost.com/2010/1/11/managing-ssl-certificates-2
Nginx SSL 實務
SSL Certificate Installation in Nginx
Configuring HTTPS servers

ssl 設定的file 有三種 伺服器憑證, 中繼憑證, RSA key
各種web server 吃的方式不同

Nginx 設定


listen ip.address:443; #監聽HTTPS, 通常是Port 443
ssl on;
ssl_certificate /path/to/server.crt;
ssl_certificate_key /path/to/private.key; #這是伺服器用的RSA Key


#server.crt要用發下來的伺服器憑證與中繼憑證合併產生:
cat domain_name.crt ca_bundle.crt > server.cr


SSLCertificateFile /etc/ssl/apache_ca.crt #這是伺服器憑證
SSLCertificateKeyFile /etc/ssl/www.goyou.com.tw.key
SSLCertificateChainFile /etc/ssl/chain.crt #中繼憑證

2010年1月28日 星期四

nginx , page cache, capistrano

Segregated page cache storage
Rails page caching vs nginx Restful route 可能會造成有相同的html, like index and create, 所以利用nginx 做一些檢查來避免
nginx rewrite rules with Passenger

if (-f $request_filename) {
break;
}

# cached pages
#set $cache_extension '';
#if ($request_method = GET) {
# set $cache_extension '.html';
#}

# the above is a hack because nginx doesn't allow nested or ANDed ifs
#if (-f $request_filename$cache_extension) {
# rewrite (.*) $1.html break;
#}

# 這個才有用 上面那些都沒用 orz, 用$uri 才有用
if (-f $document_root/cache/$uri/index.html) {
rewrite (.*) /cache/$1/index.html break;
}

if (-f $document_root/cache/$uri.html) {
rewrite (.*) /cache/$1.html break;
}


# everything else goes to the mongrel cluster
if (!-f $request_filename) {
proxy_pass http://mongrels;
break;
}



#In config/environments/production.rb, tell Rails to put cached pages in the public/cache directory.

config.action_controller.page_cache_directory = File.join(RAILS_ROOT, 'public', 'cache')

#In nginx.conf, set up the precedence for locating static files. First look in public for regular static files. Next look in the cache directory for an exact match for the url. Lastly, look in the cache directory for the url with .html appended. That will let you cache pages for regular URLs with no .html extension as well as ones with extensions like .xml, .atom, .json, etc.

if (-f $request_filename) {
break;
}

# if (-f /cache$request_filename) {
# rewrite (.*) /cache$1 break;
# break;
# }

# if (-f /cache$request_filename.html) {
# rewrite (.*) /cache$1.html break;
# break;
# }

#The capistrano recipes have to do a couple things. You need to create the shared/cache directory when setting up the deployment.

after "deploy:setup", "create_page_cache"
task :create_page_cache, :roles => :app do
run "umask 02 && mkdir -p #{shared_path}/cache"
end


after "deploy:update_code","symlink_shared_dirs"
task :symlink_shared_dirs, :roles => :app, :except => {:no_release => true, :no_symlink => true} do
run <<-CMD
cd #{release_path} &&
ln -nfs #{shared_path}/cache #{release_path}/public/cache
CMD
end

#When doing a deploy, the standard behavior is to flush the cache, just to be on the safe side. If you want to retain cached pages, as when making a change you know won't affect rendering, tell capistrano not to flush.

# default behavior is to flush page cache on deploy
set :flush_cache, true

# page cache management
task :keep_page_cache do
set :flush_cache, false
end

after "deploy:cleanup", "flush_page_cache"
task :flush_page_cache, :roles => :app do
if flush_cache
run <<-CMD
rm -rf #{shared_path}/cache/*
CMD
end
end

#With the above setup, you can deploy and retain the cache with the following capistrano command:
$ cap keep_page_cache deploy

2010年1月8日 星期五

Moneta, memcache

Moneta: 提供 key/value stores 的統一介面
moneta github
handcache github

2010年1月5日 星期二

heroku 上 你要 它卻沒有的gem

Automatically generate Heroku .gems file

用個rake 幫你生這個file