• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell
您的位置:首页 > 脚本语言 >ruby > ruby on rails 代码技巧

ruby on rails 代码技巧

作者: 字体:[增加 减小] 来源:互联网

通过本文主要向大家介绍了ruby on rails,ruby on rails教程,ruby on rails安装,ruby on rails下载,ruby on rails指南等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com

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/

您可能想查找下面的文章:

  • Rails bundle命令安装mysql gem包出错的解决方法
  • win7安装ruby on rails开发环境
  • 简单对比分析Ruby on Rails 和 Laravel
  • 在 Ubuntu 12.04 Server 上安装部署 Ruby on Rails 应用
  • 快速正确的安装 Ruby, Rails 运行环境
  • Windows下Ruby on Rails开发环境安装配置图文教程
  • Ruby On Rails中如何避免N+1问题
  • 艰难完成 nginx + puma 部署 rails 4的详细记录
  • 浅谈Rails 4 中Strong Parameters机制
  • Rails命令行常用操作命令简明总结

相关文章

  • windows下安装ruby与rails时遇到的问题总结
  • Ruby中嵌套对象转换成json的方法
  • Ruby on Rails迁移时的一些注意事项
  • Ruby元编程的一些值得注意的地方
  • ruby 异常处理:rescue
  • Ruby优化继承类实例
  • 详解Ruby语言中的注释用法与中文编码问题
  • rudy 继承 概念
  • ruby写扫描当前网页所有url的脚本
  • 比较详细的ruby symbol 学习资料

文章分类

  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell

最近更新的内容

    • Ruby实现的各种排序算法
    • 实例讲解Ruby中的钩子方法及对方法调用添加钩子
    • RUBY 新手教程 跟我一起学ruby
    • ruby元编程之创建自己的动态方法
    • 详解Ruby中的循环语句的用法
    • ruby写扫描当前网页所有url的脚本
    • 在操作系统上安装Ruby解释器的教程
    • 21个你应该知道的Ruby编程技巧
    • Ruby里4种比较函数(equal?, eql?, ==, ===)详解
    • ruby 正则表达式 教程

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有