Ruby on rails code skills

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

Git repository 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,200 8
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: 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,200 8
The first five most frequently used commands
History | awk {'print $ 2'} | sort | uniq-c | sort-k1-rn | head-n5

Posted by holin At May 15,200
Sort by an attribute of an array element
@ Users. sort! {| A, B | a. last <=> B. last}

Posted by holin At May 11,200 8
Back up databases by date
Mysqldump db_name-uroot> "/root/db_backup/kaoshi_web _ 'date +" % Y-% m-% d "'. SQL"

Posted by holin At May 08,200 8
Use memcached to manually cache data

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 30 min
End
Memcache-client 1.5.0:
Get (key, expiry = 0)
Put (key, value, expiry = 0)

Posted by devon At May 04,200 8
Shuffle an array

Class Array
Def shuffle
Sort_by {rand}
End
Def shuffle!
Self. replace shuffle
End
End

Posted by holin At May 04,200 8
Make all ajax requests not 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,200 8
Find with Hash

Event. find (
: All,
: Conditions => ["title like: search or description like: search ",
{: Search => "% Tiki %"}]
)

Posted by devon At May 03,200 8
Execute the SQL statement script

Mysql-uroot-p123 <END
Use dbame;
Delete from results;
Delete from examings;
Quit
END

Posted by holin At May 01,200 8
SQL Transaction in Rails

Def fetch_value
SQL = ActiveRecord: Base. connection ();
SQL .exe cute "SET autocommit = 0 ";
SQL. begin_db_transaction
Id, value =
SQL .exe cute ("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 limit l 30,200 8
Display the dynamic effect of Flash messages

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

Posted by devon At least l 29,200 8
Delete constants in the environment

Object. send (: remove_const,:)
> Math
=> Math
> Object. send (: remove_const,: Math)
=> Math
> Math
NameError: uninitialized constant Math

Posted by devon At least l 28,200 8
Manually add authenticity_token
<Div style = "margin: 0; padding: 0 "> <input name =" authenticity_token "type =" hidden "value =" <% = form_authenticity_token %> "/> </div>

Posted by devon At least l 28,200 8
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 % dday') %> <% = Render: partial => 'Article',: collection => articles %>
</Div>
<% End %>
Articles are grouped by days

Posted by devon At least l 25,200 8
Read/write files

# 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 limit l 17,200 8
Traverse directories
Dir. glob (File. join ('app/controllers', "**", "* _ controller. rb") {| filename | puts filename}

Posted by holin At limit l 16,200 8
String to model
1
2
> 'Tag _ course'. camw.e. 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, camw.e converts strings to UpperCamelCase. If the argument to cam%e is set to ": lower" then cam%e 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 least l 07,200 8
Call Proc
1
2
3
A = Proc. new {| I | puts I}
A ['hahaha']
A. call ('hehes ')

Posted by holin At March 28,200 8
Host static files 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 will then use that host to reference files in the public directory.
The second line will distribute asset requests guest SS assets-0.example.com, assets-1.example.com, assets-2.example.com, and assets-3.example.com.

Posted by devon At March 26,200 8
Package gems to the project directory

$ Mkdir vendor/gems
$ Cd vendor/gems
$ Gem unpack hpricot
Unpacked gem: 'hpricot-8080'
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,200 8
Execute the code in the file in the current context

Instance_eval(File.read('param.txt '))
# Such
@ Father = 'father'
Instance_eval ("puts @ father ")
# Produces:
# Father

Posted by holin At March 20,200 8
Add the directory of the current file 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 the other path.
$:. Unshift (File. expand_path (File. dirname (_ FILE __)))
* _ FILE _ * current FILE path

Posted by holin At March 19,200 8
Multi-field fuzzy search

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
In the profile table, perform fuzzy search by name, school, province, and city.

Posted by devon At March 17,200 8
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 "\ 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
Write the file to/etc/init. d/nginx
Sudo chmod + x/etc/init. d/nginx
Test availability
Sudo/etc/init. d/nginx start
Set automatic start
Sudo/sbin/chkconfig -- level 345 nginx on

Posted by devon At March 16,200 8
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 Page.

Posted by devon At March 16,200 8
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 shocould process the value and return the updated value in the body
# 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 shoshould
# 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 shoshould 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 shoshould 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
Solve the ActionController: InvalidAuthenticityToken error when in_place_editor is used in rails2.0 or later versions.

Posted by devon At March 15,200 8
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> <Body>
<B> <% = @ greeting %> </B>
</Body> 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,200 8
Use different layout in before_filter
Before_filter Proc. new {| controller | layout 'iframe' unless controller. request. env ["HTTP_REFERER"] = ~ /Localhost /}
If it is not accessed from the localhost site, use layout of iframe

Posted by devon At March 11,200 8
Get HTTP_REFERER in Rails
Request. env ["HTTP_REFERER"]
The following parameters can be obtained:
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 = %%%%%%%%%%;_ slemail = temp % 40email.com; _ slhash = %;_ haha_session = %%%250asgfzahsabjokqhvzzwr7aa % 253D % 253D -- reset
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.