(转)关于git仓库的初始化和git push的操作

 

 

(转)关于git仓库的初始化和git push的操作

分类: 版本管理 2011-06-23 20:33 146人阅读 评论(0) 收藏 举报

Git 初始化
2010-08-26 16:53
**********************************************************

为git安装一个远程仓库
2010-05-28 Linux 查看评论 需要将代码push到一个远程仓库

在远程服务器上初始化空的仓库

mkdir /home/git/myapp.git  && cd /home/git/myapp.git
git –bare init
初始化了一个空的仓库

在本地的git仓库添加一个远程仓库
cd  ~/myapp
git remote add origin ssh://myserver.com/home/git/myapp.git
这时候,本地的 .git/config 应该会改变

git push origin master
将本地的 master分支  跟踪到远程的分支

显示远程信息
git remote show origin
**********************************************************
git默认拒绝了push操作,需要进行设置,修改.git/config添加如下代码:

[receive]
denyCurrentBranch = ignore

 

在初始化远程仓库时最好使用 git –bare init   而不要使用:git init

如果使用了git init初始化,则远程仓库的目录下,也包含work tree,当本地仓库向远程仓库push时,   如果远程仓库正在push的分支上(如果当时不在push的分支,就没有问题), 那么push后的结果不会反应在work tree上,  也即在远程仓库的目录下对应的文件还是之前的内容,必须得使用git reset –hard才能看到push后的内容.
*********************************************************

在初始化远程仓库最好使用下面命令来初始化:

git –bare init

而不要使用:

git init
如果使用了git init初始化,则远程仓库的目录下,也包含work tree,当本地仓库向远程仓库push时
如果远程仓库正在push的分支上(如果当时不在push的分支,就没有问题)
那么push后的结果不会反应在work tree上
也即在远程仓库的目录下
对应的文件还是之前的内容,必须得使用git reset –hard才能看到push后的内容

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/kamemo/archive/2011/05/28/6452136.aspx

ruby (no-rails) project structure

Take a look at Mr Bones. It encapsulates many ruby best-practices and
lots of rake tasks to take care of the day-to-day development tasks

gem install bones

bones create new_project
cd new_project

rake -T            # shows you all the available tasks
rake bones:help    # shows you the various project configuration
settings

Other tools in the same vein as Mr Bones are "hoe" and "jeweler"

gem install hoe
gem install jeweler

I'm slightly partial to Mr Bones being the author and all.

Blessings,
TwP

Ruby commands notes (3)

rails generate scaffold Product title:string description:text image_url:string price:decimal

class CreateProducts < ActiveRecord::Migration
def self.up
create_table :products do |t|
t.string :title
t.text :description
t.string :image_url
t.decimal :price, :precision => 8, :scale => 2
t.timestamps
end
end

rake db:migrate

Product.delete_all
Product.create(:title => ‘Programming Ruby 1.9′ ,
:description =>
%{<p>
Ruby is the fastest growing and most exciting dynamic language out
there. If you need to get working programs delivered fast, you should
add Ruby to your toolbox.
</p>},
:image_url => ‘/images/ruby.jpg’ ,
:price => 49.50)

rake db:seed

rake db:rollback

class Product < ActiveRecord::Base
validates :title, :description, :image_url, :presence => true
validates :price, :numericality => {:greater_than_or_equal_to => 0.01}
validates :title, :uniqueness => true
validates :image_url, :format => {
:with => %r{\.(gif|jpg|png)$}i,
:message => ‘must be a URL for GIF, JPG or PNG image.’
}
end

 

rails generate controller store index

root :to => ‘store#index’ , :as => ‘store’

class Product < ActiveRecord::Base
default_scope :o rder => ‘title’
# validation stuff…
end

<%=sanitize product.description %>

image_tag(product.image_url)

<%= sprintf(“$%0.02f” , product.price)

Using our helper in the view is simple: in the index template, we change this:
<span ><%= product.price %></span>
to the following:
<span ><%= number_to_currency(product.price) %></span>

rails generate migration add_quantity_to_line_item quantity:integer

 

 

RubyMine 3.x 序列号

daigong

===== LICENSE BEGIN =====
46425-12042010
00001gwy4iEkkl3WLkBhwy”Tzs7kUd
!R07GdX9ryBR”CsTVVSccXQ”xLvq0N
AUhvn82bOajcBPrkxijpKpMqXQjzD!
===== LICENSE END =====

zhaozhongyi

===== LICENSE BEGIN =====
66595-12042010
00001Nr3WvSd7iXewTVGQaQ”1NDFUn
PpuScjzENqJpde7kYDmwqXraZEjAq5
NGeARrOyloqyr0ijfQWKTBrSPM5ISk
===== LICENSE END =====

wangxuan

===== LICENSE BEGIN =====
48291-12042010
00000emzEz7Xz7osstk2PNKywX3wl2
Uu0VdWOFc”weJiH8AoxX8qCibbzZIy
7rTtUygYhSXCnRiysq29hmZV7vdTy6
===== LICENSE END =====

liujinguo

===== LICENSE BEGIN =====
97974-12042010
00001bkeukZWlkDKe14!EVcQ48idDb
1jM76aGqUQWZTfQL”etyPS41CR8cr0
eJqByDbWHow”0yprmfKnyO”t2USk0a
===== LICENSE END =====

Ruby QuickRef

http://www.zenspider.com/Languages/Ruby/QuickRef.html

Sitemap | Search || Zen Spider Website / The Language Freak / Ruby / Ruby QuickRef

Ruby QuickRef


Contents:

PDF Version: www.mabitoga.de /downloads /Ruby_QuickRef_1.pdf

Language

General Tips

These are tips I’ve given over and over and over and over…

  • Use 2 space indent, no tabs.
  • dontNameVarsCamelCase, use_readable_variables.
  • use [] over Array.new.
  • and {} over Hash.new.
  • don’t rescue Exception. EVER. or I will stab you.
  • don’t call exit inside of a library method.
  • use space more.
  • use globals less.
  • use parens to disambiguate, otherwise avoid them.
  • use Enumerable.map instead of reimplementing it with each.
  • returning different types is almost always a no-no.
  • hungarian notation is for Other Languages, not Ruby.
  • separate ideas with blank lines, just like paragraphs.
  • align stuff to be cleaner and to optimize for human pattern matching.

See github.com /chneukirchen /styleguide /raw /master /RUBY-STYLE for more.

General Syntax Rules

  • Comments start with a pound/sharp (#) character and go to EOL.
  • Ruby programs are sequence of expressions.
  • Each expression is delimited by semicolons(;) or newlines unless obviously incomplete (e.g. trailing ‘+’).
  • Backslashes at the end of line does not terminate expression.

Reserved words

alias   and     BEGIN   begin   break   case    class   def     defined?
do      else    elsif   END     end     ensure  false   for     if
in      module  next    nil     not     or      redo    rescue  retry
return  self    super   then    true    undef   unless  until   when
while   yield

Types

Basic types are numbers, strings, ranges, regexen, symbols, arrays, and hashes. Also included are files because they are used so often.

Numbers

123 1_234 123.45 1.2e-3 0xffff (hex) 0b01011 (binary) 0377 (octal)
?a       ASCII character
?\C-a    Control-a
?\M-a    Meta-a
?\M-\C-a Meta-Control-a

Strings

In all of the %() cases below, you may use any matching characters or any single character for delimiters. %[], %!!, %@@, etc.

'no interpolation'
"#{interpolation}, and backslashes\n"
%q(no interpolation)
%Q(interpolation and backslashes)
%(interpolation and backslashes)
`echo command interpretation with interpolation and backslashes`
%x(echo command interpretation with interpolation and backslashes)
Backslashes
\t (tab), \n (newline), \r (carriage return), \f (form feed), \b
(backspace), \a (bell), \e (escape), \s (whitespace), \nnn (octal),
\xnn (hexadecimal), \cx (control x), \C-x (control x), \M-x (meta x),
\M-\C-x (meta control x)
Here Docs
<<identifier   - interpolated, goes until identifier
<<"identifier" - same thing
<<'identifier' - no interpolation
<<-identifier  - you can indent the identifier by using "-" in front

Symbols

Internalized String. Guaranteed to be unique and quickly comparable. Ideal for hash keys. Symbols may not contain \0 or be empty.

:symbol                         => :symbol
:'#{"without"} interpolation'  => :"#{"without"} interpolation"
:"#{"with"} interpolation"     => :"with interpolation"
%s(#{"without"} interpolation) => :"#{"without"} interpolation"

Ranges

1..10
1...10
'a'..'z'
'a'...'z'
(1..10)  === 5   => true
(1..10)  === 10  => true
(1...10) === 10  => false
(1..10)  === 15  => false
while gets # prints lines starting at 'start' and ending at 'end'
  print if /start/../end/
end
class Comparable
  # ...
  def <=>(rhs)
    # ...
  end
  def succ
    # ...
  end
end
range = RangeThingy.new(lower_bound)..RangeThingy.new(upper_bound)

Regexen

Test out your regexen in irb or on: www.rubyxp.com

Usual recommended form:

str =~ /regex/

Lexical options:

/normal regex/iomx[neus]
%rXalternate formX (where X can be any character or pair () {} etc)

options:

/i         case insensitive
/o         only interpolate #{} blocks once
/m         multiline mode - '.' will match newline
/x         extended mode - whitespace is ignored
/[neus]    encoding: none, EUC, UTF-8, SJIS, respectively

regex characters:

.             any character except newline
[ ]           any single character of set
[^ ]          any single character NOT of set
*             0 or more previous regular expression
*?            0 or more previous regular expression (non-greedy)
+             1 or more previous regular expression
+?            1 or more previous regular expression (non-greedy)
?             0 or 1 previous regular expression
|             alternation
( )           grouping regular expressions
^             beginning of a line or string
$             end of a line or string
{m,n}         at least m but most n previous regular expression
{m,n}?        at least m but most n previous regular expression (non-greedy)
\1-9          nth previous captured group
\&            whole match
\`            pre-match
\'            post-match
\+            highest group matched
\A            beginning of a string
\b            backspace(0x08)(inside[]only)
\b            word boundary(outside[]only)
\B            non-word boundary
\d            digit, same as[0-9]
\D            non-digit
\S            non-whitespace character
\s            whitespace character[ \t\n\r\f]
\W            non-word character
\w            word character[0-9A-Za-z_]
\z            end of a string
\Z            end of a string, or before newline at the end
(?#)          comment
(?:)          grouping without backreferences
(?=)          zero-width positive look-ahead assertion
(?!)          zero-width negative look-ahead assertion
(?>)          nested anchored sub-regexp. stops backtracking.
(?imx-imx)    turns on/off imx options for rest of regexp.
(?imx-imx:re) turns on/off imx options, localized in group.

special character classes:

[:alnum:]   alpha-numeric characters
[:alpha:]   alphabetic characters
[:blank:]   whitespace - does not include tabs, carriage returns, etc
[:cntrl:]   control characters
[:digit:]   decimal digits
[:graph:]   graph characters
[:lower:]   lower case characters
[:print:]   printable characters
[:punct:]   punctuation characters
[:space:]   whitespace, including tabs, carriage returns, etc
[:upper:]   upper case characters
[:xdigit:]  hexadecimal digits

Arrays

[1, 2, 3]
%w(foo bar baz)
%W(foo bar baz #{var})

Indexes may be negative, and they index backwards (eg -1 is last element).

Hashes

{1=>2, 2=>4, 3=>6}
{ expr => expr...}

Files

Common methods include:

  • File.join(p1, p2, … pN) => “p1/p2/…/pN” platform independent paths
  • File.new(path, modestring=”r”) => file
  • File.new(path, modenum [, permnum]) => file
  • File.open(fileName, aModeString=”r”) {|file| block} -> nil
  • File.open(fileName [, aModeNum [, aPermNum ]]) {|file| block} -> nil
  • IO.foreach(path, sepstring=$/) {|line| block}
  • IO.readlines(path) => array
Mode Strings
r
Read-only, starts at beginning of file (default mode).
r+
Read-write, starts at beginning of file.
w
Write-only, truncates existing file to zero length or creates a new file for writing.
w+
Read-write, truncates existing file to zero length or creates a new file for reading and writing.
a
Write-only, starts at end of file if file exists, otherwise creates a new file for writing.
a+
Read-write, starts at end of file if file exists, otherwise creates a new file for reading and writing.
b
(DOS/Windows only) Binary file mode (may appear with any of the key letters listed above).

Variables

$global_variable
@@class_variable
@instance_variable
[OtherClass::]CONSTANT
local_variable

Pseudo variables

self     the receiver of the current method
nil      the sole instance of the Class NilClass(represents false)
true     the sole instance of the Class TrueClass(typical true value)
false    the sole instance of the Class FalseClass(represents false)
__FILE__ the current source file name.
__LINE__ the current line number in the source file.

Pre-defined variables

$!         The exception information message set by 'raise'.
$@         Array of backtrace of the last exception thrown.
$&         The string matched by the last successful match.
$`         The string to the left  of the last successful match.
$'         The string to the right of the last successful match.
$+         The highest group matched by the last successful match.
$1         The Nth group of the last successful match. May be > 1.
$~         The information about the last match in the current scope.
$=         The flag for case insensitive, nil by default.
$/         The input record separator, newline by default.
$\         The output record separator for the print and IO#write. Default is nil.
$,         The output field separator for the print and Array#join.
$;         The default separator for String#split.
$.         The current input line number of the last file that was read.
$<         The virtual concatenation file of the files given on command line (or from $stdin if no files were given).
$>         The default output for print, printf. $stdout by default.
$_         The last input line of string by gets or readline.
$0         Contains the name of the script being executed. May be assignable.
$*         Command line arguments given for the script sans args.
$$         The process number of the Ruby running this script.
$?         The status of the last executed child process.
$:         Load path for scripts and binary modules by load or require.
$"         The array contains the module names loaded by require.
$DEBUG     The status of the -d switch.
$FILENAME  Current input file from $<. Same as $<.filename.
$LOAD_PATH The alias to the $:.
$stderr    The current standard error output.
$stdin     The current standard input.
$stdout    The current standard output.
$VERBOSE   The verbose flag, which is set by the -v switch.
$-0        The alias to $/.
$-a        True if option -a is set. Read-only variable.
$-d        The alias to $DEBUG.
$-F        The alias to $;.
$-i        In in-place-edit mode, this variable holds the extension, otherwise nil.
$-I        The alias to $:.
$-l        True if option -l is set. Read-only variable.
$-p        True if option -p is set. Read-only variable.
$-v        The alias to $VERBOSE.
$-w        True if option -w is set.

Pre-defined global constants

TRUE              The typical true value.
FALSE             The false itself.
NIL               The nil itself.
STDIN             The standard input. The default value for $stdin.
STDOUT            The standard output. The default value for $stdout.
STDERR            The standard error output. The default value for $stderr.
ENV               The hash contains current environment variables.
ARGF              The alias to the $<.
ARGV              The alias to the $*.
DATA              The file object of the script, pointing just after __END__.
RUBY_VERSION      The ruby version string (VERSION was deprecated).
RUBY_RELEASE_DATE The release date string.
RUBY_PLATFORM     The platform identifier.

Expressions

Terms

Terms are expressions that may be a basic type (listed above), a shell command, variable reference, constant reference, or method invocation.

Operators and Precedence

(Top to bottom)
:: .
[]
**
-(unary) +(unary) ! ~
*  /  %
+  -
<<  >>
&
|  ^
>  >=  <  <=
<=> == === != =~ !~
&&
||
.. ...
=(+=, -=...)
not
and or

All of the above are just methods except these:

=, ::, ., .., ..., !, not, &&, and, ||, or, !=, !~

In addition, assignment operators(+= etc.) are not user-definable.

NOTE: 1.9 has a horrible extension to allow you to define != and !~. A special place in hell is reserved for you if you define those.

Control Expressions

if bool-expr [then]
  body
elsif bool-expr [then]
  body
else
  body
end
unless bool-expr [then]
  body
else
  body
end
expr if     bool-expr
expr unless bool-expr
bool-expr ? true-expr : false-expr
case target-expr
  when comparison [, comparison]... [then]
    body
  when comparison [, comparison]... [then]
    body
  ...
[else
  body]
end

(comparisons may be regexen)

loop do
  body
end
while bool-expr [do]
 body
end
until bool-expr [do]
 body
end
begin
 body
end while bool-expr
begin
 body
end until bool-expr
for name[, name]... in expr [do]
  body
end
expr.each do | name[, name]... |
  body
end
expr while bool-expr
expr until bool-expr
  • break terminates loop immediately.
  • redo immediately repeats w/o rerunning the condition.
  • next starts the next iteration through the loop.
  • retry restarts the loop, rerunning the condition.

Invoking a Method

Nearly everything available in a method invocation is optional, consequently the syntax is very difficult to follow. Here are some examples:

  • method
  • obj.method
  • Class::method
  • method(key1 => val1, key2 => val2)
    • is one argument for def method(hash_arg) !
  • method(arg1, *[arg2, arg3]) becomes: method(arg1, arg2, arg3)
  • as ugly as you want it to be:
    • method(arg1, key1 => val1, key2 => val2, *splat_arg) #{ block }
invocation := [receiver ('::' | '.')] name [ parameters ] [ block ]
parameters := ( [param]* [, hashlist] [*array] [&aProc] )
block      := { blockbody } | do blockbody end

Defining a Class

Class names begin w/ capital character.

class Identifier [< superclass ]
  expr..
end
# singleton classes, add methods to a single instance
class << obj
  expr..
end

Defining a Module

module Identifier
  expr..
end

Defining a Method

def method_name(arg_list, *list_expr, &block_expr)
  expr..
end
# singleton method
def expr.identifier(arg_list, *list_expr, &block_expr)
  expr..
end
  • All items of the arg list, including parens, are optional.
  • Arguments may have default values (name=expr).
  • Method_name may be operators (see above).
  • The method definitions can not be nested.
  • Methods may override operators: |, ^, &, <=>, ==, ===, =~, >, >=, <, <=, +, -, *, /, %, **, <<, >>, ~, +@, -@, [], []= (2 args)

Access Restriction

  • public – totally accessible.
  • protected – accessible only by instances of class and direct descendants. Even through hasA relationships. (see below)
  • private – accessible only by instances of class (must be called nekkid no “self.” or anything else).
  • Restriction used w/o arguments set the default access control.
  • Used with arguments, sets the access of the named methods and constants.
class A
  protected
  def protected_method
    # nothing
  end
end
class B < A
  public
  def test_protected
    myA = A.new
    myA.protected_method
  end
end
b = B.new.test_protected

Accessors

Class Module provides the following utility methods:

attr_reader <attribute>[, <attribute>]…
Creates a read-only accessor for each <attribute>.
attr_writer <attribute>[, <attribute>]…
Creates a write-only accessor for each <attribute>.
attr <attribute> [, <writable>]
Equivalent to “attr_reader <attribute>; attr_writer <attribute> if <writable>”
attr_accessor <attribute>[, <attribute>]…
Equivalent to “attr <attribute>, TRUE” for each argument.

Aliasing

alias        :new  :o ld
alias_method :new, :o ld

Creates a new reference to whatever old referred to. old can be any existing method, operator, global. It may not be a local, instance, constant, or class variable.

Blocks, Closures, and Procs

Blocks/Closures

  • blocks must follow a method invocation:
invocation do ... end
invocation { ... }
  • Blocks remember their variable context, and are full closures.
  • Blocks are invoked via yield and may be passed arguments.
  • Brace form has higher precedence and will bind to the last parameter if invocation made w/o parens.
  • do/end form has lower precedence and will bind to the invocation even without parens.

Proc Objects

Created via:

  • Kernel#proc
  • Proc#new
  • By invoking a method w/ a block argument.

See class Proc for more information.

Exceptions, Catch, and Throw

  • Exception
    • NoMemoryError
    • ScriptError
      • LoadError
      • NotImplementedError
      • SyntaxError
    • SignalException
      • Interrupt
    • StandardError (default for rescue)
      • ArgumentError
      • IOError
        • EOFError
      • IndexError
      • LocalJumpError
      • NameError
        • NoMethodError
      • RangeError
        • FloatDomainError
      • RegexpError
      • RuntimeError (default for raise)
      • SecurityError
      • SystemCallError
        • Errno::*
      • SystemStackError
      • ThreadError
      • TypeError
      • ZeroDivisionError
    • SystemExit
    • fatal

Raising and Rescuing

raise ExceptionClass[, "message"]
begin
  expr..
[rescue [error_type [=> var],..]
  expr..]..
[else
  expr..]
[ensure
  expr..]
end

Catch and Throw

  • catch (:label) do … end
  • throw :label jumps back to matching catch and terminates the block.
  • + can be external to catch, but has to be reached via calling scope.
  • + Hardly ever needed.

Standard Library

Ruby comes with an extensive library of classes and modules. Some are built-in, and some are part of the standard library. You can distinguish the two by the fact that the built-in classes are in fact, built-in. There are no dot-rb files for them.

Built-in Library

Class Hierarchy

  • Object
    • Hash
    • Symbol
    • IO
      • File
    • Continuation
    • File::Stat
    • Data
    • NilClass
    • Exception (see tree above)
    • Array
    • Proc
    • String
    • Numeric
      • Float
      • Integer
        • Bignum
        • Fixnum
    • Regexp
    • Thread
    • Module
      • Class
    • ThreadGroup
    • Method
      • UnboundMethod
    • Struct
      • Struct::Tms
    • TrueClass
    • Time
    • Dir
    • Binding
    • Range
    • MatchData
    • FalseClass

Modules

  • Comparable
  • Enumerable
  • Errno
  • FileTest
  • GC
  • Kernel
  • Marshal
  • Math
  • ObjectSpace
  • Precision
  • Process

Standard Library

The essentials:

  • benchmark.rb a simple benchmarking utility
  • cgi-lib.rb decode CGI data – simpler than cgi.rb
  • cgi.rb CGI interaction
  • date.rb date object (compatible)
  • debug.rb ruby debugger
  • delegate.rb delegate messages to other object
  • English.rb access global variables by english names
  • fileutils.rb file utility methods for copying, moving, removing, etc.
  • find.rb traverse directory tree
  • jcode.rb UTF-8 and Japanese String helpers (replaces String methods)
  • net/*.rb Networking classes of all kinds
  • observer.rb observer design pattern library (provides Observable)
  • open-uri.rb good wrapper for net/http, net/https and net/ftp
  • open3.rb open subprocess connection stdin/stdout/stderr
  • ostruct.rb python style object (freeform assignment to instance vars)
  • parsearg.rb argument parser using getopts
  • pp prettier debugging output, ‘p’ on steroids.
  • profile.rb ruby profiler – find that slow code!
  • pstore.rb persistent object strage using marshal
  • rexml/*.rb XML toolkit
  • singleton.rb singleton design pattern library
  • stringio lets you use an IO attached to a string.
  • tempfile.rb temporary file that automatically removed
  • test/unit unit testing framework
  • time.rb extension to Time class with a lot of converters
  • tracer.rb execution tracer
  • webrick Fairly spiffy web server
  • yaml alternative readable serialization format

Tools

ruby

Command Line Options

-0[octal]       specify record separator (\0, if no argument).
-a              autosplit mode with -n or -p (splits $_ into $F).
-c              check syntax only.
-Cdirectory     cd to directory, before executing your script.
--copyright     print the copyright and exit.
-d              set debugging flags (set $DEBUG to true).
-e 'command'    one line of script. Several -e's allowed.
-F regexp       split() pattern for autosplit (-a).
-h		  prints summary of the options.
-i[extension]   edit ARGV files in place (make backup if extension supplied).
-Idirectory     specify $LOAD_PATH directory (may be used more than once).
-Kkcode         specifies KANJI (Japanese) code-set.
-l              enable line ending processing.
-n              assume 'while gets(); ... end' loop around your script.
-p              assume loop like -n but print line also like sed.
-rlibrary       require the library, before executing your script.
-s              enable some switch parsing for switches after script name.
-S              look for the script using PATH environment variable.
-T[level]       turn on tainting checks.
-v              print version number, then turn on verbose mode.
--version       print the version and exit.
-w              turn warnings on for your script.
-x[directory]   strip off text before #! line and perhaps cd to directory.
-X directory    causes Ruby to switch to the directory.
-y              turns on compiler debug mode.

Environment Variables

DLN_LIBRARY_PATH Search path for dynamically loaded modules.
RUBYLIB          Additional search paths.
RUBYLIB_PREFIX   Add this prefix to each item in RUBYLIB. Windows only.
RUBYOPT          Additional command line options.
RUBYPATH         With -S, searches PATH, or this value for ruby programs.
RUBYSHELL        Shell to use when spawning.

irb

irb [options] [script [args]]

The essential options are:

-d              Sets $DEBUG to true. Same as "ruby -d ..."
-f              Prevents the loading of ~/.irb.rc.
-h              Get a full list of options.
-m              Math mode. Overrides --inspect. Loads "mathn.rb".
-r module       Loads a module. Same as "ruby -r module ..."
-v              Prints the version and exits.
--inf-ruby-mode Turns on emacs support and turns off readline.
--inspect       Turns on inspect mode. Default.
--noinspect     Turns off inspect mode.
--noprompt      Turns off the prompt.
--noreadline    Turns off readline support.
--prompt        Sets to one of 'default', 'xmp', 'simple', or 'inf-ruby'.
--readline      Turns on readline support. Default.
--tracer        Turns on trace mode.

Besides arbitrary ruby commands, the special commands are:

exit                  exits the current session, or the program
fork block            forks and runs the given block
cb args               changes to a secified binding
source file           loads a ruby file into the session
irb [obj]             starts a new session, with obj as self, if specified
conf[.key[= val]]     access the configuration of the session
jobs                  lists the known sessions
fg session            switches to the specifed session
kill session          kills a specified session

Session may be specified via session#, thread-id, obj, or self.

xmp

require "irb/xmp"
xmp "something to eval" # or:
x = XMP.new
x.puts "something to eval"

ruby-mode

TODO: I don’t have a freakin clue how to use the inferior ruby thing… I always fire up a shell in emacs… DOH!

Debugger

To invoke the debugger:

ruby -r debug ...

To use the debugger:

b[reak] [file:|class:]<line|method
b[reak] [class.]<line|method
                           set breakpoint to some position
wat[ch] expression         set watchpoint to some expression
cat[ch] exception          set catchpoint to an exception
b[reak]                    list breakpoints
cat[ch]                    show catchpoint
del[ete][ nnn]             delete some or all breakpoints
disp[lay] expression       add expression into display expression list
undisp[lay][ nnn]          delete one particular or all display expressions
c[ont]                     run until program ends or hit breakpoint
s[tep][ nnn]               step (into methods) one line or till line nnn
n[ext][ nnn]               go over one line or till line nnn
w[here]                    display frames
f[rame]                    alias for where
l[ist][ (-|nn-mm)]         list program, - lists backwards
                           nn-mm lists given lines
up[ nn]                    move to higher frame
down[ nn]                  move to lower frame
fin[ish]                   return to outer frame
tr[ace] (on|off)           set trace mode of current thread
tr[ace] (on|off) all       set trace mode of all threads
q[uit]                     exit from debugger
v[ar] g[lobal]             show global variables
v[ar] l[ocal]              show local variables
v[ar] i[nstance] object    show instance variables of object
v[ar] c[onst] object       show constants of object
m[ethod] i[nstance] obj    show methods of object
m[ethod] class|module      show instance methods of class or module
th[read] l[ist]            list all threads
th[read] c[ur[rent]]       show current thread
th[read] [sw[itch]] nnn    switch thread context to nnn
th[read] stop nnn          stop thread nnn
th[read] resume nnn        resume thread nnn
p expression               evaluate expression and print its value
h[elp]                     print this help
everything else            evaluate
empty                      repeats the last command

rdoc

Structure

=     Level One Heading
==    Level Two Heading, and so on
*     bullet list
-     bullet list
1.    numbered list
[cat] labeled list
cat:: labeled list, tabular format
---   horizontal line (rule)

Formatting

_italic_      italic text
*bold*        bold text
+typewriter+  typewriter or mono-spaced text
\+escaped+    escaped, not special formatting

Hyperlinks

http://example.com/index.html        converts to external link, shows link
[home]http://example.com/index.html  converts to external link, shows "home"
link:/some/file/on/my/disk           converts to link to local file

Metadata

# :yields: ...      on method description, ... are yield parameters
# :nodoc:[all]      don't include this element in documentation, all for sub-elements too
# :doc:             force an element to be documented
# :notnew:          do not assume initialize arguments are for the new method
# --                in comment stop rdoc processing
# ++                in comment start rdoc processing again
# :include:filename include filename at this point
# :title:text       set the title for this document to text
# :main:name        set the class, module, or file to appear on the index page
=begin
the everything between a line beginning with `=begin' and
that with `=end' will be skipped by the ruby interpreter.
=end

Command Line Options

Run `rdoc –help` for full listing. Here are the more common flags:

–all, -a
include all methods (not just public) in the output
–diagram, -d
Generate diagrams showing modules and classes.
–exclude, -x pattern
Do not process files or directories matching pattern.
–force-update, -U
forces to scan all sources even if newer than the flag file.
–fmt, -f format name
Output using output formatters: chm, html, ri, xml (pluggable)
–inline-source, -S
Show method source code inline, rather than via a popup link
–main, -m name
‘name’ will be the initial page displayed
–op, -o dir
Set the output directory.
–ri, -r
generate ri output files to ~/.rdoc.
–style, -s stylesheet url
Specifies the URL of a separate stylesheet.
–template, -T template
Set the template used when generating output
–title, -t text
Set ‘text’ as the title for the output.

Mindshare, Idiom and Patterns

Object Design

Visitor Pattern

By defining the method #each and including Enumerable, you get to use all the methods in Enumerable:

class Mailbox
  include Enumerable
  # ...
  def each
    @mail.each do
       # ...
       yield
    end
  end
end

Class SimpleDelegator, DelegateClass

foo = Object.new
foo2 = SimpleDelegator.new(foo)
foo.hash == foo2.hash # => false
Foo = DelegateClass(Array)
class ExtArray<DelegateClass(Array)
  ...
end

Module Observer

monitor.add_observer(self)
...
def update
  ...
  notify_observers(data, ...)
end

Module Singleton

class Klass
  include Singleton
  # ...
end
a, b = Klass.instance, Klass.instance
a == b # => true
a.new  # raises NoMethodError

Other Third-party Libraries

Racc

Test::Unit

  • assert(boolean, message=nil)
  • assert_block(message=”assert_block failed.”) do … end
  • assert_equal(expected, actual, message=nil)
  • assert_in_delta(expected_float, actual_float, delta, message=”")
  • assert_instance_of(klass, object, message=”")
  • assert_kind_of(klass, object, message=”")
  • assert_match(pattern, string, message=”")
  • assert_nil(object, message=”")
  • assert_no_match(regexp, string, message=”")
  • assert_not_equal(expected, actual, message=”")
  • assert_not_nil(object, message=”")
  • assert_not_same(expected, actual, message=”")
  • assert_nothing_raised(*args)
  • assert_nothing_thrown(message=”") do … end
  • assert_operator(object1, operator, object2, message=”")
  • assert_raises(expected_exception_klass, message=”") do … end
  • assert_respond_to(object, method, message=”")
  • assert_same(expected, actual, message=”")
  • assert_send(send_array, message=”")
  • assert_throws(expected_symbol, message=”") do … end
  • flunk(message=”Flunked”)

Original URL: www.zenspider.com/Languages/Ruby/QuickRef.html
$Author: ryand $
$Date: 2011/10/07 $
$Revision: #62 $

Sitemap | Search || Zen Spider Website / The Language Freak / Ruby / Ruby QuickRef

“More matter, with less art” – Gertrude, Hamlet.
Copyright © 1996-2009 Ryan Davis, Seattle.rb, & Zen Spider Software. All Rights Reserved.
Generated: 2011-10-07 23:30:01

ruby rail commands notes(2)

rubys> cd work
work> rails new demo

demo> rails server

demo> rails generate controller Say hello goodbye

<%= link_to “Goodbye!” , say_goodbye_path %>

order = Order.find(1) puts
puts “Customer #{order.customer_id}, amount=$#{order.amount}”

Order.where(:name => ‘dave’ ).each do |order|
puts order.amount
end

redirect_to :action => “edit” , :id => params[:id]

ages = []
for person in @people
ages << person.age
end

a = [ 'ant' , 'bee' , 'cat' , 'dog' , 'elk' ]
# this is the same:
a = %w{ ant bee cat dog elk }

begin
content = load_blog_data(file_name)
rescue BlogDataNotFound
STDERR.puts “File #{file_name} not found”
rescue BlogDataFormatError
STDERR.puts “Invalid blog data in #{file_name}”
rescue Exception => exc
STDERR.puts “General error loading #{file_name}: #{exc.message}”
end

rescue clauses can be directly placed on the outermost level of a method definition
without needing to enclose the contents in a begin/end block.

class Greeter
attr_accessor :name # create reader and writer methods
attr_reader :greeting # create reader only
attr_writer :age # create writer only

class MyClass
def m1 # this method is public
end
protected
def m2 # this method is protected
end
private
def m3 # this method is private
end
end

module StoreHelper
def capitalize_words(string)
string.split(‘ ‘ ).map {|word| word.capitalize}.join(‘ ‘ )
end
end

 

class CreateProducts < ActiveRecord::Migration
def self.up
create_table :products do |t|
t.string :title
t.text :description
t.string :image_url
t.decimal :price, :precision => 8, :scale => 2
t.timestamps
end
end
def self.down
drop_table :products
end
end

 

ruby rail commands notes(1) Installing Rails

Class examples:

class Project < ActiveRecord::Base
belongs_to :portfolio
has_one :project_manager
has_many :milestones
has_many :deliverables, :through => :milestones
validates :name, :description, :presence => true
validates :non_disclosure_agreement, :acceptance => true
validates :short_name, :uniqueness => true
end

Installing Rails

rubyGem update:

gem update –system
gem uninstall rubygems-update

Sqlite3

Copy the files inside these zips to your C:\Ruby\bin directory. The results
should look something like this:
Directory of C:\Ruby\bin
01/05/2010 06:30 PM 3,744 sqlite3.def
01/05/2010 06:30 PM 511,383 sqlite3.dll
01/05/2010 06:31 PM 530,762 sqlite3.exe
3 File(s) 1,045,889 bytes
Now install the ruby bindings to SQLite3, and the Rails beta itself:
gem install sqlite3-ruby
gem install rails

 

Testsqlite.rb

require ‘rubygems’
require ‘sqlite3′
tempname = “test.sqlite#{3+rand}”
db = SQLite3::Database.new(tempname)
puts db.execute(‘select sqlite_version()’ )
db.close
File.unlink(tempname)

Installing on Mac OS X

sudo port upgrade sqlite3
Next, users of OS X prior to Snow Leopard will need to upgrade their version
of Ruby to 1.8.7. Again, this can be done with MacPorts:
sudo port install ruby

sudo gem update –system
sudo gem uninstall rubygems-update
sudo gem install rails –pre
sudo gem install sqlite3-ruby

Installing on Linux

sudo aptitude install build-essential libopenssl-ruby libfcgi-dev
sudo aptitude install ruby irb rubygems ruby1.8-dev
sudo aptitude install sqlite3 libsqlite3-dev

• Using the gem update system:
sudo gem update –system
• Using the gem designed to update troublesome systems:
sudo gem install rubygems-update
sudo update_rubygems
• Using setup.rb, which is provided with rubygems-update:
sudo gem install rubygems-update
cd /var/lib/gems/1.8/gems/rubygems-update-*
sudo ruby setup.rb
• Finally, installing from source:
wget http://rubyforge.org/frs/download.php/69365/rubygems-1.3.6.tgz
tar xzf rubygems-1.3.6.tgz
cd rubygems-1.3.6
sudo ruby setup.rb

sudo gem install rails –pre
sudo gem install sqlite3-ruby

export PATH=/var/lib/gems/1.8/bin:$PATH

 

gem list –local rails

 

Ruby on Rails: UUID as your ActiveRecord primary key

Sometimes, using the good old ‘auto increment’ from your database just isn’t good enough. If you really require that all your objects have unique ID, even across systems and different databases there’s only one way go: UUID or Universally Unique IDentifier.

A UUID is generated in such a way that every generated UUID in the world is unique. For example: 12f186e6-687e-11ad-843e-001b632783f1. This string is randomly generated based on several factors that guarantee it’s uniqueness.

Anyway, you want to replace the default integer-based primary keys in your model with a UUID. This is quite easy, but there are some caveats.

First off, you should have a column in your database table that holds the UUID. You may be tempted to just change the column definition for id from integer to string and be done with it. But this won’t work as expected. For your development, and maybe even your production system, this may work fine, but you might be in for some unexpected surprises.

The best example of such a surprise is RSpec. RSpec uses ‘rake db:schema:dump’ to create a sql dump to quickly load the database with. However, the ‘schema:dump’ does not look at the id column in your database, but instead adds the default primary key definition from the ActiveRecord adapter.

The solution is to disable the id column and create a primary key column named uuid instead.

create_table :posts, :id => false do |t|
t.string :uuid, :limit => 36, :primary => true
end

In your Post model you should then set the name of this new primary key column.

class Post

The next step is to create the UUID itself. We’ll have to do this the Rails app, because most databases don’t support UUID out of the box.

First install the uuidtools gem

sudo gem install uuidtools

Create a file like lib/uuid_helper.rb and add the following content.

require ‘rubygems’
require ‘uuidtools’

module UUIDHelper
def before_create()
self.uuid = UUID.timestamp_create().to_s
end
end

Then, include this module in all UUID-enabled models, like Post in this example.

class Post

Now, when you save a new Post object, the uuid field is automatically filled with a Universally Unique Identifier. What else could you wish for?

Tagged with General

ruby_学习笔记:字符串处理函数

http://www.51testing.com/?uid-46209-action-viewspace-itemid-80645

最最常用的字符串处理函数

1.返回字符串的长度
str.length => integer

2.判断字符串中是否包含另一个串
str.include? other_str => true or false

“hello”.include? “lo” #=> true
“hello”.include? “ol” #=> false
“hello”.include? ?h #=> true

3.字符串插入:
str.insert(index, other_str) => str

“abcd”.insert(0, ‘X’) #=> “Xabcd”
“abcd”.insert(3, ‘X’) #=> “abcXd”
“abcd”.insert(4, ‘X’) #=> “abcdX”
“abcd”.insert(-3, ‘X’) #=> “abXcd”
“abcd”.insert(-1, ‘X’) #=> “abcdX”

4.字符串分隔,默认分隔符为空格
str.split(pattern=$;, [limit]) => anArray

” now’s the time”.split #=> ["now's", "the", "time"]
“1, 2.34,56, 7″.split(%r{,\s*}) #=> ["1", "2.34", "56", "7"]
“hello”.split(//) #=> ["h", "e", "l", "l", "o"]
“hello”.split(//, 3) #=> ["h", "e", "llo"]
“hi mom”.split(%r{\s*}) #=> ["h", "i", "m", "o", "m"]

“mellow yellow”.split(“ello”) #=> ["m", "w y", "w"]
“1,2,,3,4,,”.split(‘,’) #=> ["1", "2", "", "3", "4"]
“1,2,,3,4,,”.split(‘,’, 4) #=> ["1", "2", "", "3,4,,"]

5.字符串替换
str.gsub(pattern, replacement) => new_str
str.gsub(pattern) {|match| block } => new_str

“hello”.gsub(/[aeiou]/, ‘*’) #=> “h*ll*” #将元音替换成*号
“hello”.gsub(/([aeiou])/, ‘<\1>‘) #=> “hll” #将元音加上尖括号,\1表示保留原有字符???
“hello”.gsub(/./) {|s| s[0].to_s + ‘ ‘} #=> “104 101 108 108 111 ”

字符串替换二:
str.replace(other_str) => str
s = “hello” #=> “hello”
s.replace “world” #=> “world”

6.字符串删除:

str.delete([other_str]+) => new_str
“hello”.delete “l”,”lo” #=> “heo”
“hello”.delete “lo” #=> “he”
“hello”.delete “aeiou”, “^e” #=> “hell”
“hello”.delete “ej-m” #=> “ho”

7.去掉前和后的空格
str.lstrip => new_str

” hello “.lstrip #=> “hello ”
“hello”.lstrip #=> “hello”

8.字符串匹配
str.match(pattern) => matchdata or nil

9.字符串反转
str.reverse => new_str

“stressed”.reverse #=> “desserts”

10.去掉重复的字符
str.squeeze([other_str]*) => new_str
“yellow moon”.squeeze #=> “yelow mon” #默认去掉串中所有重复的字符
” now is the”.squeeze(” “) #=> ” now is the” #去掉串中重复的空格
“putters shoot balls”.squeeze(“m-z”) #=> “puters shot balls” #去掉指定范围内的重复字符

11.转化成数字
str.to_i=> str
“12345″.to_i #=> 12345

chomp和chop的区别:
chomp:去掉字符串末尾的\n或\r
chop:去掉字符串末尾的最后一个字符,不管是\n\r还是普通字符

“hello”.chomp #=> “hello”
“hello\n”.chomp #=> “hello”
“hello\r\n”.chomp #=> “hello”
“hello\n\r”.chomp #=> “hello\n”
“hello\r”.chomp #=> “hello”
“hello”.chomp(“llo”) #=> “he”

“string\r\n”.chop #=> “string”
“string\n\r”.chop #=> “string\n”
“string\n”.chop #=> “string”
“string”.chop #=> “strin”
“x”.chop.chop #=> “”

YahooFinance – Ruby Module

http://www.transparentech.com/opensource/yahoofinance

YahooFinance – Ruby Module

YahooFinance is a Ruby programming language module for retrieving stock quote information from the finance.yahoo.com web site. It can retrieve current stock quote data or historical quote data.

This module can be “required” and used as a library. Or it can be run from the command-line as a script.
Programatic Usage

The following is example code using the YahooFinance Ruby module to retrieve the most recent stock quote data.

require ‘yahoofinance’

# Set the type of quote we want to retrieve.
# Available type are:
# – YahooFinanace::StandardQuote
# – YahooFinanace::ExtendedQuote
# – YahooFinanace::RealTimeQuote
quote_type = YahooFinance::StandardQuote

# Set the symbols for which we want to retrieve quotes.
# You can include more than one symbol by separating
# them with a ‘,’ (comma).
quote_symbols = “yhoo,goog”

# Get the quotes from Yahoo! Finance. The get_quotes method call
# returns a Hash containing one quote object of type “quote_type” for
# each symbol in “quote_symbols”. If a block is given, it will be
# called with the quote object (as in the example below).
YahooFinance::get_quotes( quote_type, quote_symbols ) do |qt|
puts “QUOTING: #{qt.symbol}”
puts qt.to_s
end

# You can get the same effect using the quote specific method.
quotes = YahooFinance::get_standard_quotes( quote_symbols )
quotes.each do |symbol, qt|
puts “QUOTING: #{symbol}”
puts qt.to_s
end

The following is an example of using the YahooFinance Ruby module to download historical quote data.

require ‘yahoofinance’

# You can get the historical quote data in 2 formats:
# 1. As an array of raw data.
# 2. As a YahooFinance::HistoricalQuote object.

# Getting the historical quote data as a raw array.
# The elements of the array are:
# [0] – Date
# [1] – Open
# [2] – High
# [3] – Low
# [4] – Close
# [5] – Volume
# [6] – Adjusted Close

# The following example will download 30 days worth of qutoes.
# See the note below on the meaning of the number of days.
YahooFinance::get_historical_quotes_days( ‘YHOO’, 30 ) do |row|
puts “YHOO,#{row.join(‘,’)}”
end
# The API also supportes retrieving quotes based on specific dates.
YahooFinance::get_historical_quotes( ‘YHOO’,
Date.parse( ’2005-09-09′ ),
Date.today() ) do |row|
puts “YHOO,#{row.join(‘,’)}”
end

# Getting the data as YahooFinance::HistoricalQuote objects using the
# days API.
YahooFinance::get_HistoricalQuotes_days( ‘YHOO’, 30 ) do |hq|
puts “#{hq.symbol},#{hq.date},#{hq.open},#{hq.high},#{hq.low},”
+ “#{hq.close},#{hq.volume},#{hq.adjClose}”
end
# Getting the data as YahooFinance::HistoricalQuote objects based on
# specific dates.
YahooFinance::get_HistoricalQuotes( ‘YHOO’,
Date.parse( ’2005-09-09′ ),
Date.today() ) do |hq|
puts “#{hq.symbol},#{hq.date},#{hq.open},#{hq.high},#{hq.low},”
+ “#{hq.close},#{hq.volume},#{hq.adjClose}”
end

Command-Line Usage

The module includes a simple command-line interface.

% yahoofinance.rb -h
Usage: yahoofinance.rb [options]

-s Retrieve standard quotes (default).
-x Retrieve extended quotes.
-r Retrieve real-time quotes.
-z Retrieve historical quotes.
-d, –days N Number of days of historical
quotes to retrieve. Default is 90.
-h, –help Show this message

% yahoofinance.rb -x yhoo
Retrieving quotes for: yhoo
QUOTING: YHOO
YahooFinance::ExtendedQuote
movingAve50daysChangePercentFrom = -10.64%
weeks52ChangeFromLow = 2.23
annualizedGain = -
pricePaid = -
weeks52ChangePercentFromLow = +8.95%
weeks52Range = 24.91 – 43.66
stockExchange = NasdaqNM
holdingsGain = -
tradeDate = -
pegRatio = 2.12
dividendYield = N/A
name = YAHOO INC
dayValueChange = – - -1.20%
pricePerEPSEstimateCurrentYear = 56.06
oneYearTargetPrice = 38.30
dividendPerShare = 0.00
shortRatio = 6.00
holdingsValue = -
commission = -
pricePerSales = 6.48
pricePerEPSEstimateNextYear = 41.00
earningsPerShare = 0.848
notes = -
highLimit = -
movingAve50days = 30.372
pricePerBook = 4.47
exDividendDate = 12-May-04
lowLimit = -
movingAve200days = 31.911
bookValue = 6.149
epsEstimateCurrentYear = 0.49
marketCap = 38.235B
peRatio = 32.39
sharesOwned = -
movingAve200daysChangeFrom = -4.771
epsEstimateNextYear = 0.67
symbol = YHOO
movingAve200daysChangePercentFrom = -14.95%
epsEstimateNextQuarter = 0.16
dividendPayDate = N/A
weeks52ChangeFromHigh = -16.52
holdingsGainPercent = – - -
movingAve50daysChangeFrom = -3.232
ebitda = 1.849B
weeks52ChangePercentFromHigh = -37.84%

% yahoofinance.rb -z -d 10 yhoo
Retrieving quotes for: yhoo
yhoo,31-Jul-06,27.46,27.55,26.99,27.14,16492600,27.14
yhoo,28-Jul-06,26.90,27.50,26.33,27.47,21584800,27.47
yhoo,27-Jul-06,27.35,27.50,26.64,26.70,25153000,26.70
yhoo,26-Jul-06,26.78,27.51,26.57,27.08,20073800,27.08
yhoo,25-Jul-06,26.75,27.19,26.57,26.95,21382900,26.95
yhoo,24-Jul-06,26.24,27.23,25.89,26.94,42631300,26.94

Note On Historical Quote Retrieval

Requests for historical quotes of stocks on some ‘international’ exchanges are limited by Yahoo! Finance to 200 data points per request. In order to retrieve all of the data points in one method call, the YahooFinance Ruby module will internally make multiple requests if the 200 data point limit is detected. Thus, users of the YahooFinance Ruby module need not be concerned with this limitation.
The API for historical quotes supports selecting the quotes based on dates or a number of days. When using the number of days, it is important to understand that the number of days given does not correspond to actual business days. It corresponds to calendar days and thus the number of data points returned will almost always be less than the number of days requested.
When speed is an issue, using the raw array API is recommended.

Download

Current Version

yahoofinance-1.2.2.gem
yahoofinance-1.2.2.tar.gz

YahooFinance RubyForge Page
Installation Instructions

RubyGem Installation

# gem install yahoofinance

or

# gem install yahoofinance-.gem

Tarball Installation

% tar xvzf yahoofinance-.tar.gz
% cd yahoofinance-
% ruby setup.rb

You may also be interested in the on-line documentation for setup.rb .
Credits/Complaints/Suggestions/Bugs

nickrahn at users.sourceforge.net

License

The YahooFinance Ruby module is released under the GNU General Public License (GPL).