2012-09-20

reading notes of Programming Ruby 2nd





a.rb
#!/usr/bin/ruby -w
# -*- coding: utf-8 -*-
animals = %w{ant bee cat dog elk}
def say_hello (name)
  "Hello, #{name.capitalize}"
end

puts say_hello('ww')

$globalV = "hello"
@instanceV = "instanceV"
@@classV = "ww"
puts "#$globalV, #@instanceV #@@classV"



hash_example = {
  'a' => 'A',
  'b' => 'B',
  'c' => 'C'
}
puts hash_example['c']

hash_default_value_zero = Hash.new(0)
puts hash_default_value_zero['key-do-not-exists'] == 0

testflag = true
puts "use simple if statement, if possible" if testflag

puts "regex demo: if perl match /perl|python/" if "perl" =~ /perl|python/

aline = 'Perl and Python'
aline.sub(/Perl/, 'Ruby') # replace first 'Perl' with 'Ruby' 
aline.gsub(/Python/, 'Ruby') # replace every 'Python' with 'Ruby'
aline.gsub(/Perl|Python/, 'Ruby')

animals.each { |animal| puts animal }
5.times { print "*" }
3.upto(6) {|i| print i }
('a'..'e').each {|char| print char }

class Song
  attr_reader :name, :artist, :duration, :attr_foo
  attr_writer :name, :artist, :duration
  protected :attr_foo

  def initialize(name, artist, duration)
    @name = name
    @artist = artist
    @duration = duration
  end
  
  def to_s
    "Song: #@name, #@artist, #@duration "
  end
end

class SubSong < Song
  CONSTANTS_START_WITH_UPPERCASE_LETTER = 300
  def initialize(name, artist, duration, lyrics)
    super(name, artist, duration)
    @lyrics = lyrics
  end  

  def SubSong.staticMethod
    "static method"
  end

  def [] (seconds)  #index method, e.g: SubSong[22]
    seconds
  end

  def play
  end

  def pause
  end

  def inspect
    '#' * 10
  end
end

s = SubSong.new("a", "b", "c", "lyrics")
puts
puts s.duration
puts s.name
puts SubSong.staticMethod

class SingletonLogger
  private_class_method :new
  @@logger = nil
  def SingletonLogger.get_instance
    @@logger = new unless @@logger
    @@logger
  end

  def self.static_method_form_b
  end
  
  class << self
    def static_method_form_c
    end
  end

  def public_method_a
  end
  public :public_method_a

  protected
    def protected_method_a
    end
  private
    def private_method_a
    end
end

i = SingletonLogger.get_instance
puts i.object_id == SingletonLogger.get_instance.object_id
puts i.class
j = i.dup   #duplicate a new object
puts j.class
j.freeze    #freeze an object

array = Array.new
array[0] = "xxx"
array[1] = "yyy"
array[2] = "zzz"
puts array[0,2]
puts array[100] == nil

#a=[1,3,5,7,9]    → [1,3,5,7,9]                        
#a[2, 2] = ’cat’   → [1, 3, "cat", 9]                   
#a[2, 0] = ’dog’   → [1, 3, "dog", "cat", 9]            
#a[1,1]=[9,8,7]   → [1,9,8,7,"dog","cat",9]            
#a[0..3] = []     → ["dog", "cat", 9]                  
#a[5..6] = 99, 98 → ["dog", "cat", 9, nil, nil, 99, 98]



require 'test/unit'
class TestSong < Test::Unit::TestCase
  def test_method
    h = { 'a' => 'A', 'b' => 'B', 'c' => 'C'}
    assert_equal(h['c'], 'C')
  end
end


def two_times
  yield
  yield
end

two_times { puts "Hello"}

a = [1, 'cat', 3.14]   #array with three elements
a[2] = nil
puts a.find {|element| element == 1}
puts [1,3,5,7,9].find{|v|v*v>30}
puts [1,3,5,7,9].each {|i| puts i}
puts ['S', 'V'].collect {|x| x.succ}
puts defined?(not_defined_variable) == nil

puts [1,2,3,4].inject {|p, e| p*e}

class File
  def File.with_file_open(*args)
    result = f = File.open(*args)
    if block_given?
      result = yield f
      f.close
    end
    f
  end
end

song = SubSong.new("a", "b", "c", "d")
p s
class SongButton
  def initialize(label, &action)
    @label = label
    @action = action
  end

  def button_pressed
    @action.call(self)
  end
end

start_button = SongButton.new("Start") { song.start }

def n_times(thing)
  return lambda { |n| thing *n }
end

proc_3_times = n_times("hello")
puts proc_3_times.call(3)

num = 81
5.times do 
  puts "#{num.class}: #{num}"
  num *= num
end

99.downto(96) { |i| print i, " " }
50.step(80,5) { |i| print i, " " }

puts "#{'hello ' * 3}"
puts "now is #{
def the(a)
  'the ' + a
end
the('time')
} for all.."

p (1..10).to_a
p ('bar'..'bat').to_a

digits = 0..9
puts digits.include?(5)

puts 1 <=> 2
puts 1 <=> 1

puts (1..10) === 5
puts (1..10) === 12

#102 More about methods
#method name instance_of? chop chop! name=

def method_without_parameters_do_not_need_parenthesis
puts ' '
end

def method_parameter_can_have_default_value(input="hello")
puts input
end
method_parameter_can_have_default_value

def varargs(arg1, *rest)
  "Got #{arg1} and #{rest.join(', ')}"
end

puts varargs("first variable", "and", "more", "params")

#if block_given?

#if omit the receiver, it defaults to self.
#self.frozen?  is same as frozen?
#self.id       is same as id

#Modules
module Module_Can_do_mixin
  PI = 3.14
  def morsecode
  end
end

module Debug
  def who_am_i
    "#{self.class.name}"
  end
end

class Photo
  include Debug
end

require 'open-uri'
open('http://www.sina.com.cn') do |f|
  puts f.read.scan(/<img src="(.*?)"/m).uniq
end

#Threads and Processes
#P377 to be continue...

2012-09-19

copy to end of line from current point

As an Emacs user, maybe you already known CopyWithoutSelection

But currently without copy to line end from current point.
Following is the my implementation, and bind to the shortcut "C-c e"




init.el

(defun copy-to-line-end (&optional arg)
  "Save point to current line end into Kill-Ring without mark (or kill and yank)"
  (interactive "P")
  (let ((start (point)))
    (save-excursion
      (end-of-line)
      (copy-region-as-kill start (point))
      )
    )
)
(global-set-key (kbd "C-c e") 'copy-to-line-end)


2012-09-03

Using Jenkins' Script Console to Download Files


jenkins.org

* Using Jenkins Script Console to Download Files
Scenario::
ServerA has a file test.t want to copy to ServerB, But don't have login user on ServerB.

And ServerB running a Jenkins server, we can access.

Solutions::
On ServerA:
    1. goto folder of test.t
    2. execute python -m SimpleHTTPServer
       19:41 ~ $ python -m SimpleHTTPServer
       Serving HTTP on 0.0.0.0 port 8000 ...

On Jenkins::
    1. execute following code in Jenkins's Script Console.
    
String cmd ="curl <ip_of_server_A>:8000/test.t -o test.t";
Runtime run = Runtime.getRuntime();
Process pr = run.exec(cmd);
pr.waitFor();
BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line = "";
while ((line=buf.readLine())!=null) {
        println line;
}
Then, test.t will located in Home folder of user who running the Jenkins.

   2. Surely,  any Groovy Script can execute here.