亚洲香蕉成人av网站在线观看_欧美精品成人91久久久久久久_久久久久久久久久久亚洲_热久久视久久精品18亚洲精品_国产精自产拍久久久久久_亚洲色图国产精品_91精品国产网站_中文字幕欧美日韩精品_国产精品久久久久久亚洲调教_国产精品久久一区_性夜试看影院91社区_97在线观看视频国产_68精品久久久久久欧美_欧美精品在线观看_国产精品一区二区久久精品_欧美老女人bb

首頁 > 編程 > Ruby > 正文

ruby on rails 代碼技巧

2020-03-29 12:11:22
字體:
來源:轉載
供稿:網友

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


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
亚洲香蕉成人av网站在线观看_欧美精品成人91久久久久久久_久久久久久久久久久亚洲_热久久视久久精品18亚洲精品_国产精自产拍久久久久久_亚洲色图国产精品_91精品国产网站_中文字幕欧美日韩精品_国产精品久久久久久亚洲调教_国产精品久久一区_性夜试看影院91社区_97在线观看视频国产_68精品久久久久久欧美_欧美精品在线观看_国产精品一区二区久久精品_欧美老女人bb
亚洲欧美制服中文字幕| 欧美成人sm免费视频| 在线观看不卡av| 精品国内产的精品视频在线观看| 亚洲欧美在线一区二区| 亚洲欧洲国产一区| 欧美精品久久一区二区| 亚洲精品成人av| 亚洲欧洲自拍偷拍| 亚洲伊人久久大香线蕉av| 日韩中文字幕网| 亚洲第一精品夜夜躁人人爽| 国内成人精品视频| 亚洲美女在线视频| 欧美激情在线播放| 亚洲男人的天堂在线播放| 国产精品大片wwwwww| 欧美亚洲在线播放| 国产女人18毛片水18精品| 精品网站999www| 九九热这里只有精品免费看| 78m国产成人精品视频| 欧美日本黄视频| 久久视频精品在线| 91视频国产高清| 国产视频久久久久久久| 亚洲国产免费av| 欧美一级免费看| 亚洲久久久久久久久久| 国产一区二区三区视频免费| 亚洲四色影视在线观看| 国产精品免费视频xxxx| 亚洲欧美综合精品久久成人| 欧美第一页在线| xvideos国产精品| 精品在线欧美视频| 欧美中文字幕在线播放| 欧美性极品xxxx娇小| 欧美诱惑福利视频| 黑人巨大精品欧美一区免费视频| 亚洲淫片在线视频| 亚洲欧美中文日韩v在线观看| 最近2019中文免费高清视频观看www99| 欧美午夜片在线免费观看| 欧美黑人巨大xxx极品| 国产午夜精品视频| 精品福利樱桃av导航| 精品偷拍各种wc美女嘘嘘| 国产女人18毛片水18精品| 国产亚洲成精品久久| 日韩久久午夜影院| 国产精品国产亚洲伊人久久| 亚洲xxxxx性| 久久精品视频一| 色婷婷综合久久久久| 亚洲欧美日韩高清| xvideos成人免费中文版| 国产成人久久久| 久久免费精品视频| 黑人狂躁日本妞一区二区三区| 久久久久久一区二区三区| 韩国三级电影久久久久久| 亚洲iv一区二区三区| 久久91精品国产91久久跳| 国产精品观看在线亚洲人成网| 日韩电影大片中文字幕| 九九热99久久久国产盗摄| 69久久夜色精品国产69乱青草| 欧美性猛交xxxx乱大交极品| 992tv成人免费视频| 久久久久久有精品国产| 69久久夜色精品国产7777| 亚洲欧洲高清在线| 国产精品久久久久99| 一本一道久久a久久精品逆3p| 日韩欧美在线视频| 欧美尤物巨大精品爽| 日韩中文字幕视频| 久久99久久99精品免观看粉嫩| 亚洲欧洲一区二区三区久久| 欧美专区日韩视频| 久久69精品久久久久久久电影好| 免费97视频在线精品国自产拍| 日韩一区在线视频| 国内精品久久久久久影视8| 96pao国产成视频永久免费| 亚洲欧美激情在线视频| 亚洲xxxx妇黄裸体| 亚洲人成电影网站色xx| www.欧美免费| 欧美一级bbbbb性bbbb喷潮片| 亚洲综合在线播放| 中文欧美日本在线资源| 久久九九国产精品怡红院| 精品无人区乱码1区2区3区在线| 亚洲自拍另类欧美丝袜| 成人观看高清在线观看免费| 欧美亚洲激情视频| 亚洲成人久久一区| 午夜精品视频在线| 欧洲成人午夜免费大片| 视频在线观看99| 九九精品视频在线| 亚洲国产古装精品网站| 国产成人精品午夜| 中文字幕成人精品久久不卡| 欧洲日韩成人av| 日韩日本欧美亚洲| 国产精品7m视频| 最近2019中文字幕mv免费看| 中文字幕亚洲欧美日韩高清| 午夜剧场成人观在线视频免费观看| 国产日韩在线观看av| 美女精品久久久| 91色视频在线观看| 九九久久综合网站| 日韩在线观看免费全集电视剧网站| 欧美在线视频免费播放| 另类色图亚洲色图| 91精品国产99| 亚洲免费视频一区二区| 亚洲人成电影网站色www| 久久久综合免费视频| 日韩中文字幕视频| 国产ts人妖一区二区三区| 国产精品永久免费视频| 中文日韩电影网站| 日韩av三级在线观看| 日韩在线观看免费全集电视剧网站| 91天堂在线视频| 亚洲人成77777在线观看网| 国产精品黄色影片导航在线观看| 久久最新资源网| 性欧美xxxx视频在线观看| 九九久久精品一区| 亚洲欧美日韩国产成人| 免费av在线一区| 精品福利视频导航| 亚洲日韩欧美视频一区| 中文字幕久热精品在线视频| 91国内精品久久| 亚洲国产97在线精品一区| 亚洲视频在线观看视频| 国产成人精品视频| 国产丝袜一区二区| 国产福利精品视频| 欧美国产中文字幕| 亚洲一区二区精品| 色香阁99久久精品久久久| 日本电影亚洲天堂| 日韩免费黄色av| 国产精品国产三级国产专播精品人| 综合国产在线视频| 91久久国产综合久久91精品网站| 精品国产电影一区| 美女999久久久精品视频| 日本午夜精品理论片a级appf发布| 操91在线视频| 国产91九色视频| 日韩视频在线免费| 色爱av美腿丝袜综合粉嫩av| 国产ts一区二区| 久久精品2019中文字幕| 国产精品免费在线免费|