Ruby – Discussion

Discuss Ruby ”; Previous Next Ruby is a scripting language designed by Yukihiro Matsumoto, also known as Matz. It runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX. This tutorial gives a complete understanding on Ruby. Print Page Previous Next Advertisements ”;

Ruby – Built-in Functions

Ruby – Built-in Functions ”; Previous Next Since the Kernel module is included by Object class, its methods are available everywhere in the Ruby program. They can be called without a receiver (functional form). Therefore, they are often called functions. A complete list of Built-in Functions is given here for your reference − Sr.No. Methods & Description 1 abort Terminates program. If an exception is raised (i.e., $! isn”t nil), its error message is displayed. 2 Array( obj) Returns obj after converting it to an array using to_ary or to_a. 3 at_exit {…} Registers a block for execution when the program exits. Similar to END statement, but END statement registers the block only once. 4 autoload( classname, file) Registers a class classname to be loaded from file the first time it”s used. classname may be a string or a symbol. 5 binding Returns the current variable and method bindings. The Binding object that is returned may be passed to the eval method as its second argument. 6 block_given? Returns true if the method was called with a block. 7 callcc {| c|…} Passes a Continuation object c to the block and executes the block. callcc can be used for global exit or loop construct. 8 caller([ n]) Returns the current execution stack in an array of the strings in the form file:line. If n is specified, returns stack entries from nth level on down. 9 catch( tag) {…} Catches a nonlocal exit by a throw called during the execution of its block. 10 chomp([ rs = $/]) Returns the value of variable $_ with the ending newline removed, assigning the result back to $_. The value of the newline string can be specified with rs. 11 chomp!([ rs = $/]) Removes newline from $_, modifying the string in place. 12 chop Returns the value of $_ with its last character (one byte) removed, assigning the result back to $_. 13 chop! Removes the last character from $_, modifying the string in place. 14 eval( str[, scope[, file, line]]) Executes str as Ruby code. The binding in which to perform the evaluation may be specified with scope. The filename and line number of the code to be compiled may be specified using file and line. 15 exec( cmd[, arg…]) Replaces the current process by running the command cmd. If multiple arguments are specified, the command is executed with no shell expansion. 16 exit([ result = 0]) Exits program, with result as the status code returned. 17 exit!([ result = 0]) Kills the program bypassing exit handling such as ensure, etc. 18 fail(…) See raise(…) 19 Float( obj) Returns obj after converting it to a float. Numeric objects are converted directly; nil is converted to 0.0; strings are converted considering 0x, 0b radix prefix. The rest are converted using obj.to_f. 20 fork fork {…} Creates a child process. nil is returned in the child process and the child process” ID (integer) is returned in the parent process. If a block is specified, it”s run in the child process. 21 format( fmt[, arg…]) See sprintf. 22 gets([ rs = $/]) Reads the filename specified in the command line or one line from standard input. The record separator string can be specified explicitly with rs. 23 global_variables Returns an array of global variable names. 24 gsub( x, y) gsub( x) {…} Replaces all strings matching x in $_ with y. If a block is specified, matched strings are replaced with the result of the block. The modified result is assigned to $_. 25 gsub!( x, y) gsub!( x) {…} Performs the same substitution as gsub, except the string is changed in place. 26 Integer( obj) Returns obj after converting it to an integer. Numeric objects are converted directly; nil is converted to 0; strings are converted considering 0x, 0b radix prefix. The rest are converted using obj.to_i. 27 lambda {| x|…} proc {| x|…} lambda proc Converts a block into a Proc object. If no block is specified, the block associated with the calling method is converted. 28 load( file[, private = false]) Loads a Ruby program from file. Unlike require, it doesn”t load extension libraries. If private is true, the program is loaded into an anonymous module, thus protecting the namespace of the calling program. 29 local_variables Returns an array of local variable names. 30 loop {…} Repeats a block of code. 31 open( path[, mode = “r”]) open( path[, mode = “r”]) {| f|…} Opens a file. If a block is specified, the block is executed with the opened stream passed as an argument. The file is closed automatically when the block exits. If path begins with a pipe |, the following string is run as a command, and the stream associated with that process is returned. 32 p( obj) Displays obj using its inspect method (often used for debugging). 33 print([ arg…]) Prints arg to $defout. If no arguments are specified, the value of $_ is printed. 34 printf( fmt[, arg…]) Formats arg according to fmt using sprintf and prints the result to $defout. For formatting specifications, see sprintf for detail. 35 proc {| x|…} proc See lamda. 36 putc( c) Prints one character to the default output ($defout). 37 puts([ str]) Prints string to the default output ($defout). If the string doesn”t end with a newline, a newline is appended to the string. 38 raise(…) fail(…) Raises an exception. Assumes RuntimeError if no exception class is specified. Calling raise without arguments in a rescue clause re-raises the exception. Doing so outside a rescue clause raises a message-less RuntimeError. fail is an obsolete name for raise. 39 rand([ max = 0]) Generates a pseudo-random number greater than or equal to 0 and less than max. If max is either not specified or is set to 0, a random number is returned as a floating-point number greater than or equal to 0 and less than 1. srand may be used to initialize pseudo-random stream. 40 readline([ rs =

Ruby – Ruby/XML, XSLT

Ruby – XML, XSLT and XPath Tutorial ”; Previous Next What is XML? The Extensible Markup Language (XML) is a markup language much like HTML or SGML. This is recommended by the World Wide Web Consortium and available as an open standard. XML is a portable, open source language that allows programmers to develop applications that can be read by other applications, regardless of operating system and/or developmental language. XML is extremely useful for keeping track of small to medium amounts of data without requiring a SQL-based backbone. XML Parser Architectures and APIs There are two different flavors available for XML parsers − SAX-like (Stream interfaces) − Here you register callbacks for events of interest and then let the parser proceed through the document. This is useful when your documents are large or you have memory limitations, it parses the file as it reads it from disk, and the entire file is never stored in memory. DOM-like (Object tree interfaces) − This is World Wide Web Consortium recommendation wherein the entire file is read into memory and stored in a hierarchical (tree-based) form to represent all the features of an XML document. SAX obviously can”t process information as fast as DOM can when working with large files. On the other hand, using DOM exclusively can really kill your resources, especially if used on a lot of small files. SAX is read-only, while DOM allows changes to the XML file. Since these two different APIs literally complement each other there is no reason why you can”t use them both for large projects. Parsing and Creating XML using Ruby The most common way to manipulate XML is with the REXML library by Sean Russell. Since 2002, REXML has been part of the standard Ruby distribution. REXML is a pure-Ruby XML processor conforming to the XML 1.0 standard. It is a non-validating processor, passing all of the OASIS non-validating conformance tests. REXML parser has the following advantages over other available parsers − It is written 100 percent in Ruby. It can be used for both SAX and DOM parsing. It is lightweight, less than 2000 lines of code. Methods and classes are really easy-to-understand. SAX2-based API and Full XPath support. Shipped with Ruby installation and no separate installation is required. For all our XML code examples, let”s use a simple XML file as an input − <collection shelf = “New Arrivals”> <movie title = “Enemy Behind”> <type>War, Thriller</type> <format>DVD</format> <year>2003</year> <rating>PG</rating> <stars>10</stars> <description>Talk about a US-Japan war</description> </movie> <movie title = “Transformers”> <type>Anime, Science Fiction</type> <format>DVD</format> <year>1989</year> <rating>R</rating> <stars>8</stars> <description>A schientific fiction</description> </movie> <movie title = “Trigun”> <type>Anime, Action</type> <format>DVD</format> <episodes>4</episodes> <rating>PG</rating> <stars>10</stars> <description>Vash the Stampede!</description> </movie> <movie title = “Ishtar”> <type>Comedy</type> <format>VHS</format> <rating>PG</rating> <stars>2</stars> <description>Viewable boredom</description> </movie> </collection> DOM-like Parsing Let”s first parse our XML data in tree fashion. We begin by requiring the rexml/document library; often we do an include REXML to import into the top-level namespace for convenience. #!/usr/bin/ruby -w require ”rexml/document” include REXML xmlfile = File.new(“movies.xml”) xmldoc = Document.new(xmlfile) # Now get the root element root = xmldoc.root puts “Root element : ” + root.attributes[“shelf”] # This will output all the movie titles. xmldoc.elements.each(“collection/movie”){ |e| puts “Movie Title : ” + e.attributes[“title”] } # This will output all the movie types. xmldoc.elements.each(“collection/movie/type”) { |e| puts “Movie Type : ” + e.text } # This will output all the movie description. xmldoc.elements.each(“collection/movie/description”) { |e| puts “Movie Description : ” + e.text } This will produce the following result − Root element : New Arrivals Movie Title : Enemy Behind Movie Title : Transformers Movie Title : Trigun Movie Title : Ishtar Movie Type : War, Thriller Movie Type : Anime, Science Fiction Movie Type : Anime, Action Movie Type : Comedy Movie Description : Talk about a US-Japan war Movie Description : A schientific fiction Movie Description : Vash the Stampede! Movie Description : Viewable boredom SAX-like Parsing To process the same data, movies.xml, file in a stream-oriented way we will define a listener class whose methods will be the target of callbacks from the parser. NOTE − It is not suggested to use SAX-like parsing for a small file, this is just for a demo example. #!/usr/bin/ruby -w require ”rexml/document” require ”rexml/streamlistener” include REXML class MyListener include REXML::StreamListener def tag_start(*args) puts “tag_start: #{args.map {|x| x.inspect}.join(”, ”)}” end def text(data) return if data =~ /^w*$/ # whitespace only abbrev = data[0..40] + (data.length > 40 ? “…” : “”) puts ” text : #{abbrev.inspect}” end end list = MyListener.new xmlfile = File.new(“movies.xml”) Document.parse_stream(xmlfile, list) This will produce the following result − tag_start: “collection”, {“shelf”=>”New Arrivals”} tag_start: “movie”, {“title”=>”Enemy Behind”} tag_start: “type”, {} text : “War, Thriller” tag_start: “format”, {} tag_start: “year”, {} tag_start: “rating”, {} tag_start: “stars”, {} tag_start: “description”, {} text : “Talk about a US-Japan war” tag_start: “movie”, {“title”=>”Transformers”} tag_start: “type”, {} text : “Anime, Science Fiction” tag_start: “format”, {} tag_start: “year”, {} tag_start: “rating”, {} tag_start: “stars”, {} tag_start: “description”, {} text : “A schientific fiction” tag_start: “movie”, {“title”=>”Trigun”} tag_start: “type”, {} text : “Anime, Action” tag_start: “format”, {} tag_start: “episodes”, {} tag_start: “rating”, {} tag_start: “stars”, {} tag_start: “description”, {} text : “Vash the Stampede!” tag_start: “movie”, {“title”=>”Ishtar”} tag_start: “type”, {} tag_start: “format”, {} tag_start: “rating”, {} tag_start: “stars”, {} tag_start: “description”, {} text : “Viewable boredom” XPath and Ruby An alternative way to view XML is XPath. This is a kind of pseudo-language that describes how to locate specific elements and attributes in an XML document, treating that document as a logical ordered tree. REXML has XPath support via the XPath class. It assumes tree-based parsing (document object model) as we have seen above. #!/usr/bin/ruby -w require ”rexml/document” include REXML xmlfile = File.new(“movies.xml”) xmldoc = Document.new(xmlfile) # Info for the first movie found movie = XPath.first(xmldoc, “//movie”) p movie # Print out all the movie types XPath.each(xmldoc, “//type”) { |e| puts e.text } # Get an array of all of the movie formats. names = XPath.match(xmldoc, “//format”).map {|x| x.text } p

Ruby – Web Services

Web Services with Ruby – SOAP4R ”; Previous Next What is SOAP? The Simple Object Access Protocol (SOAP), is a cross-platform and language-independent RPC protocol based on XML and, usually (but not necessarily) HTTP. It uses XML to encode the information that makes the remote procedure call, and HTTP to transport that information across a network from clients to servers and vice versa. SOAP has several advantages over other technologies like COM, CORBA etc: for example, its relatively cheap deployment and debugging costs, its extensibility and ease-of-use, and the existence of several implementations for different languages and platforms. Please refer to our simple tutorial SOAP to understand it in detail. This chapter makes you familiar with the SOAP implementation for Ruby (SOAP4R). This is a basic tutorial, so if you need a deep detail, you would need to refer other resources. Installing SOAP4R SOAP4R is the SOAP implementation for Ruby developed by Hiroshi Nakamura and can be downloaded from − NOTE − There may be a great chance that you already have installed this component. Download SOAP If you are aware of gem utility then you can use the following command to install SOAP4R and related packages. $ gem install soap4r –include-dependencies If you are working on Windows, then you need to download a zipped file from the above location and need to install it using the standard installation method by running ruby install.rb. Writing SOAP4R Servers SOAP4R supports two different types of servers − CGI/FastCGI based (SOAP::RPC::CGIStub) Standalone (SOAP::RPC:StandaloneServer) This chapter gives detail on writing a stand alone server. The following steps are involved in writing a SOAP server. Step 1 – Inherit SOAP::RPC::StandaloneServer Class To implement your own stand alone server you need to write a new class, which will be child of SOAP::StandaloneServer as follows − class MyServer < SOAP::RPC::StandaloneServer …………… end NOTE − If you want to write a FastCGI based server then you need to take SOAP::RPC::CGIStub as parent class, rest of the procedure will remain the same. Step 2 – Define Handler Methods Second step is to write your Web Services methods, which you would like to expose to the outside world. They can be written as simple Ruby methods. For example, let”s write two methods to add two numbers and divide two numbers − class MyServer < SOAP::RPC::StandaloneServer …………… # Handler methods def add(a, b) return a &plus; b end def div(a, b) return a / b end end Step 3 – Expose Handler Methods Next step is to add our defined methods to our server. The initialize method is used to expose service methods with one of the two following methods − class MyServer < SOAP::RPC::StandaloneServer def initialize(*args) add_method(receiver, methodName, *paramArg) end end Here is the description of the parameters − Sr.No. Parameter & Description 1 receiver The object that contains the methodName method. You define the service methods in the same class as the methodDef method, this parameter is self. 2 methodName The name of the method that is called due to an RPC request. 3 paramArg Specifies, when given, the parameter names and parameter modes. To understand the usage of inout or out parameters, consider the following service method that takes two parameters (inParam and inoutParam), returns one normal return value (retVal) and two further parameters: inoutParam and outParam − def aMeth(inParam, inoutParam) retVal = inParam &plus; inoutParam outParam = inParam . inoutParam inoutParam = inParam * inoutParam return retVal, inoutParam, outParam end Now, we can expose this method as follows − add_method(self, ”aMeth”, [ %w(in inParam), %w(inout inoutParam), %w(out outParam), %w(retval return) ]) Step 4 – Start the Server The final step is to start your server by instantiating one instance of the derived class and calling start method. myServer = MyServer.new(”ServerName”, ”urn:ruby:ServiceName”, hostname, port) myServer.start Here is the description of required parameters − Sr.No. Parameter & Description 1 ServerName A server name, you can give what you like most. 2 urn:ruby:ServiceName Here urn:ruby is constant but you can give a unique ServiceName name for this server. 3 hostname Specifies the hostname on which this server will listen. 4 port An available port number to be used for the web service. Example Now, using the above steps, let us write one standalone server − require “soap/rpc/standaloneserver” begin class MyServer < SOAP::RPC::StandaloneServer # Expose our services def initialize(*args) add_method(self, ”add”, ”a”, ”b”) add_method(self, ”div”, ”a”, ”b”) end # Handler methods def add(a, b) return a &plus; b end def div(a, b) return a / b end end server = MyServer.new(“MyServer”, ”urn:ruby:calculation”, ”localhost”, 8080) trap(”INT){ server.shutdown } server.start rescue => err puts err.message end When executed, this server application starts a standalone SOAP server on localhost and listens for requests on port 8080. It exposes one service methods, add and div, which takes two parameters and return the result. Now, you can run this server in background as follows − $ ruby MyServer.rb& Writing SOAP4R Clients The SOAP::RPC::Driver class provides support for writing SOAP client applications. This chapter describes this class and demonstrate its usage on the basis of an application. Following is the bare minimum information you would need to call a SOAP service − The URL of the SOAP service (SOAP Endpoint URL). The namespace of the service methods (Method Namespace URI). The names of the service methods and their parameters. Now, we will write a SOAP client which would call service methods defined in above example, named add and div. Here are the main steps to create a SOAP client. Step 1 – Create a SOAP Driver Instance We create an instance of SOAP::RPC::Driver by calling its new method as follows − SOAP::RPC::Driver.new(endPoint, nameSpace, soapAction) Here is the description of required parameters − Sr.No. Parameter & Description 1 endPoint URL of the SOAP server to connect with. 2 nameSpace The namespace to use for all RPCs done with this SOAP::RPC::Driver object. 3 soapAction A value for the SOAPAction field of the HTTP header. If nil this defaults to the empty string “”. Step 2

Ruby – Multithreading

Ruby – Multithreading ”; Previous Next Traditional programs have a single thread of execution the statements or instructions that comprise the program are executed sequentially until the program terminates. A multithreaded program has more than one thread of execution. Within each thread, statements are executed sequentially, but the threads themselves may be executed in parallel on a multicore CPU, for example. Often on a single CPU machine, multiple threads are not actually executed in parallel, but parallelism is simulated by interleaving the execution of the threads. Ruby makes it easy to write multi-threaded programs with the Thread class. Ruby threads are a lightweight and efficient way to achieve concurrency in your code. Creating Ruby Threads To start a new thread, just associate a block with a call to Thread.new. A new thread will be created to execute the code in the block, and the original thread will return from Thread.new immediately and resume execution with the next statement − # Thread #1 is running here Thread.new { # Thread #2 runs this code } # Thread #1 runs this code Example Here is an example, which shows how we can use multi-threaded Ruby program. #!/usr/bin/ruby def func1 i = 0 while i<=2 puts “func1 at: #{Time.now}” sleep(2) i = i&plus;1 end end def func2 j = 0 while j<=2 puts “func2 at: #{Time.now}” sleep(1) j = j&plus;1 end end puts “Started At #{Time.now}” t1 = Thread.new{func1()} t2 = Thread.new{func2()} t1.join t2.join puts “End at #{Time.now}” This will produce following result − Started At Wed May 14 08:21:54 -0700 2008 func1 at: Wed May 14 08:21:54 -0700 2008 func2 at: Wed May 14 08:21:54 -0700 2008 func2 at: Wed May 14 08:21:55 -0700 2008 func1 at: Wed May 14 08:21:56 -0700 2008 func2 at: Wed May 14 08:21:56 -0700 2008 func1 at: Wed May 14 08:21:58 -0700 2008 End at Wed May 14 08:22:00 -0700 2008 Thread Lifecycle A new threads are created with Thread.new. You can also use the synonyms Thread.start and Thread.fork. There is no need to start a thread after creating it, it begins running automatically when CPU resources become available. The Thread class defines a number of methods to query and manipulate the thread while it is running. A thread runs the code in the block associated with the call to Thread.new and then it stops running. The value of the last expression in that block is the value of the thread, and can be obtained by calling the value method of the Thread object. If the thread has run to completion, then the value returns the thread”s value right away. Otherwise, the value method blocks and does not return until the thread has completed. The class method Thread.current returns the Thread object that represents the current thread. This allows threads to manipulate themselves. The class method Thread.main returns the Thread object that represents the main thread. This is the initial thread of execution that began when the Ruby program was started. You can wait for a particular thread to finish by calling that thread”s Thread.join method. The calling thread will block until the given thread is finished. Threads and Exceptions If an exception is raised in the main thread, and is not handled anywhere, the Ruby interpreter prints a message and exits. In threads, other than the main thread, unhandled exceptions cause the thread to stop running. If a thread t exits because of an unhandled exception, and another thread s calls t.join or t.value, then the exception that occurred in t is raised in the thread s. If Thread.abort_on_exception is false, the default condition, an unhandled exception simply kills the current thread and all the rest continue to run. If you would like any unhandled exception in any thread to cause the interpreter to exit, set the class method Thread.abort_on_exception to true. t = Thread.new { … } t.abort_on_exception = true Thread Variables A thread can normally access any variables that are in scope when the thread is created. Variables local to the block of a thread are local to the thread, and are not shared. Thread class features a special facility that allows thread-local variables to be created and accessed by name. You simply treat the thread object as if it were a Hash, writing to elements using []= and reading them back using []. In this example, each thread records the current value of the variable count in a threadlocal variable with the key mycount. Live Demo #!/usr/bin/ruby count = 0 arr = [] 10.times do |i| arr[i] = Thread.new { sleep(rand(0)/10.0) Thread.current[“mycount”] = count count &plus;= 1 } end arr.each {|t| t.join; print t[“mycount”], “, ” } puts “count = #{count}” This produces the following result − 8, 0, 3, 7, 2, 1, 6, 5, 4, 9, count = 10 The main thread waits for the subthreads to finish and then prints out the value of count captured by each. Thread Priorities The first factor that affects the thread scheduling is the thread priority: high-priority threads are scheduled before low-priority threads. More precisely, a thread will only get CPU time if there are no higher-priority threads waiting to run. You can set and query the priority of a Ruby Thread object with priority = and priority. A newly created thread starts at the same priority as the thread that created it. The main thread starts off at priority 0. There is no way to set the priority of a thread before it starts running. A thread can, however, raise or lower its own priority as the first action it takes. Thread Exclusion If two threads share access to the same data, and at least one of the threads modifies that data, you must take special care to ensure that no thread can ever see the data in an inconsistent state. This is called thread exclusion. Mutex is a class that implements a simple semaphore lock for mutually exclusive access to some shared resource. That is, only one thread

Ruby – Sending Email

Sending Email using Ruby – SMTP ”; Previous Next Simple Mail Transfer Protocol (SMTP) is a protocol, which handles sending e-mail and routing e-mail between mail servers. Ruby provides Net::SMTP class for Simple Mail Transfer Protocol (SMTP) client-side connection and provides two class methods new and start. The new takes two parameters − The server name defaulting to localhost. The port number defaulting to the well-known port 25. The start method takes these parameters − The server − IP name of the SMTP server, defaulting to localhost. The port − Port number, defaulting to 25. The domain − Domain of the mail sender, defaulting to ENV[“HOSTNAME”]. The account − Username, default is nil. The password − User password, defaulting to nil. The authtype − Authorization type, defaulting to cram_md5. An SMTP object has an instance method called sendmail, which will typically be used to do the work of mailing a message. It takes three parameters − The source − A string or array or anything with an each iterator returning one string at a time. The sender − A string that will appear in the from field of the email. The recipients − A string or an array of strings representing the recipients” addressee(s). Example Here is a simple way to send one email using Ruby script. Try it once − require ”net/smtp” message = <<MESSAGE_END From: Private Person <me&commat;fromdomain.com> To: A Test User <test&commat;todomain.com> Subject: SMTP e-mail test This is a test e-mail message. MESSAGE_END Net::SMTP.start(”localhost”) do |smtp| smtp.send_message message, ”me&commat;fromdomain.com”, ”test&commat;todomain.com” end Here, you have placed a basic e-mail in message, using a document, taking care to format the headers correctly. E-mails require a From, To, and Subject header, separated from the body of the e-mail with a blank line. To send the mail you use Net::SMTP to connect to the SMTP server on the local machine and then use the send_message method along with the message, the from address, and the destination address as parameters (even though the from and to addresses are within the e-mail itself, these aren”t always used to route mail). If you”re not running an SMTP server on your machine, you can use the Net::SMTP to communicate with a remote SMTP server. Unless you”re using a webmail service (such as Hotmail or Yahoo! Mail), your e-mail provider will have provided you with outgoing mail server details that you can supply to Net::SMTP, as follows − Net::SMTP.start(”mail.your-domain.com”) This line of code connects to the SMTP server on port 25 of mail.your-domain.com without using any username or password. If you need to, though, you can specify port number and other details. For example − Net::SMTP.start(”mail.your-domain.com”, 25, ”localhost”, ”username”, ”password” :plain) This example connects to the SMTP server at mail.your-domain.com using a username and password in plain text format. It identifies the client”s hostname as localhost. Sending an HTML e-mail using Ruby When you send a text message using Ruby then all the content will be treated as simple text. Even if you will include HTML tags in a text message, it will be displayed as simple text and HTML tags will not be formatted according to HTML syntax. But Ruby Net::SMTP provides option to send an HTML message as actual HTML message. While sending an email message you can specify a Mime version, content type and character set to send an HTML email. Example Following is the example to send HTML content as an email. Try it once − require ”net/smtp” message = <<MESSAGE_END From: Private Person <me&commat;fromdomain.com> To: A Test User <test&commat;todomain.com> MIME-Version: 1.0 Content-type: text/html Subject: SMTP e-mail test This is an e-mail message to be sent in HTML format <b>This is HTML message.</b> <h1>This is headline.</h1> MESSAGE_END Net::SMTP.start(”localhost”) do |smtp| smtp.send_message message, ”me&commat;fromdomain.com”, ”test&commat;todomain.com” end Sending Attachments as an e-mail To send an email with mixed content requires to set Content-type header to multipart/mixed. Then text and attachment sections can be specified within boundaries. A boundary is started with two hyphens followed by a unique number, which cannot appear in the message part of the email. A final boundary denoting the email”s final section must also end with two hyphens. Attached files should be encoded with the pack(“m”) function to have base64 encoding before transmission. Example Following is the example, which will send a file /tmp/test.txt as an attachment. require ”net/smtp” filename = “/tmp/test.txt” # Read a file and encode it into base64 format filecontent = File.read(filename) encodedcontent = [filecontent].pack(“m”) # base64 marker = “AUNIQUEMARKER” body = <<EOF This is a test email to send an attachement. EOF # Define the main headers. part1 = <<EOF From: Private Person <me&commat;fromdomain.net> To: A Test User <test&commat;todmain.com> Subject: Sending Attachement MIME-Version: 1.0 Content-Type: multipart/mixed; boundary = #{marker} –#{marker} EOF # Define the message action part2 = <<EOF Content-Type: text/plain Content-Transfer-Encoding:8bit #{body} –#{marker} EOF # Define the attachment section part3 = <<EOF Content-Type: multipart/mixed; name = “#{filename}” Content-Transfer-Encoding:base64 Content-Disposition: attachment; filename = “#{filename}” #{encodedcontent} –#{marker}– EOF mailtext = part1 &plus; part2 &plus; part3 # Let”s put our code in safe area begin Net::SMTP.start(”localhost”) do |smtp| smtp.sendmail(mailtext, ”me&commat;fromdomain.net”, [”test&commat;todmain.com”]) end rescue Exception => e print “Exception occured: ” &plus; e end NOTE − You can specify multiple destinations inside the array but they should be separated by comma. Print Page Previous Next Advertisements ”;

Ruby – Exceptions

Ruby – Exceptions ”; Previous Next The execution and the exception always go together. If you are opening a file, which does not exist, then if you did not handle this situation properly, then your program is considered to be of bad quality. The program stops if an exception occurs. So exceptions are used to handle various type of errors, which may occur during a program execution and take appropriate action instead of halting program completely. Ruby provide a nice mechanism to handle exceptions. We enclose the code that could raise an exception in a begin/end block and use rescue clauses to tell Ruby the types of exceptions we want to handle. Syntax begin # – rescue OneTypeOfException # – rescue AnotherTypeOfException # – else # Other exceptions ensure # Always will be executed end Everything from begin to rescue is protected. If an exception occurs during the execution of this block of code, control is passed to the block between rescue and end. For each rescue clause in the begin block, Ruby compares the raised Exception against each of the parameters in turn. The match will succeed if the exception named in the rescue clause is the same as the type of the currently thrown exception, or is a superclass of that exception. In an event that an exception does not match any of the error types specified, we are allowed to use an else clause after all the rescue clauses. Example Live Demo #!/usr/bin/ruby begin file = open(“/unexistant_file”) if file puts “File opened successfully” end rescue file = STDIN end print file, “==”, STDIN, “n” This will produce the following result. You can see that STDIN is substituted to file because open failed. #<IO:0xb7d16f84>==#<IO:0xb7d16f84> Using retry Statement You can capture an exception using rescue block and then use retry statement to execute begin block from the beginning. Syntax begin # Exceptions raised by this code will # be caught by the following rescue clause rescue # This block will capture all types of exceptions retry # This will move control to the beginning of begin end Example #!/usr/bin/ruby begin file = open(“/unexistant_file”) if file puts “File opened successfully” end rescue fname = “existant_file” retry end The following is the flow of the process − An exception occurred at open. Went to rescue. fname was re-assigned. By retry went to the beginning of the begin. This time file opens successfully. Continued the essential process. NOTE − Notice that if the file of re-substituted name does not exist this example code retries infinitely. Be careful if you use retry for an exception process. Using raise Statement You can use raise statement to raise an exception. The following method raises an exception whenever it”s called. It”s second message will be printed. Syntax raise OR raise “Error Message” OR raise ExceptionType, “Error Message” OR raise ExceptionType, “Error Message” condition The first form simply re-raises the current exception (or a RuntimeError if there is no current exception). This is used in exception handlers that need to intercept an exception before passing it on. The second form creates a new RuntimeError exception, setting its message to the given string. This exception is then raised up the call stack. The third form uses the first argument to create an exception and then sets the associated message to the second argument. The fourth form is similar to the third form but you can add any conditional statement like unless to raise an exception. Example Live Demo #!/usr/bin/ruby begin puts ”I am before the raise.” raise ”An error has occurred.” puts ”I am after the raise.” rescue puts ”I am rescued.” end puts ”I am after the begin block.” This will produce the following result − I am before the raise. I am rescued. I am after the begin block. One more example showing the usage of raise − Live Demo #!/usr/bin/ruby begin raise ”A test exception.” rescue Exception => e puts e.message puts e.backtrace.inspect end This will produce the following result − A test exception. [“main.rb:4″] Using ensure Statement Sometimes, you need to guarantee that some processing is done at the end of a block of code, regardless of whether an exception was raised. For example, you may have a file open on entry to the block and you need to make sure it gets closed as the block exits. The ensure clause does just this. ensure goes after the last rescue clause and contains a chunk of code that will always be executed as the block terminates. It doesn”t matter if the block exits normally, if it raises and rescues an exception, or if it is terminated by an uncaught exception, the ensure block will get run. Syntax begin #.. process #..raise exception rescue #.. handle error ensure #.. finally ensure execution #.. This will always execute. end Example Live Demo begin raise ”A test exception.” rescue Exception => e puts e.message puts e.backtrace.inspect ensure puts “Ensuring execution” end This will produce the following result − A test exception. [“main.rb:4″] Ensuring execution Using else Statement If the else clause is present, it goes after the rescue clauses and before any ensure. The body of an else clause is executed only if no exceptions are raised by the main body of code. Syntax begin #.. process #..raise exception rescue # .. handle error else #.. executes if there is no exception ensure #.. finally ensure execution #.. This will always execute. end Example Live Demo begin # raise ”A test exception.” puts “I”m not raising exception” rescue Exception => e puts e.message puts e.backtrace.inspect else puts “Congratulations– no errors!” ensure puts “Ensuring execution” end This will produce the following result − I”m not raising exception Congratulations– no errors! Ensuring execution Raised error message can be captured using &dollar;! variable. Catch and Throw While the exception mechanism of raise and rescue is great for abandoning the execution when things go wrong, it”s sometimes nice to be able to jump out of some deeply

Ruby – Regular Expressions

Ruby – Regular Expressions ”; Previous Next A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings using a specialized syntax held in a pattern. A regular expression literal is a pattern between slashes or between arbitrary delimiters followed by %r as follows − Syntax /pattern/ /pattern/im # option can be specified %r!/usr/local! # general delimited regular expression Example Live Demo #!/usr/bin/ruby line1 = “Cats are smarter than dogs”; line2 = “Dogs also like meat”; if ( line1 =~ /Cats(.*)/ ) puts “Line1 contains Cats” end if ( line2 =~ /Cats(.*)/ ) puts “Line2 contains Dogs” end This will produce the following result − Line1 contains Cats Regular-Expression Modifiers Regular expression literals may include an optional modifier to control various aspects of matching. The modifier is specified after the second slash character, as shown previously and may be represented by one of these characters − Sr.No. Modifier & Description 1 i Ignores case when matching text. 2 o Performs #{} interpolations only once, the first time the regexp literal is evaluated. 3 x Ignores whitespace and allows comments in regular expressions. 4 m Matches multiple lines, recognizing newlines as normal characters. 5 u,e,s,n Interprets the regexp as Unicode (UTF-8), EUC, SJIS, or ASCII. If none of these modifiers is specified, the regular expression is assumed to use the source encoding. Like string literals delimited with %Q, Ruby allows you to begin your regular expressions with %r followed by a delimiter of your choice. This is useful when the pattern you are describing contains a lot of forward slash characters that you don”t want to escape − # Following matches a single slash character, no escape required %r|/| # Flag characters are allowed with this syntax, too %r[</(.*)>]i Regular-Expression Patterns Except for control characters, (&plus; ? . * ^ &dollar; ( ) [ ] { } | ), all characters match themselves. You can escape a control character by preceding it with a backslash. Following table lists the regular expression syntax that is available in Ruby. Sr.No. Pattern & Description 1 ^ Matches beginning of line. 2 $ Matches end of line. 3 . Matches any single character except newline. Using m option allows it to match newline as well. 4 […] Matches any single character in brackets. 5 [^…] Matches any single character not in brackets 6 re* Matches 0 or more occurrences of preceding expression. 7 re+ Matches 1 or more occurrence of preceding expression. 8 re? Matches 0 or 1 occurrence of preceding expression. 9 re{ n} Matches exactly n number of occurrences of preceding expression. 10 re{ n,} Matches n or more occurrences of preceding expression. 11 re{ n, m} Matches at least n and at most m occurrences of preceding expression. 12 a| b Matches either a or b. 13 (re) Groups regular expressions and remembers matched text. 14 (?imx) Temporarily toggles on i, m, or x options within a regular expression. If in parentheses, only that area is affected. 15 (?-imx) Temporarily toggles off i, m, or x options within a regular expression. If in parentheses, only that area is affected. 16 (?: re) Groups regular expressions without remembering matched text. 17 (?imx: re) Temporarily toggles on i, m, or x options within parentheses. 18 (?-imx: re) Temporarily toggles off i, m, or x options within parentheses. 19 (?#…) Comment. 20 (?= re) Specifies position using a pattern. Doesn”t have a range. 21 (?! re) Specifies position using pattern negation. Doesn”t have a range. 22 (?> re) Matches independent pattern without backtracking. 23 w Matches word characters. 24 W Matches nonword characters. 25 s Matches whitespace. Equivalent to [tnrf]. 26 S Matches nonwhitespace. 27 d Matches digits. Equivalent to [0-9]. 28 D Matches nondigits. 29 A Matches beginning of string. 30 Z Matches end of string. If a newline exists, it matches just before newline. 31 z Matches end of string. 32 G Matches point where last match finished. 33 b Matches word boundaries when outside brackets. Matches backspace (0x08) when inside brackets. 34 B Matches non-word boundaries. 35 n, t, etc. Matches newlines, carriage returns, tabs, etc. 36 1…9 Matches nth grouped subexpression. 37 10 Matches nth grouped subexpression if it matched already. Otherwise refers to the octal representation of a character code. Regular-Expression Examples Literal Characters Sr.No. Example & Description 1 /ruby/ Matches “ruby”. 2 ¥ Matches Yen sign. Multibyte characters are supported in Ruby 1.9 and Ruby 1.8. Character Classes Sr.No. Example & Description 1 /[Rr]uby/ Matches “Ruby” or “ruby”. 2 /rub[ye]/ Matches “ruby” or “rube”. 3 /[aeiou]/ Matches any one lowercase vowel. 4 /[0-9]/ Matches any digit; same as /[0123456789]/. 5 /[a-z]/ Matches any lowercase ASCII letter. 6 /[A-Z]/ Matches any uppercase ASCII letter. 7 /[a-zA-Z0-9]/ Matches any of the above. 8 /[^aeiou]/ Matches anything other than a lowercase vowel. 9 /[^0-9]/ Matches anything other than a digit. Special Character Classes Sr.No. Example & Description 1 /./ Matches any character except newline. 2 /./m In multi-line mode, matches newline, too. 3 /d/ Matches a digit: /[0-9]/. 4 /D/ Matches a non-digit: /[^0-9]/. 5 /s/ Matches a whitespace character: /[ trnf]/. 6 /S/ Matches non-whitespace: /[^ trnf]/. 7 /w/ Matches a single word character: /[A-Za-z0-9_]/. 8 /W/ Matches a non-word character: /[^A-Za-z0-9_]/. Repetition Cases Sr.No. Example & Description 1 /ruby?/ Matches “rub” or “ruby”: the y is optional. 2 /ruby*/ Matches “rub” plus 0 or more ys. 3 /ruby+/ Matches “rub” plus 1 or more ys. 4 /d{3}/ Matches exactly 3 digits. 5 /d{3,}/ Matches 3 or more digits. 6 /d{3,5}/ Matches 3, 4, or 5 digits. Non-greedy Repetition This matches the smallest number of repetitions − Sr.No. Example & Description 1 /<.*>/ Greedy repetition: matches “<ruby>perl>”. 2 /<.*?>/ Non-greedy: matches “<ruby>” in “<ruby>perl>”. Grouping with Parentheses Sr.No. Example & Description 1 /Dd+/ No group: + repeats d 2 /(Dd)+/ Grouped: + repeats Dd pair 3 /([Rr]uby(, )?)+/ Match “Ruby”, “Ruby, ruby, ruby”, etc. Back References This

Ruby – Date & Time

Ruby – Date & Time ”; Previous Next The Time class represents dates and times in Ruby. It is a thin layer over the system date and time functionality provided by the operating system. This class may be unable on your system to represent dates before 1970 or after 2038. This chapter makes you familiar with all the most wanted concepts of date and time. Getting Current Date and Time Following is the simple example to get current date and time − Live Demo #!/usr/bin/ruby -w time1 = Time.new puts “Current Time : ” &plus; time1.inspect # Time.now is a synonym: time2 = Time.now puts “Current Time : ” &plus; time2.inspect This will produce the following result − Current Time : Mon Jun 02 12:02:39 -0700 2008 Current Time : Mon Jun 02 12:02:39 -0700 2008 Getting Components of a Date & Time We can use Time object to get various components of date and time. Following is the example showing the same − Live Demo #!/usr/bin/ruby -w time = Time.new # Components of a Time puts “Current Time : ” + time.inspect puts time.year # => Year of the date puts time.month # => Month of the date (1 to 12) puts time.day # => Day of the date (1 to 31 ) puts time.wday # => 0: Day of week: 0 is Sunday puts time.yday # => 365: Day of year puts time.hour # => 23: 24-hour clock puts time.min # => 59 puts time.sec # => 59 puts time.usec # => 999999: microseconds puts time.zone # => “UTC”: timezone name This will produce the following result − Current Time : Mon Jun 02 12:03:08 -0700 2008 2008 6 2 1 154 12 3 8 247476 UTC Time.utc, Time.gm and Time.local Functions These two functions can be used to format date in a standard format as follows − # July 8, 2008 Time.local(2008, 7, 8) # July 8, 2008, 09:10am, local time Time.local(2008, 7, 8, 9, 10) # July 8, 2008, 09:10 UTC Time.utc(2008, 7, 8, 9, 10) # July 8, 2008, 09:10:11 GMT (same as UTC) Time.gm(2008, 7, 8, 9, 10, 11) Following is the example to get all the components in an array in the following format − [sec,min,hour,day,month,year,wday,yday,isdst,zone] Try the following − Live Demo #!/usr/bin/ruby -w time = Time.new values = time.to_a p values This will generate the following result − [26, 10, 12, 2, 6, 2008, 1, 154, false, “MST”] This array could be passed to Time.utc or Time.local functions to get different format of dates as follows − Live Demo #!/usr/bin/ruby -w time = Time.new values = time.to_a puts Time.utc(*values) This will generate the following result − Mon Jun 02 12:15:36 UTC 2008 Following is the way to get time represented internally as seconds since the (platform-dependent) epoch − # Returns number of seconds since epoch time = Time.now.to_i # Convert number of seconds into Time object. Time.at(time) # Returns second since epoch which includes microseconds time = Time.now.to_f Timezones and Daylight Savings Time You can use a Time object to get all the information related to Timezones and daylight savings as follows − time = Time.new # Here is the interpretation time.zone # => “UTC”: return the timezone time.utc_offset # => 0: UTC is 0 seconds offset from UTC time.zone # => “PST” (or whatever your timezone is) time.isdst # => false: If UTC does not have DST. time.utc? # => true: if t is in UTC time zone time.localtime # Convert to local timezone. time.gmtime # Convert back to UTC. time.getlocal # Return a new Time object in local zone time.getutc # Return a new Time object in UTC Formatting Times and Dates There are various ways to format date and time. Here is one example showing a few − Live Demo #!/usr/bin/ruby -w time = Time.new puts time.to_s puts time.ctime puts time.localtime puts time.strftime(“%Y-%m-%d %H:%M:%S”) This will produce the following result − Mon Jun 02 12:35:19 -0700 2008 Mon Jun 2 12:35:19 2008 Mon Jun 02 12:35:19 -0700 2008 2008-06-02 12:35:19 Time Formatting Directives These directives in the following table are used with the method Time.strftime. Sr.No. Directive & Description 1 %a The abbreviated weekday name (Sun). 2 %A The full weekday name (Sunday). 3 %b The abbreviated month name (Jan). 4 %B The full month name (January). 5 %c The preferred local date and time representation. 6 %d Day of the month (01 to 31). 7 %H Hour of the day, 24-hour clock (00 to 23). 8 %I Hour of the day, 12-hour clock (01 to 12). 9 %j Day of the year (001 to 366). 10 %m Month of the year (01 to 12). 11 %M Minute of the hour (00 to 59). 12 %p Meridian indicator (AM or PM). 13 %S Second of the minute (00 to 60). 14 %U Week number of the current year, starting with the first Sunday as the first day of the first week (00 to 53). 15 %W Week number of the current year, starting with the first Monday as the first day of the first week (00 to 53). 16 %w Day of the week (Sunday is 0, 0 to 6). 17 %x Preferred representation for the date alone, no time. 18 %X Preferred representation for the time alone, no date. 19 %y Year without a century (00 to 99). 20 %Y Year with century. 21 %Z Time zone name. 22 %% Literal % character. Time Arithmetic You can perform simple arithmetic with time as follows − Live Demo now = Time.now # Current time puts now past = now – 10 # 10 seconds ago. Time – number => Time puts past future = now + 10 # 10 seconds from now Time + number => Time puts future diff = future – past # => 10 Time – Time => number of seconds puts diff This will produce the following result − Thu Aug 01 20:57:05 -0700 2013 Thu Aug 01 20:56:55 -0700 2013

Ruby – Useful Resources

Ruby – Useful Resources ”; Previous Next The following resources contain additional information on Ruby. Please use them to get more in-depth knowledge on this topic. Learn Ruby on Rails online from Scratch 47 Lectures 9.5 hours Eduonix Learning Solutions More Detail Ruby on Rails Course for Beginners 98 Lectures 7.5 hours Skillbakery More Detail Dissecting Ruby on Rails 5 – Become a Professional Developer 228 Lectures 40 hours YouAccel More Detail Print Page Previous Next Advertisements ”;