RSS
 

Archive for the ‘Ruby’ Category

how to install mysql2 gem on windows/mingw32

07 Apr

download MySQL connector from http://dev.mysql.com/downloads/connector/c, choose the non-vs2005 zip archive, extract the folder into your local box, i.e. c:\mysql-connector-c-noinstall-6.0.2-win32

copy c:\mysql-connector-c-noinstall-6.0.2-win32\lib\libmysql.dll to c:\ruby187\bin(your ruby bin directory)

gem i mysql2 — –with-mysql-dir=c:\mysql-connector-c-noinstall-6.0.2-win32

 
No Comments

Posted in Ruby

 

Chinese ID card validation

15 Dec
def card(c)
w = %w{7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2}.map(&:to_i)
y = %w{1 0 X 9 8 7 6 5 4 3 2}
i = -1
s = c[0,17].split('').map(&:to_i).inject(0){|s,a| i += 1; s + a * w[i]}
c[0,17] + y[s % 11]
end
 
No Comments

Posted in Ruby

 

install ruby 1.9.2

06 Nov

1. download ftp://ftp.ruby-lang.org//pub/ruby/1.9/ruby-1.9.2-p0.tar.gz from http://www.ruby-lang.org/en/downloads/

tar xzvf ruby-1.9.2-p0.tar.gz

cd ruby-1.9.2-p0

./configure

make && make install

2. install extensions if not found

- install zlib:

apt-get install zlib1g zlib1g-dev

cd ext/zlib; ruby extconf.rb; make install

- install readline:

apt-get install libreadline

cd ext/readline; ruby extconf.rb; make install

3. install mysql2 gem:

apt-get install libmysqlclient-dev

gem i mysql2

 
No Comments

Posted in Debian, Ruby

 

6 Ways to Run Shell Commands in Ruby

10 Dec

Often times we want to interact with the operating system or run shell commands from within Ruby. Ruby provides a number of ways for us to perform this task.

Exec

Kernel#exec (or simply exec) replaces the current process by running the given command For example:


  $ irb
  >> exec 'echo "hello $HOSTNAME"'
  hello nate.local
  $

Notice how exec replaces the irb process is with the echo command which then exits. Because the Ruby effectively ends this method has only limited use. The major drawback is that you have no knowledge of the success or failure of the command from your Ruby script.

System

The system command operates similarly but the system command runs in a subshell instead of replacing the current process. system gives us a little more information than exec in that it returns true if the command ran successfully and false otherwise.


  $ irb             
  >> system 'echo "hello $HOSTNAME"'
  hello nate.local
  => true
  >> system 'false' 
  => false
  >> puts $?
  256
  => nil
  >> 

system sets the global variable $? to the exit status of the process. Notice that we have the exit status of the false command (which always exits with a non-zero code). Checking the exit code gives us the opportunity to raise an exception or retry our command.

Note for Newbies: Unix commands typically exit with a status of 0 on success and non-zero otherwise.

System is great if all we want to know is “Was my command successful or not?” However, often times we want to capture the output of the command and then use that value in our program.

Backticks (`)

Backticks (also called “backquotes”) runs the command in a subshell and returns the standard output from that command.


  $ irb
  >> today = `date`
  => "Mon Mar 12 18:15:35 PDT 2007\n" 
  >> $?
  => #<Process::Status: pid=25827,exited(0)>
  >> $?.to_i
  => 0

This is probably the most commonly used and widely known method to run commands in a subshell. As you can see, this is very useful in that it returns the output of the command and then we can use it like any other string.

Notice that $? is not simply an integer of the return status but actually a Process::Status object. We have not only the exit status but also the process id. Process::Status#to_i gives us the exit status as an integer (and #to_s gives us the exit status as a string).

One consequence of using backticks is that we only get the standard output (stdout) of this command but we do not get the standard error (stderr). In this example we run a Perl script which outputs a string to stderr.


  $ irb
  >> warning = `perl -e "warn 'dust in the wind'"`
  dust in the wind at -e line 1.
  => "" 
  >> puts warning

  => nil

Notice that the variable warning doesn’t get set! When we warn in Perl this is output on stderr which is not captured by backticks.

IO#popen

IO#popen is another way to run a command in a subprocess. popen gives you a bit more control in that the subprocess standard input and standard output are both connected to the IO object.


  $ irb
  >> IO.popen("date") { |f| puts f.gets }
  Mon Mar 12 18:58:56 PDT 2007
  => nil

While IO#popen is nice, I typically use Open3#popen3 when I need this level of granularity.

Open3#popen3

The Ruby standard library includes the class Open3. It’s easy to use and returns stdin, stdout and stderr. In this example, lets use the interactive command dc. dc is reverse-polish calculator that reads from stdin. In this example we will push two numbers and an operator onto the stack. Then we use p to print out the result of the operator operating on the two numbers. Below we push on 5, 10 and + and get a response of 15\n to stdout.


  $ irb
  >> stdin, stdout, stderr = Open3.popen3('dc') 
  => [#<IO:0x6e5474>, #<IO:0x6e5438>, #<IO:0x6e53d4>]
  >> stdin.puts(5)
  => nil
  >> stdin.puts(10)
  => nil
  >> stdin.puts("+")
  => nil
  >> stdin.puts("p")
  => nil
  >> stdout.gets
  => "15\n" 

Notice that with this command we not only read the output of the command but we also write to the stdin of the command. This allows us a great deal of flexibility in that we can interact with the command if needed.

popen3 will also give us the stderr if we need it.


  # (irb continued...)
  >> stdin.puts("asdfasdfasdfasdf")
  => nil
  >> stderr.gets
  => "dc: stack empty\n" 

However, there is a shortcoming with popen3 in ruby 1.8.5 in that it doesn’t return the proper exit status in $?.


  $ irb
  >> require "open3" 
  => true
  >> stdin, stdout, stderr = Open3.popen3('false')
  => [#<IO:0x6f39c0>, #<IO:0x6f3984>, #<IO:0x6f3920>]
  >> $?
  => #<Process::Status: pid=26285,exited(0)>
  >> $?.to_i
  => 0

0? false is supposed to return a non-zero exit status! It is this shortcoming that brings us to Open4.

Open4#popen4

Open4#popen4 is a Ruby Gem put together by Ara Howard. It operates similarly to open3 except that we can get the exit status from the program. popen4 returns a process id for the subshell and we can get the exit status from that waiting on that process. (You will need to do a gem instal open4 to use this.)


  $ irb
  >> require "open4" 
  => true
  >> pid, stdin, stdout, stderr = Open4::popen4 "false" 
  => [26327, #<IO:0x6dff24>, #<IO:0x6dfee8>, #<IO:0x6dfe84>]
  >> $?
  => nil
  >> pid
  => 26327
  >> ignored, status = Process::waitpid2 pid
  => [26327, #<Process::Status: pid=26327,exited(1)>]
  >> status.to_i
  => 256

A nice feature is that you can call popen4 as a block and it will automatically wait for the return status.


  $ irb
  >> require "open4" 
  => true
  >> status = Open4::popen4("false") do |pid, stdin, stdout, stderr|
  ?>            puts "PID #{pid}" 
  >>          end
  PID 26598
  => #<Process::Status: pid=26598,exited(1)>
  >> puts status
  256
  => nil
 
No Comments

Posted in Ruby

 

Added plural and singular functions to ruby String class

08 May
String.class_eval do

PLURALS = [['(quiz)$', '\1zes'],['(ox)$', '\1en'],['([m|l])ouse$', '\1ice'],['(matr|vert|ind)ix|ex$', '\1ices'],
['(x|ch|ss|sh)$', '\1es'],['([^aeiouy]|qu)ies$', '\1y'],['([^aeiouy]|q)y$$', '\1ies'],['(hive)$', '\1s'],
['(?:[^f]fe|([lr])f)$', '\1\2ves'],['(sis)$', 'ses'],['([ti])um$', '\1a'],['(buffal|tomat)o$', '\1oes'],['(bu)s$', '\1es'],
['(alias|status)$', '\1es'],['(octop|vir)us$', '\1i'],['(ax|test)is$', '\1es'],['s$', 's'],['$', 's']]
SINGULARS =[['(quiz)zes$', '\1'],['(matr)ices$', '\1ix'],['(vert|ind)ices$', '\1ex'],['^(ox)en$', '\1'],['(alias|status)es$', '\1'],
['(octop|vir)i$', '\1us'],['(cris|ax|test)es$', '\1is'],['(shoe)s$', '\1'],['[o]es$', '\1'],['[bus]es$', '\1'],['([m|l])ice$', '\1ouse'],
['(x|ch|ss|sh)es$', '\1'],['(m)ovies$', '\1ovie'],['[s]eries$', '\1eries'],['([^aeiouy]|qu)ies$', '\1y'],['[lr]ves$', '\1f'],
['(tive)s$', '\1'],['(hive]s$', '\1'],['([^f]]ves$', '\1fe'],['(^analy)ses$', '\1sis'],
['([a]naly|[b]a|[d]iagno|[p]arenthe|[p]rogno|[s]ynop|[t]he)ses$', '\1\2sis'],['([ti])a$', '\1um'],['(news)$', '\1ews']]

def singular()
  SINGULARS.each { |match_exp, replacement_exp| return gsub(Regexp.compile(match_exp), replacement_exp) unless match(Regexp.compile(match_exp)).nil?}
end

def plural()
  PLURALS.each { |match_exp, replacement_exp| return gsub(Regexp.compile(match_exp), replacement_exp) unless match(Regexp.compile(match_exp)).nil? }
end

def plural?
  PLURALS.each {|match_exp, replacement_exp| return true if match(Regexp.compile(match_exp))}
  false
end

end
 
1 Comment

Posted in Ruby

 

Format Date time

08 May

Formats time according to the directives in the given format string. Any text not listed as a directive will be passed through to the output string.
Format meaning:

  %a – The abbreviated weekday name (“Sun”)
  %A – The  full  weekday  name (“Sunday”)
  %b – The abbreviated month name (“Jan”)
  %B – The  full  month  name (“January”)
  %c – The preferred local date and time representation
  %d – Day of the month (01..31)
  %H – Hour of the day, 24-hour clock (00..23)
  %I – Hour of the day, 12-hour clock (01..12)
  %j – Day of the year (001..366)
  %m – Month of the year (01..12)
  %M – Minute of the hour (00..59)
  %p – Meridian indicator (“AM”  or  “PM”)
  %S – Second of the minute (00..60)
  %U – Week  number  of the current year,
          starting with the first Sunday as the first
          day of the first week (00..53)
  %W – Week  number  of the current year,
          starting with the first Monday as the first
          day of the first week (00..53)
  %w – Day of the week (Sunday is 0, 0..6)
  %x – Preferred representation for the date alone, no time
  %X – Preferred representation for the time alone, no date
  %y – Year without a century (00..99)
  %Y – Year with century
  %Z – Time zone name
  %% – Literal “%” character

   t = Time.now
   t.strftime(“Printed on %m/%d/%Y”)   #=> “Printed on 04/09/2003″
   t.strftime(“at %I:%M%p”)            #=> “at 08:56AM”

 
1 Comment

Posted in Ruby

 

Creating Your Own Rails API Documentation

08 May

You can create your own local version of the consolidated Rails API documentation. Just type the following commands at a command prompt (remembering to start the command window in your Rails environment if you’re using InstantRails or Locomotive).
rails_apps> rails dummy_app
rails_apps> cd dummy_app
dummy_app> rake rails:freeze:gems
dummy_app> echo >vendor/rails/activesupport/README
dummy_app> rake doc:rails
The last step takes a while. When it finishes, you’ll have the Rails API documentation in a directory tree starting at doc/api. I suggest moving this folder to your desktop, then deleting the dummy_app tree.

 
No Comments

Posted in Ruby

 

RDoc Documentation

08 May

RDoc is a documentation system for Ruby source code. Just like JavaDoc, RDoc takes a bunch of source files and generates HTML documentation, using syntactic information from the source and text in comment blocks. Unlike JavaDoc, RDoc can produce fairly good content even if the source contains no comments. It’s fairly painless to write RDoc documentation as you write the source for your applications. RDoc is described in Chapter 16 of the PickAxe. RDoc is used to document Ruby’s built-in and standard libraries. Depending on how your Ruby was installed, you might be able to use the ri command to access the documentation.
dave> ri String.capitalize
———————————————– String#capitalize
str.capitalize => new_str
—————————————————————–
Returns a copy of str with the first character converted to uppercase and the remainder to lowercase.
“hello”.capitalize #=> “Hello”
“HELLO”.capitalize #=> “Hello”
“123ABC”.capitalize #=> “123abc”
If you used RubyGems to install Rails, you can access the Rails API documentation by running gem_server and then pointing your browser at the URL http://localhost:8808. The rake doc:app task creates the HTML documentation for a Rails project, leaving it in the doc/app directory.

 
No Comments

Posted in Ruby