rubyonrails: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(:_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 {'pr $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.
k = MD5.(sql)
@blogs = Cache.get k
@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 .gif' />
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 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 消息动态效果
<% flash[:warning] or flash[:notice] %>
<div id="notice" <% flash[:warning] %>="warning"<% end %>>
<%= flash[:warning] || flash[:notice] %>
</div>
<script type="text/javascript">
Timeout(" 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 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__and_underscored_word, first_letter_in_upper = true)*
By default, camelize converts s to UpperCamelCase. If the argument to camelize is to ":lower" then camelize produces lowerCamelCase.
*constantize(camel_d_word)*
Constantize tries to find a declared constant with the name specied in the . 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. { |i| puts i }
a['haha']
a.call('hehe')
Posted by holin At March 28, 2008 23:10
Rails中Host静态文件
1
2
config.action_controller.as_host = "http://ass.example.com"
config.action_controller.as_host = "http://ass-%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 as requests across ass-0.example.com,ass-1.example.com, ass-2.example.com, and ass-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 _disibledevent=>[:name, :school, :province, :city].each { |attr| conditions << Profile.send(:sanitize_sql, ["#{attr} LIKE ?", "%#{params[:q]}%"]) 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 _disibledevent=>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 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"
}
"$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
# _disibledevent=><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 specied 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="specied url">
# <input name="value" text="The content of myElement"/>
# <input type="submit" value="ok"/>
# <a _disibledevent=># </form>
#
# The form is serialized and sent to the server using an AJAX call, the action _disibledevent=>function = " Ajax.InPlaceEditor("
function << "'#{field_id}', "
function << "'#{url_for(options[:url])}'"
js_options = {}
protect_against_forgery?
options[:with] ||= "Form.serialize(form)"
options[:with] " + '&authenticity_token=' + encodeURIComponent('#{form_authenticity_token}')"
end
js_options['cancelText'] = %('#{options[:cancel_text]}') options[:cancel_text]
js_options['okText'] = %('#{options[:save_text]}') options[:save_text]
js_options['loadingText'] = %('#{options[:loading_text]}') options[:loading_text]
js_options['savingText'] = %('#{options[:saving_text]}') options[:saving_text]
js_options['rows'] = options[:rows] options[:rows]
js_options['cols'] = options[:cols] options[:cols]
js_options['size'] = options[:size] options[:size]
js_options['externalControl'] = "'#{options[:external_control]}'" options[:external_control]
js_options['loadTextURL'] = "'#{url_for(options[:load_text_url])}'" options[:load_text_url]
js_options['ajaxOptions'] = options[:options] options[:options]
# js_options['evalScripts'] = options[:script] options[:script]
js_options['htmlResponse'] = !options[:script] options[:script]
js_options['callback'] = "function(form) { #{options[:with]} }" options[:with]
js_options['clickToEditText'] = %('#{options[:click_to_edit_text]}') options[:click_to_edit_text]
js_options['textBetweenControls'] = %('#{options[:text_between_controls]}') options[:text_between_controls]
function << (', ' + options_for_javascript(js_options)) unless js_options.empty?
function << ')'
javascript_tag(function)
end
# Renders the value of the specied 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.(object, method, self)
tag_options = {:tag => "span", :id => "#{object}_#{method}_#{tag.object.id}_in_place_editor", : => "in_place_editor_field"}.merge!(tag_options)
in_place_editor_options[:url] = in_place_editor_options[:url] || url_for({ :action => "_#{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 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 o 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. {|controller| layout 'rame' unless controller.request.env["HTTP_REFERER"] =~ /localhost/ }
如果不是从localhost这个站点来访问则使用 rame 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 (Macosh; 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


Tags:  rubyonrails实例 rubyonrails教程 rubyonrails安装 rubyonrails

延伸阅读

最新评论

发表评论