首页 > 学院 > 开发设计 > 正文

ruby on rails 代码技巧

2019-10-26 19:22:26
字体:
来源:转载
供稿:网友

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)

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表