ruby on rails 代码技巧
git仓库输出
git archive --format=tar --prefix=actasfavor/ head | (cd /home/holin/work/ && tar xf -)
输出到/home/holin/work/actasfavor/目录下
posted by holin at may 16, 2008 16:42
加载plugins中的controller和model
# include hook code here
require 'act_as_favor'
# make plugin controller, model, helper available to app
config.load_paths += %w(#{actasfavor::plugin_controller_path} #{actasfavor::plugin_helper_path} #{actasfavor::plugin_models_path})
rails::initializer.run(:set_load_path, config)
# require the controller
require 'favors_controller'
# require models
require 'favor'
posted by holin at may 15, 2008 15:36
使用最频繁的前5个命令
history | awk {'print $2'} | sort | uniq -c | sort -k1 -rn| head -n5
posted by holin at may 15, 2008 10:40
按数组元素的某属性排序
@users.sort!{|a, b| a.last <=> b.last }
posted by holin at may 11, 2008 14:35
按日期备份数据库
mysqldump db_name -uroot > "/root/db_backup/kaoshi_web_`date +"%y-%m-%d"`.sql"
posted by holin at may 08, 2008 12:05
用memcached手动cache数据
sql = "select * from blogs limit 100"
blog.class
k = md5.new(sql)
@blogs = cache.get k
if @blogs.blank?
@blogs = blog.find_by_sql(sql)
cache.put k, @blogs, 60*30 #expire after 30min
end
memcache-client 1.5.0:
get(key, expiry = 0)
put(key, value, expiry = 0)
posted by devon at may 04, 2008 20:39
shuffle an array
class array
def shuffle
sort_by { rand }
end
def shuffle!
self.replace shuffle
end
end
posted by holin at may 04, 2008 15:39
让所有的ajax请求都不render :layout
def render(*args)
args.first[:layout] = false if request.xhr? and args.first[:layout].nil?
super
end
posted by devon at may 03, 2008 10:53
find with hash
event.find(
:all,
:conditions => [ "title like :search or description like :search",
{:search => "%tiki%"}]
)
posted by devon at may 03, 2008 10:49
执行sql语句脚本
mysql -uroot -p123<<end
use dbame;
delete from results;
delete from examings;
quit
end
posted by holin at may 01, 2008 12:14
sql transaction in rails
def fetch_value
sql = activerecord::base.connection();
sql.execute "set autocommit=0";
sql.begin_db_transaction
id, value =
sql.execute("select id, value from sometable where used=0 limit 1 for update").fetch_row;
sql.update "update sometable set used=1 where id=#{id}";
sql.commit_db_transaction
value;
end
posted by holin at april 30, 2008 09:37
显示 flash 消息的动态效果
<% if flash[:warning] or flash[:notice] %>
<div id="notice" <% if flash[:warning] %>class="warning"<% end %>>
<%= flash[:warning] || flash[:notice] %>
</div>
<script type="text/javascript">
settimeout("new effect.fade('notice');", 15000)
</script>
<% end %>
15000 毫秒后自动 notice div 自动消失。
posted by devon at april 29, 2008 13:02
删除环境中的常量
object.send(:remove_const, :a)
>> math
=> math
>> object.send(:remove_const, :math)
=> math
>> math
nameerror: uninitialized constant math
posted by devon at april 28, 2008 18:24
手动加上 authenticity_token
<div style="margin:0;padding:0"><input name="authenticity_token" type="hidden" value="<%= form_authenticity_token %>" /></div>
posted by devon at april 28, 2008 14:24
rails group_by
<% @articles.group_by(&:day).each do |day, articles| %>
<div id='day' style="padding: 10px 0;">
<h2><%= day.to_date.strftime('%y年%m月%d日') %></h2>
<%= render :partial => 'article', :collection => articles %>
</div>
<% end %>
articles 按天数分组
posted by devon at april 25, 2008 22:32
读写文件
# open and read from a text file
# note that since a block is given, file will
# automatically be closed when the block terminates
file.open('p014constructs.rb', 'r') do |f1|
while line = f1.gets
puts line
end
end
# create a new file and write to it
file.open('test.rb', 'w') do |f2|
# use "\n" for two lines of text
f2.puts "created by satish\nthank god!"
end
posted by holin at april 17, 2008 02:10
遍历目录
dir.glob(file.join('app/controllers', "**", "*_controller.rb")) { |filename| puts filename }
posted by holin at april 16, 2008 15:28
字符串到 model
1
2
>> 'tag_course'.camelize.constantize.find(:first)
=> #<tagcourse id: 7, tag_id: 83, course_id: 2>
*camelize(lower_case_and_underscored_word, first_letter_in_uppercase = true)*
by default, camelize converts strings to uppercamelcase. if the argument to camelize is set to ":lower" then camelize produces lowercamelcase.
*constantize(camel_cased_word)*
constantize tries to find a declared constant with the name specified in the string. it raises a nameerror when the name is not in camelcase or is not initialized.
posted by devon at april 07, 2008 17:32
调用proc
1
2
3
a = proc.new { |i| puts i }
a['haha']
a.call('hehe')
posted by holin at march 28, 2008 23:10
rails中host静态文件
1
2
config.action_controller.asset_host = "http://assets.example.com"
config.action_controller.asset_host = "http://assets-%d.example.com"
the rails image_path and similar helper methods will then use that host to reference files in the public directory.
the second line will distribute asset requests across assets-0.example.com,assets-1.example.com, assets-2.example.com, and assets-3.example.com.
posted by devon at march 26, 2008 18:18
打包gems到项目目录中
$ mkdir vendor/gems
$ cd vendor/gems
$ gem unpack hpricot
unpacked gem: 'hpricot-0.4'
config.load_paths += dir["#{rails_root}/vendor/gems/**"].map do |dir|
file.directory?(lib = "#{dir}/lib") ? lib : dir
end
posted by devon at march 26, 2008 18:12
在当前上下文中执行文件中的代码
instance_eval(file.read('param.txt'))
# such as
@father = 'father'
instance_eval("puts @father")
#produces:
#father
posted by holin at march 20, 2008 01:13
将当前文件所在目录加入require路径
$load_path << file.expand_path(file.dirname(__file__))
# or
$: << file.expand_path(file.dirname(__file__))
# this one puts current path before the other path.
$:.unshift( file.expand_path(file.dirname(__file__)) )
*__ file __* 当前文件路径
posted by holin at march 19, 2008 01:40
多字段模糊搜索
conditions = []
[:name, :school, :province, :city].each { |attr| conditions << profile.send(:sanitize_sql, ["#{attr} like ?", "%#{params[:q]}%"]) if params[:q] }
conditions = conditions.any? ? conditions.collect { |c| "(#{c})" }.join(' or ') : nil
在profile表里,按name, school, province, city模糊搜索
posted by devon at march 17, 2008 17:25
nginx 启动脚本
#! /bin/sh
# chkconfig: - 58 74
# description: nginx is the nginx daemon.
# description: startup script for nginx webserver on debian. place in /etc/init.d and
# run 'sudo update-rc.d nginx defaults', or use the appropriate command on your
# distro.
#
# author: ryan norbauer
# modified: geoffrey grosenbach http://topfunky.com
# modified: david krmpotic http://davidhq.com
set -e
path=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
desc="nginx daemon"
name=nginx
daemon=/usr/local/nginx/sbin/$name
configfile=/usr/local/nginx/conf/nginx.conf
daemon=/usr/local/nginx/sbin/$name
configfile=/usr/local/nginx/conf/nginx.conf
pidfile=/usr/local/nginx/logs/$name.pid
scriptname=/etc/init.d/$name
# gracefully exit if the package has been removed.
test -x $daemon || exit 0
d_start() {
$daemon -c $configfile || echo -en "\n already running"
}
d_stop() {
kill -quit `cat $pidfile` || echo -en "\n not running"
}
d_reload() {
kill -hup `cat $pidfile` || echo -en "\n can't reload"
}
case "$1" in
start)
echo -n "starting $desc: $name"
d_start
echo "."
stop)
echo -n "stopping $desc: $name"
d_stop
echo "."
reload)
echo -n "reloading $desc configuration..."
d_reload
echo "."
restart)
echo -n "restarting $desc: $name"
d_stop
# one second might not be time enough for a daemon to stop,
# if this happens, d_start will fail (and dpkg will break if
# the package is being upgraded). change the timeout if needed
# be, or change d_stop to have start-stop-daemon use --retry.
# notice that using --retry slows down the shutdown process
# somewhat.
sleep 1
d_start
echo "."
*)
echo "usage: $scriptname {start|stop|restart|reload}" >&2
exit 3
esac
exit 0
将文件写入到 /etc/init.d/nginx
sudo chmod +x /etc/init.d/nginx
测试是否可正确运行
sudo /etc/init.d/nginx start
设置自动启动
sudo /sbin/chkconfig --level 345 nginx on
posted by devon at march 16, 2008 12:26
link_to_remote 取静态页面
1
2
<%= link_to_remote "update post", :update => 'post', :method => 'get', :url => '/post_1.html' %>
<div id='post'></div>
将 url 改为静态面页的地址即可。
posted by devon at march 16, 2008 11:07
in_place_editor for rails2.0
module inplacemacroshelper
# makes an html element specified by the dom id +field_id+ become an in-place
# editor of a property.
#
# a form is automatically created and displayed when the user clicks the element,
# something like this:
# <form id="myelement-in-place-edit-form" target="specified url">
# <input name="value" text="the content of myelement"/>
# <input type="submit" value="ok"/>
# <a onclick="javascript to cancel the editing">cancel</a>
# </form>
#
# the form is serialized and sent to the server using an ajax call, the action on
# the server should process the value and return the updated value in the body of
# the reponse. the element will automatically be updated with the changed value
# (as returned from the server).
#
# required +options+ are:
# <tt>:url</tt>:: specifies the url where the updated value should
# be sent after the user presses "ok".
#
# addtional +options+ are:
# <tt>:rows</tt>:: number of rows (more than 1 will use a textarea)
# <tt>:cols</tt>:: number of characters the text input should span (works for both input and textarea)
# <tt>:size</tt>:: synonym for :cols when using a single line text input.
# <tt>:cancel_text</tt>:: the text on the cancel link. (default: "cancel")
# <tt>:save_text</tt>:: the text on the save link. (default: "ok")
# <tt>:loading_text</tt>:: the text to display while the data is being loaded from the server (default: "loading...")
# <tt>:saving_text</tt>:: the text to display when submitting to the server (default: "saving...")
# <tt>:external_control</tt>:: the id of an external control used to enter edit mode.
# <tt>:load_text_url</tt>:: url where initial value of editor (content) is retrieved.
# <tt>:options</tt>:: pass through options to the ajax call (see prototype's ajax.updater)
# <tt>:with</tt>:: javascript snippet that should return what is to be sent
# in the ajax call, +form+ is an implicit parameter
# <tt>:script</tt>:: instructs the in-place editor to evaluate the remote javascript response (default: false)
# <tt>:click_to_edit_text</tt>::the text shown during mouseover the editable text (default: "click to edit")
def in_place_editor(field_id, options = {})
function = "new ajax.inplaceeditor("
function << "'#{field_id}', "
function << "'#{url_for(options[:url])}'"
js_options = {}
if protect_against_forgery?
options[:with] ||= "form.serialize(form)"
options[:with] += " + '&authenticity_token=' + encodeuricomponent('#{form_authenticity_token}')"
end
js_options['canceltext'] = %('#{options[:cancel_text]}') if options[:cancel_text]
js_options['oktext'] = %('#{options[:save_text]}') if options[:save_text]
js_options['loadingtext'] = %('#{options[:loading_text]}') if options[:loading_text]
js_options['savingtext'] = %('#{options[:saving_text]}') if options[:saving_text]
js_options['rows'] = options[:rows] if options[:rows]
js_options['cols'] = options[:cols] if options[:cols]
js_options['size'] = options[:size] if options[:size]
js_options['externalcontrol'] = "'#{options[:external_control]}'" if options[:external_control]
js_options['loadtexturl'] = "'#{url_for(options[:load_text_url])}'" if options[:load_text_url]
js_options['ajaxoptions'] = options[:options] if options[:options]
# js_options['evalscripts'] = options[:script] if options[:script]
js_options['htmlresponse'] = !options[:script] if options[:script]
js_options['callback'] = "function(form) { return #{options[:with]} }" if options[:with]
js_options['clicktoedittext'] = %('#{options[:click_to_edit_text]}') if options[:click_to_edit_text]
js_options['textbetweencontrols'] = %('#{options[:text_between_controls]}') if options[:text_between_controls]
function << (', ' + options_for_javascript(js_options)) unless js_options.empty?
function << ')'
javascript_tag(function)
end
# renders the value of the specified object and method with in-place editing capabilities.
def in_place_editor_field(object, method, tag_options = {}, in_place_editor_options = {})
tag = ::actionview::helpers::instancetag.new(object, method, self)
tag_options = {:tag => "span", :id => "#{object}_#{method}_#{tag.object.id}_in_place_editor", :class => "in_place_editor_field"}.merge!(tag_options)
in_place_editor_options[:url] = in_place_editor_options[:url] || url_for({ :action => "set_#{object}_#{method}", :id => tag.object.id })
tag.to_content_tag(tag_options.delete(:tag), tag_options) +
in_place_editor(tag_options[:id], in_place_editor_options)
end
end
解决在rails2.0以上版本使用in_place_editor时出现的 actioncontroller::invalidauthenticitytoken 错误。
posted by devon at march 15, 2008 16:20
capture in view
<% @greeting = capture do %>
welcome to my shiny new web page! the date and time is
<%= time.now %>
<% end %>
<html>
<head><title><%= @greeting %></title></head>
<body>
<b><%= @greeting %></b>
</body></html>
the capture method allows you to extract part of a template into a variable. you can then use this variable anywhere in your templates or layout.
posted by devon at march 13, 2008 14:06
在 before_filter 中使用不同的layout
before_filter proc.new {|controller| layout 'iframe' unless controller.request.env["http_referer"] =~ /localhost/ }
如果不是从localhost这个站点来访问的,则使用 iframe 的 layout
posted by devon at march 11, 2008 17:38
rails中获取 http_referer
request.env["http_referer"]
可以取到的参数包括:
server_name: localhost
path_info: /forum/forums
http_user_agent: mozilla/5.0 (macintosh; u; intel mac os x; en) applewebkit/522.11 (khtml, like gecko) version/3.0.2 safari/522.12
http_accept_encoding: gzip, deflate
script_name: /
server_protocol: http/1.1
http_host: localhost:3000
http_cache_control: max-age=0
http_accept_language: en
remote_addr: 127.0.0.1
server_software: mongrel 1.1.3
request_path: /forum/forums
http_referer: http://localhost:3000/
http_cookie: _matchsession=bah7bzomy3nyzl9pzcilnwjinzg4nduzowqznwfhztq4mgrkntuwyzc0mdc5%250azgyicmzsyxnosum6j0fjdglvbknvbnryb2xszxi6okzsyxnoojpgbgfzaehh%250ac2h7aay6ckb1c2vkewa%253d268e6091590591d959128f3b17b62ff46244a0a3; _slemail=temp%40email.com; _slhash=9dfd86431742273e3e96e06a1c20541d69f74dc9; _haha_session=bah7biikzmxhc2hjqzonqwn0aw9uq29udhjvbgxlcjo6rmxhc2g6okzsyxno%250asgfzahsabjokqhvzzwr7aa%253d%253d--96565e41694dc839bd244af40b5d5121a923c8e3
http_version: http/1.1
request_uri: /forum/forums
server_port: "3000"
gateway_interface: cgi/1.2
http_accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
http_connection: keep-alive
request_method: get
上一篇: 如何解决iphone通话听不清?