Ruby on Rails code tips _ruby Topics

Source: Internet
Author: User
Tags constant math shuffle ruby on rails

Git warehouse output
Git Archive--format=tar--prefix=actasfavor/head | (cd/home/holin/work/&& Tar XF-)
Output to the/home/holin/work/actasfavor/directory

Posted by Holin at May 16, 2008 16:42
Load controller and model in plugins

# Include Hook code here
Require ' Act_as_favor '
# Make plugin controller, model, helper available to app
Config.load_paths + =%w (#{actasfavor::P lugin_controller_path} #{actasfavor::P Lugin_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
Use the top 5 commands most frequently
History | awk {' Print $ '} | Sort | uniq-c | sort-k1-rn| Head-n5

Posted by Holin at May 15, 2008 10:40
Sort by an attribute of an array element
@users. sort! {|a, b| a.last <=> B.last}

Posted by Holin at May 11, 2008 14:35
Back up a database by date
Mysqldump db_name-uroot > "/root/db_backup/kaoshi_web_ ' date +"%y-%m-%d "'. sql"

Posted by Holin at May 08, 2008 12:05
Manual cache data with memcached

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
Make all the Ajax requests 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
Execute SQL statement Script

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
Display the dynamic effect of a Flash message

<% 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%>
Automatically notice Div disappears after 15000 milliseconds.

Posted by Devon at April 29, 2008 13:02
Deleting constants in an environment

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
Manually plus 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 (&:d ay). Each do |day, articles| %>
<div id= ' Day ' style= "padding:10px 0;" >
<%= render:p artial => ' article ', collection, => articles
</div>
<% End%>
Articles GROUP BY days

Posted by Devon at April 25, 2008 22:32
Read and write files

# Open and read from a text file
# that's since a block is given, file would
# automatically be closed ' 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
Traverse Directory
Dir.glob (File.join (' app/controllers ', "* *", "*_controller.rb")) {|filename| puts filename}

Posted by Holin at April 16, 2008 15:28
String to model
1
2
>> ' Tag_course '. Camelize.constantize.find (: a)
=> #<tagcourse Id:7, tag_id:83, course_id:2>
*camelize (Lower_case_and_underscored_word, first_letter_in_uppercase = True) *
By default, the Camelize converts strings to uppercamelcase. If the argument to Camelize are set to ": Lower" then camelize produces.
*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 ' is ' not ' in CamelCase ' or ' is ' not ' initialized.

Posted by Devon at April 07, 2008 17:32
Call proc
1
2
3
A = proc.new {|i| puts i}
a[' haha ']
A.call (' hehe ')

Posted by Holin at March 28, 2008 23:10
The host static file in Rails
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 would then use this host to reference files into the public directory.
The second line would 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
Package gems into the project directory

$ 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
Executing code in a file in the current context

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
Add the current file directory to the Require path

$LOAD _path << File.expand_path (File.dirname (__file__))
# or
$: << File.expand_path (File.dirname (__file__))
# This one puts current path before to the other path.
$:.unshift (File.expand_path (File.dirname (__file__))
*__ file __* Current files path

Posted by Holin at March 19, 2008 01:40
Multi-field Fuzzy search

conditions = []
[: Name,: School,:p rovince,: city].each {|attr| conditions << profile.send (: Sanitize_sql, ["#{attr} like?", "%#{pa rams[:q]}% "]) if PARAMS[:Q]}
conditions = Conditions.any?? Conditions.collect {|c| "(#{c})"}.join (' OR '): Nil
In the profile, press name, school, province, city Blur search

Posted by Devon at March 17, 2008 17:25
Nginx Startup script


#! /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 "\ already Running"
}
D_stop () {
Kill-quit ' Cat $PIDFILE ' | | Echo-en "\ Not Running"
}
D_reload () {
Kill-hup ' Cat $PIDFILE ' | | Echo-en "\ can ' t reload"
}
Case "$" 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 being time enough for a daemon to stop,
# If this happens, D_start'll fail (and dpkg would break if
# The package is being upgraded). Change the timeout if needed
# be, or the d_stop to have start-stop-daemon the 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
Write files to/etc/init.d/nginx
sudo chmod +x/etc/init.d/nginx
Test to run correctly
Sudo/etc/init.d/nginx start
Set Auto Start
Sudo/sbin/chkconfig--level 345 Nginx on

Posted by Devon at March 16, 2008 12:26
Link_to_remote static page
1
2
<%= link_to_remote "update post": Update => ' Post ': Method => ' Get ',: url => '/post_1.html '%>
<div id= ' Post ' ></div>
Change the URL to the address of the static surface page.

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 a In-place
# Editor of a property.
#
# A form is automatically created and displayed 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" editing ">cancel</a>
# </form>
#
# The form is serialized and sent to the server using a AJAX call, the action on
# The server should process the value and return the updated value of
# The Reponse. The element would automatically be updated with the changed value
# (as returned from the server).
#
# Required +options+ are:
# <tt>:url</tt&gt:: Specifies the URL where the updated value should
# be sent after the user presses ' OK '.
#
# addtional +options+ are:
# <tt>:rows</tt&gt:: Number of rows (more than 1 would use a TEXTAREA)
# <tt>:cols</tt&gt:: Number of characters the text input should span (works for both input and TEXTAREA)
# <tt>:size</tt&gt:: Synonym For:cols when using a single line text input.
# &LT;TT&GT;:CANCEL_TEXT&LT;/TT&GT;:: The text on the cancel link. (Default: "Cancel")
# &LT;TT&GT;:SAVE_TEXT&LT;/TT&GT;:: The text on the Save link. (Default: "OK")
# <tt>:loading_text</tt&gt:: The text to display while the ' data is ' being loaded from the server (default: "Loadi Ng ... ")
# <tt>:saving_text</tt&gt:: The text to display when submitting to the server (default: "Saving ...")
# <tt>:external_control</tt&gt:: The ID of a external control used to enter edit mode.
# <tt>:load_text_url</tt&gt:: URL where initial value of editor (content) is retrieved.
# <tt>:options</tt&gt:: Pass through options to the AJAX call (the prototype ' s ajax.updater)
# <tt>:with</tt&gt:: JavaScript snippet that should return what are to be sent
# in the AJAX call, +form+ are an implicit parameter
# <tt>:script</tt&gt:: 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
Resolves the actioncontroller::invalidauthenticitytoken error that occurs when the in_place_editor is used with the rails2.0 version.

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 the IS
<%= Time.now%>
<% End%>
<body>
<b><%= @greeting%></b>
</body>The Capture method allows your to extract part of a template into a variable. You can then the variable anywhere in your templates or layout.

Posted by Devon at March 13, 2008 14:06
Use different layout in Before_filter
Before_filter proc.new {|controller| layout ' iframe ' unless controller.request.env[' http_referer '] =~/localhost/}
If you are not accessing this site from localhost, use the layout of the IFRAME

Posted by Devon at March 11, 2008 17:38
Get Http_referer in Rails
request.env["Http_referer"]
The parameters that can be taken include:
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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.