Ruby Jewellery [Updating...]
This article will include many usefull examples. Let's enjoy Ruby!

Here is am example shows how to write HTTP client with Ruby.


































Send email with Ruby:
1 require 'net/smtp'
2 SMTP_HOST = "192.168.60.99"
3
4 def send(from, to, subject, msg)
5 mail = "To: #{to}\r\n" +
6 "From: #{from}\r\n" +
7 "Subject: #{subject}\r\n" +
8 "\r\n" +
9 msg
10
11 Net::SMTP.start(SMTP_HOST) do |smtp|
12 smtp.send_mail(mail, from, to)
13 end
14 end
15
16 from = "blake@192.168.60.99"
17 to = ["blake@192.168.60.99"]
18 send(from, to, "test", "Just a test!\ntest")
2 SMTP_HOST = "192.168.60.99"
3
4 def send(from, to, subject, msg)
5 mail = "To: #{to}\r\n" +
6 "From: #{from}\r\n" +
7 "Subject: #{subject}\r\n" +
8 "\r\n" +
9 msg
10
11 Net::SMTP.start(SMTP_HOST) do |smtp|
12 smtp.send_mail(mail, from, to)
13 end
14 end
15
16 from = "blake@192.168.60.99"
17 to = ["blake@192.168.60.99"]
18 send(from, to, "test", "Just a test!\ntest")
Notice:
1. 'mail' is the email body, it use "\r\n" to separate the mail header and mail context. So if you only want to send context without header, you should write: "mail = "\r\n" + msg". Otherwise your email will lost the context.

This is one small tools to get the total file line number of on folder.
1
POST_FIX = %w{java jsp html xml properties}
2
EXCLUDE_DIR = %w{CVS}
3
$displayStr = ""
4
$fileReg = ""
5
$dirReg = "\\.|\\.\\.|"
6
7
def sumLine(fileName)
8
file = open fileName
9
begin
10
while file.gets()
11
end
12
ensure
13
file.close
14
end
15
$.
16
end
17
18
def iteDir(name, level=0)
19
lines = 0
20
dir = Dir.open name
21
rex = /\. + "java" +$|\.jsp$|\.html$/
22
begin
23
dir.each do |fileName|
24
fileName = dir.path + '/' + fileName
25
if File.ftype(fileName) =~ /directory/
26
if not fileName =~ Regexp.new($dirReg)
27
lines += iteDir(fileName, level+1)
28
else
29
next
30
end
31
elsif fileName =~ Regexp.new($fileReg)
32
lines += sumLine(fileName)
33
end
34
end
35
ensure
36
dir.close
37
end
38
str = ""
39
for i in 0..(level-1)
40
str += "\t|"
41
end
42
if level != 0
43
str += "---"
44
end
45
$displayStr = "#{str}#{name}\t#{lines} lines\n#{$displayStr}"
46
lines
47
end
48
49
POST_FIX.each do |postfix|
50
$fileReg += "\.#{postfix}$|"
51
end
52
$fileReg = $fileReg.chop
53
54
EXCLUDE_DIR.each do |excludeDir|
55
$dirReg += "^#{excludeDir}$|"
56
end
57
$dirReg = $dirReg.chop
58
59
print "Total #{iteDir("E:/_MyWorkSpace/IDEA_Proj")} lines\n"
60
print $displayStr

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

Keystone:
1. Ruby I/O access. Dir and File
2. Regexp & String -> Regexp
3. Some kinds of variables
4. Array operation
Technorati Tags: Ruby
posted on 2005-06-02 16:37 Blake HAN 閱讀(276) 評(píng)論(0) 編輯 收藏 所屬分類: ROR