1. Trang chủ
  2. » Công Nghệ Thông Tin

Ruby for Rails phần 2 ppsx

52 428 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 52
Dung lượng 273,33 KB

Nội dung

16 CHAPTER 1 How Ruby works As already noted, when you run a Ruby program, you’re really running a pro- gram called ruby and feeding your program to that program. Here, we’ll look at fur- ther options available to you in the course of doing this. These options include command-line switches (of which you’ve seen an example in the -cw syntax-checking flag), techniques for directing your program to the Ruby interpreter without having to invoke ruby on the command line, and details of how to run the irb interpreter. 1.2.1 Command-line switches When you start the Ruby interpreter from the command line, you can provide not only the name of a program file but also one or more command-line switches. The switches you choose instruct the interpreter to behave in particular ways and/or take particular actions. Ruby has more than 20 command-line switches. Some of them are used rarely; others are used every day by many Ruby programmers. Here we’ll look at several more of the most commonly used ones. (You've already seen two of them, -c and -w, used in combination with each other.) These common switches are summa- rized in table 1.2 and then explained separately. Check syntax (-c) The -c switch tells Ruby to check the code in one or more files for syntactical accu- racy without executing the code. It’s usually used in conjunction with the -w flag. Table 1.2 Summary of commonly used Ruby command-line switches Switch Description Example of usage -c Check the syntax of a program file without executing the program ruby -c c2f.rb -w Give warning messages during pro- gram execution ruby -w c2f.rb -e Execute the code provided in quota- tion marks on the command line ruby -e 'puts "Code demo!"' -v Show Ruby version information, and execute the program in verbose mode ruby -v -l Line mode: print a newline after every line, if not otherwise present ruby -l -e 'print "Will jump down!"' -rname Load the named extension (require it) ruby -rprofile version Show Ruby version information ruby version Techniques of interpreter invocation 17 Turn on warnings (-w) Running your program with -w causes the interpreter to run in warning mode. This means you’ll see more warnings than you otherwise would printed to the screen, drawing your attention to places in your program which, although not syn- tax errors, are stylistically or logically suspect. It’s Ruby’s way of saying, “What you’ve done is syntactically correct, but it’s weird. Are you sure you meant to do that?” (Even without this switch, Ruby issues certain warnings, but fewer than it does in full warning mode.) Execute literal script (-e) The -e switch tells the interpreter that the command line includes Ruby code, in quotation marks, and that it should execute that actual code rather than executing the code contained in a file. This can be handy for quick scripting jobs where enter- ing your code into a file and running ruby on the file may not be worth the trouble. For example, let’s say you want to see your name backward. Here’s how you can do this quickly, in one command-line command, using the execute switch: $ ruby -e 'puts "David A. Black".reverse' kcalB .A divaD What lies inside the single quotation marks is an entire (although short) Ruby program. If you want to feed a program with more than one line to the -e switch, you can use literal linebreaks inside the mini-program: $ ruby -e 'print "Enter a name: " puts gets.reverse' Enter a name: David A. Black kcalB .A divaD Or, you can separate the lines with semicolons: $ ruby -e 'print "Enter a name: "; print gets.reverse' NOTE NEWLINES IN REVERSED STRINGS Why is there a blank line between the program code and the output in the two-line reverse examples? Because the line you enter on the keyboard ends with a newline character—so when you reverse the input, the new string starts with a newline! Ruby, as al- ways, takes you literally when you ask it to manipulate and print data. Run in line mode (-l) If you look back at the result of executing the first version of the Celsius conversion program, the output from Ruby—the number 212—runs together on the screen 18 CHAPTER 1 How Ruby works with the prompt from the shell (the $ character). The reason, as you saw, was that you used print rather than puts , so no newline character followed the number. The -l switch gives you blanket coverage on putting lines of output on sepa- rate lines. It’s sometimes convenient to do this when you’re not sure whether the lines you plan to print end with newlines. In most cases, you can use puts , but the -l switch helps you in cases where you don’t have control over the code. Let’s say someone else writes a program that goes through a file of names and prints out the first names. For whatever reason, the original programmer uses print rather than puts , which means that a run of the program on a typical file produces output like this: $ ruby firstnames.rb AdaBarbaraClaraDoris Now, let’s say you want to use the program, but you want each name on a separate line. You can tell Ruby to operate in line mode, and you’ll get what you need: $ ruby -l firstnames.rb Ada Barbara Clara Doris You won’t see the -l flag as often as you’ll see programs that use puts to ensure similar behavior. But it can be useful, and you’ll want to be able to recognize it. Require named file or extension (-rname) The -r switch lets you specify files to require on the command line. As you’ll see, require also has the broader purpose of activating extensions (add-on program- ming facilities). You can use the -r flag for that flavor of require, too. Run in verbose mode (-v) Running with -v does two things: It prints out information about the version of Ruby you’re using, and then it turns on the same warning mechanism as the -w flag. The most common use of -v is to find out the Ruby version number: $ ruby -v ruby 1.8.2 (2004-12-25) [i686-linux] (In this case, we’re using Ruby 1.8.2, released on Christmas Day, 2004, and com- piled for an i686-based machine running Linux.) Because there’s no program or code to run, Ruby exits as soon as it has printed the version number. Techniques of interpreter invocation 19 Print Ruby version ( version) Not surprisingly, this flag is like -v except that all version does is to print the Ruby version information. It doesn’t proceed to execute any code, even if you pro- vide code or a filename. It just prints the version information and exits. You’ll see ruby -v much more often than ruby version . Combining switches It’s not uncommon to combine one or more command-line switches in a single invocation of Ruby. You’ve already seen the cw combination, which checks the syntax of the file without executing it, while also giving you warnings: $ ruby -cw filename Another combination of switches you’ll often see is -v and -e , which shows you the version of Ruby you’re running and then runs the code provided in quotation marks. You’ll see this combination a lot in discussions of Ruby, on mailing lists and elsewhere; people use it to demonstrate how the same code might work differ- ently in different versions of Ruby. For example, if you want to show clearly that an operation called lstrip (strip all whitespace from the left-hand side of a string) was not present in Ruby 1.6.8 but is present in Ruby 1.8.2, you can run a sample program using first one version of Ruby, then the other: $ ruby-1.6.8 -ve 'puts " abc".lstrip' ruby 1.6.8 (2002-12-24) [i686-linux] -e:1: undefined method `lstrip' for " abc":String (NameError) $ ruby -ve 'puts " abc".lstrip' ruby 1.8.2 (2004-12-25) [i686-linux] abc The undefined method 'lstrip' message on the first run (the one using version1.6.8) means that you’ve tried to perform a nonexistent named operation. When you run the same Ruby snipped using Ruby 1.8.2, however, it works: Ruby prints abc (with no leading blanks). This is a convenient way to share information and formulate questions about changes in Ruby’s behavior from one release to another. At this point, we’re going to go back and look more closely at the interactive Ruby interpreter, irb. You may have looked at this section already, when it was alluded to near the beginning of the chapter. If not, you can take this opportunity to learn more about this exceptionally useful Ruby tool. 20 CHAPTER 1 How Ruby works 1.2.2 A closer look at interactive Ruby interpretation with irb One of the great pleasures of using Ruby is using irb. irb is an interactive inter- preter—which means that instead of processing a file, it processes what you type in during a session. irb is a great tool for testing Ruby code, and a great tool for learning Ruby. To start an irb session, you use the command irb . irb will print out its prompt: $ irb irb(main):001:0> Now, you can enter Ruby commands. You can even run a one-shot version of the Celcius-to-Fahrenheit conversion program. As you’ll see in this example, irb behaves like a pocket calculator: It evaluates whatever you type in and prints the result. You don’t have to use a print or puts command: irb(main):001:0> 100 * 9 / 5 + 32 => 212 To find out how many minutes there are in a year (if you don’t have a CD of the hit song from the musical Rent handy), type in the relevant multiplication expression: irb(main):001:0> 365 * 24 * 60 => 525600 irb will also, of course, process any Ruby instructions you enter. For example, if you want to assign the day, hour, and minute counts to variables, and then multi- ply those variables, you can do that in irb: irb(main):001:0> days = 365 => 365 irb(main):002:0> hours = 24 => 24 irb(main):003:0> minutes = 60 => 60 irb(main):004:0> days * hours * minutes => 525600 The last calculation is what you’d expect. But look at the first three lines of entry. When you type days = 365 , irb responds by printing 365 . Why? The expression days = 365 is an assignment expression: You’re assigning the value 365 to a variable called days . The main business of an assignment expres- sion is to assign, so that you can use the variable later. But assignment expressions themselves—the whole days = 365 line—have a value. The value of an assignment expression is its right-hand side. When irb sees any expression, it prints out the value of that expression. So, when irb sees days = 365 , it prints out 365 . This may Ruby extensions and programming libraries 21 seem like overzealous printing, but it comes with the territory; it’s the same behav- ior that lets you type 2 + 2 into irb and see the result without having to use an explicit print statement. Once you get the hang of irb’s approach to printing out the value of everything, you’ll find it an immensely useful tool (and toy). TIP EXITING FROM IRB (INTENTIONALLY OR OTHERWISE) If you get stuck in a loop or frozen situation in irb , press Ctrl-c. To exit, press Ctrl-d or type exit . Occasionally, irb may blow up on you (that is, hit a fatal error and terminate itself). Most of the time, though, it will catch its own errors and let you continue. Next on our tour of the Ruby landscape are Ruby extensions and libraries. Look- ing at these facilities will give you a sense of how the core language interacts with the add-ons that are either bundled in the Ruby distribution or distributed sepa- rately by third-party programmers interested in enriching the Ruby program- ming environment. 1.3 Ruby extensions and programming libraries Earlier, you saw a simple example of the use of require to pull in one file from another during program execution. require is the foundation of a huge amount of Ruby’s power and richness as a programming language. Specifically, this mech- anism gives you access to the many extensions and programming libraries bundled with the Ruby programming language—as well as an even larger number of exten- sions and libraries written independently by other programmers and made avail- able for use with Ruby. The full range of Ruby’s standard library is outside of the scope of this book. This section provides guidelines and pointers about what Ruby offers and how to use libraries in your own programs. 1.3.1 Using standard extensions and libraries When you install Ruby on your system, you really install several layers. First is the core Ruby language: the basic operations and programming techniques available when you run the Ruby interpreter. Second are a large number of extensions and programming libraries bundled with Ruby—add-ons that help you write programs in different areas of specialization. These are usually referred to collectively as the standard library. Ruby comes with extensions for a wide variety of projects and tasks: database management, net- working, specialized mathematics, XML processing, and many more. 22 CHAPTER 1 How Ruby works To use a Ruby extension, you require it: require 'cgi' require 'REXML/Document' Extensions are basically just program files (or clusters of related program files that require each other) containing specialized code, dedicated to a particular area of programming. When you use, say, the CGI extension, as in the previous example, you immediately have access to a wide variety of programming commands and techniques designed to help you write CGI programs. (Ruby on Rails does this; you’ll see the line require 'cgi' in a number of the program files that make up the Rails package.) The purpose, as with any extension, is to save everyone a lot of trouble. Because all those CGI programming techniques are already available through a simple require command, everyone can use them. The alternative would be for everyone to write the code required to support those techniques, which would be difficult and a waste of time. Note that you say require 'cgi' , not require 'cgi.rb' . Aside from looking nicer, this bareword way of referring to the extension is necessary because not all extensions use files ending in .rb . Specifically, extensions written in C (more in the next section) are stored in files ending with .so or .dll . To keep the process transparent—that is, to save you the trouble of knowing whether the extension you want uses a .rb file or not—Ruby accepts a bareword and then does some automatic file-searching and trying out of possible filenames until it finds the file corresponding to the extension you have requested. NOTE EXTENSION OR LIBRARY? The broadest term for a collection of program- ming commands and techniques that you can pull into your own pro- gram via a require statement is library. The term extension is usually reserved for libraries that are distributed with Ruby, as opposed to those written by third-party programmers and made available to others for use in their applications. One exception is extensions to Ruby written in the C programming language—both those provided with Ruby and those written as add-ons—which are frequently referred to as extensions. 1.3.2 Using C extensions Some of the extensions that come with Ruby are written in Ruby. They use the techniques available in the core language to conjure up more layers of functional- ity and language features. Some extensions, however, are written in C. C exten- sions in the Ruby distribution include a socket-programming library (for network applications), a syslog (system logging) programming facility, and several libraries devoted to database handling. Ruby extensions and programming libraries 23 Some of these C extensions could have been written in Ruby. There are a cou- ple of reasons for writing them in C. The main reason is speed—execution speed, that is. Some C extensions have to be in C; their goal is to provide a bridge between Ruby and what’s already available to C programmers. They can’t be writ- ten in Ruby because they’re bringing these features to Ruby. The Ruby interpreter handles extensions in such a way that when you use one, you don’t have to worry about whether it was written in Ruby or C. You just require it require 'gdbm' and Ruby finds the files it needs to load, whether they are Ruby files or binary files produced during the compile process from C source files. 1.3.3 Writing extensions and libraries Many extensions and add-on libraries are bundled with the official distribution of the Ruby programming language and are installed on your system when you install Ruby. But anyone can write an extension or library. When you write Ruby code that lets you and other programmers do something new and valuable with Ruby, you’ve written an extension. Your code may not make it into the collection of extensions that comes with the Ruby language. But you can still make it available to other pro- grammers, thereby adding value to the Ruby programming environment. The difference between writing a library and breaking your program into mul- tiple files lies in what happens to your code. Do you use it in more than one pro- gram? Do other people use it? If so, then it’s reasonable to call it a library. The Rails framework is a library (really a bundle of interrelated libraries). As a Rails developer, you may or may not write Ruby libraries. But you can do so, and it’s not uncommon for Ruby programmers involved in diverse projects to release parts of what they’re working on as libraries and extensions useable by other programmers. TIP VISIT THE RUBY APPLICATION ARCHIVE AND RUBYFORGE If you’re inter- ested in seeing the kinds of Ruby projects that other Rubyists have made available, including applications as well as programming libraries and ex- tensions, the best places to look are the Ruby Application Archive ( RAA; http://raa.ruby-lang.org) and RubyForge (http://www.rubyforge.net). We’ll conclude this chapter with an examination of the Ruby programming envi- ronment: what comes with Ruby (including the source code for Ruby); where Ruby installs itself on your system; and what kinds of applications and program- ming facilities Ruby provides you. 24 CHAPTER 1 How Ruby works 1.4 Anatomy of the Ruby programming environment Installing Ruby on your system means installing numerous components of the lan- guage, possibly including the source code for the language, and definitely includ- ing a number of disk directories’ worth of Ruby-language libraries and support files. You won’t necessarily use everything in this section every time you write something in Ruby, but it’s good to know what’s there. Also, quite a few of the pro- gramming libraries that come bundled with Ruby are written in Ruby—so know- ing your way around the Ruby installation will enable you to look at some well- written Ruby code and (we hope) absorb some good habits. We’ll start with the Ruby source code. 1.4.1 The layout of the Ruby source code The Ruby source code directory (tree) contains the files that house the program code for the Ruby interpreter as well as a number of bundled add-ons. The core Ruby language is written in C, so in order to read and fully understand the files, you need to know C. But even if you don’t know C, you can learn a lot from perus- ing the comments and documentation contained in the source files. TIP MAKE SURE YOUR PACKAGE MANAGER GIVES YOU ALL OF RUBY If you in- stall Ruby via a remote package manager, you may not end up with the Ruby source on your machine. If that happens, and you want the source, check for a package named “ruby-source” or something similar. If there’s no such package, you can download the source from ruby-lang.org and un-tar it. See the book’s appendix for more information about installing Ruby and pointers on how to get platform-specific information. If you examine a directory listing of the top-level directory of the Ruby source tree, you’ll see the following: ■ Several subdirectories, including ext/ and lib/ (both discussed shortly) ■ Informational, legal, and license-related files (such as COPYING , GPL , and README ) ■ Files pertaining to the process of building and installing Ruby (all the con- fig* files, Makefile.in , install-sh , and so on) ■ C program and header files ( *.c and *.h ) Some of these files are only needed during the building of Ruby. Some of them are copied over directly when Ruby is installed. And, of course, the building process Anatomy of the Ruby programming environment 25 generates a number of new files (including ruby , the interpreter) that make their way onto your system permanently when you install Ruby. 1.4.2 Navigating the Ruby installation We’ll look at several of the subdirectories of the main Ruby installation to give you a general sense of what’s in them. This is just an overview. The best way—really, the only way—to get to know the Ruby installation layout and become comfort- able with it is to navigate around it and see what’s there. Before you can either navigate generally or pinpoint files specifically, you need to know where Ruby is installed on your system. The best way to find out is to ask Ruby. How to get Ruby to tell you where it’s installed Ruby is installed to directories with different names on different platforms and/or by different packaging systems. You can find out where the installation is on your system by using irb. First, start up irb with the -r flag, requiring the extension named rbconfig : $ irb -rrbconfig This command causes irb to preload some configuration information for your particular installation, including information about where various components of Ruby have been installed. To get the information, enter an expression like this into irb: irb(main):001:0> Config::CONFIG["bindir"] This request shows you the directory where the Ruby executable files (including ruby and irb ) have been installed; that’s the bindir . To get other information, you need to replace bindir in the irb command with other terms. But each time, you’ll use the same basic formula: Config::CONFIG["term"] . In each of the following sections, the section subtitle includes the term you need. Just plug that term into the irb command, and you’ll be shown the name of the directory. The extensions and libraries subdirectory (rubylibdir) Inside the rubylibdir (whatever that directory may be called on your system), you’ll find program files written in Ruby. These files provide standard library facil- ities, which you can require from your own programs if you need the functionality they provide. Here’s a sampling of the files you’ll find in this directory: [...]... INTO editions VALUES (2, 1,"Urtext","RubyTunes, Inc.", 1977, 23 .50); INSERT INTO editions VALUES (3,1,"ed Y.Matsumoto","RubyTunes, Inc.", 20 01, 22 .95); INSERT INTO editions VALUES (4 ,2, "","D Black Music House", 1995, 39.95); INSERT INTO editions VALUES (5 ,2, "Reprint of 1894 ed.", "RubyTunes, Inc.", 20 03, 35.95); NOTE You can download some sample or seed data from the Ruby for Rails Web site (http://www.manning.com/books/black),... Popular Web servers used with Rails include Apache, WEBrick (server written in Ruby and shipped with Ruby) , lightTPD Figure 2. 1 CGI Library CGI data processing routines Parses incoming form data Part of the Ruby standard library ERb "Embedded Ruby" Templating system for mixing static text with output from Ruby code Schematic view of Ruby and the Rails framework 2. 3 A Rails application walk-through... f This example runs Ruby with the debug extension loaded: $ ruby -rdebug c2fi.rb #1 Debug.rb Emacs support available c2fi.rb:3:print "Please enter a Celsius temperature: " (rdb:1) step Please enter a Celsius temperature: c2fi.rb:4:c = gets.to_i (rdb:1) step 25 c2fi.rb:5:f = (c * 9 / 5) + 32 (rdb:1) step c2fi.rb:5:f = (c * 9 / 5) + 32 (rdb:1) step c2fi.rb:6:puts f (rdb:1) v l c => 25 f => 77 (rdb:1)... archives of Ruby libraries Anatomy of the Ruby programming environment 27 The site _ruby directory parallels the main Ruby installation directory, in the sense that it has its own subdirectories for Ruby- language and C-language extensions (sitelibdir and sitearchdir, respectively, in Config terms) When you require an extension, the Ruby interpreter checks for it in these subdirectories of site _ruby as... to the Rails development environment, but we’ll go a lot further in the direction of writing actual code As you’ll see, the Ruby and Rails environments interact very effectively How Rails works This chapter covers ■ Overview of the Rails framework ■ Details of how Rails handles incoming requests ■ Domain modeling and database creation ■ A complete sample Rails application 33 34 CHAPTER 2 How Rails. .. it do the specific things you want NOTE GETTING RAILS AND RAILS INFORMATION This book’s appendix contains information about installing Rails and pointers on where to get more information You may be working on a system with Rails installed already; but if not, or if you want to make sure you have your finger on the pulse of the major sources of Rails information, look at the appendix The term framework... appendix for information about RubyGems.) Assuming a standard, default installation, you can find them like this: $ cd /usr/local/lib /ruby/ gems/1.8/gems $ ls Analyzing Rails implementation of MVC Table 2. 1 39 Overview of how Rails implements the MVC framework design MVC phase Rails sublibrary Purpose Model ActiveRecord Provides an interface and binding between the tables in a relational database and the Ruby. .. site _ruby; so, if you’ve found site _ruby, look at what else is installed next to it Inside the gems directory are one or more subdirectories; and if you explore these, you’ll find (possibly among other things) the source code for the Rails framework We’ll stop here, because the Rails source is a topic for later in the book (particularly for the last chapter, chapter 17) But you have a sense for where Ruby. .. main rubylibdir and the main archdir The gems directory This directory is a little different; it isn’t part of Ruby s internal configuration information because it’s for something that gets installed separately: the RubyGems packaging system But you’ll probably see it on any system with Rails installed, for the simple reason that the Rails framework is usually distributed and installed using the RubyGems... interactive Ruby interpreter, irb, for testing, learning, and playing with Ruby We then looked at Ruby extensions and libraries, including some specific example but focusing mainly on the mechanism for calling up extensions in your code (with require) This overview also included discussion of C extensions, which are often used for speed or for easy interaction with existing C libraries written outside of Ruby . is to find out the Ruby version number: $ ruby -v ruby 1.8 .2 (20 04- 12- 25) [i686-linux] (In this case, we’re using Ruby 1.8 .2, released on Christmas Day, 20 04, and com- piled for an i686-based. 1.6.8 (20 02- 12- 24) [i686-linux] -e:1: undefined method `lstrip' for " abc":String (NameError) $ ruby -ve 'puts " abc".lstrip' ruby 1.8 .2 (20 04- 12- 25) [i686-linux] abc The. temperature: c2fi.rb:4:c = gets.to_i (rdb:1) step 25 c2fi.rb:5:f = (c * 9 / 5) + 32 (rdb:1) step c2fi.rb:5:f = (c * 9 / 5) + 32 (rdb:1) step c2fi.rb:6:puts f (rdb:1) v l c => 25 f => 77 (rdb:1)

Ngày đăng: 06/08/2014, 09:20