[ contact ] [ home ] [ search ] [ submit link ] login | want to join? register in seconds!

home and garden
lawyers reviews
cosmetic surgery
cosmetic surgery cost / price site
channels:
hot tags: [all tags...]
hot tags(2): [all tags...]
[all tags...]
Learn Ruby on Rails the Ultimate Beginner s Guide Server Side Essentials
tech related articles:
0
vote!
Ruby - wprowadzenie - Rubedo: RazorJack technicznie (blog.razorjack.net)
crawler @ 04/02/07 19:51 comments(0) report
0
vote!
Ruby On Rails in Rails (www.rubyonrails.org)
crawler @ 04/03/07 10:17 comments(0) report
0
vote!
Hobo - the web app builder for Rails (hobocentral.net)
crawler @ 04/02/07 19:51 comments(0) report
0
vote!
Datetime Toolbocks - Intuitive Date Input Selection (datetime.toolbocks.com)
crawler @ 04/02/07 19:51 comments(0) report
0
vote!
Acts as Authenticated in Plugins (technoweenie.stikipad.com)
crawler @ 04/11/07 14:55 comments(0) report
0
vote!
Ruby Fleebie » 3 steps to understand how classes and objects work in ruby (www.rubyfleebie.com)
crawler @ 04/02/07 19:51 comments(0) report
Learn Ruby on Rails: the Ultimate Beginner's Guide [Server Side Essentials]
" Patrick has been developing web applications for ten years. Founder and lead developer of the freshmeat.net software portal, he and his Rails consultancy and application development company, "

" were responsible for a major relaunch of Germany's biggest infotainment community. Patrick lives in Wiesbaden, Germany. His weblog can be found at "

"While it certainly makes no attempt to constitute a complete guide to the Ruby language, this tutorial will introduce you to some of the basics of Ruby. We'll power through a crash-course in object oriented programming, covering the more common features of the language along the way, and leaving the more obscure aspects of Ruby for a "

". I'll also point out some of the advantages that Ruby has over other languages when it comes to developing applications for the Web."

"Some Rails developers suggest that it's possible to learn and use Rails without learning the Ruby basics first, but as far as I'm concerned, it's extremely beneficial to know even a little Ruby before diving into the guts of Rails. In fact, if you take the time to learn the Ruby basics first, you'll automatically become a better Rails programmer."

"That's what this tutorial is all about. In fact, this information is excerpted from my new book, "

", which is now available through sitepoint.com. The two chapters presented here get straight into the finer points of Ruby and Rails. If you need installation and other setup instructions, "

"In general, programming languages fall into one of two categories: they're either compiled languages or scripting languages. Let's explore what each of those terms means, and understand the differences between them."

"The language in which you write an application is not actually something that your computer understands. Your code needs to be translated into bits and bytes that can be executed by your computer. This process of translation is called compilation, and any language that requires compilation is referred to as a compiled language. Examples of compiled languages include C, C#, and "

"For a compiled language, the actual compilation is the final step in the development process. You invoke a compiler -- the software program that translates your final hand-written, human-readable code into machine-readable code -- and the compiler creates an executable file. This final product is then able to execute independently of the original source code."

"Thus, if you make changes to your code, and you want those changes to be incorporated into the application, you must stop the running application, recompile it, then start the application again."

"On the other hand, a scripting language such as Ruby, PHP, or Python, relies upon an application's source code all of the time. Scripting languages don't have a compiler or a compilation phase per se; instead, they use an interpreter -- a program that runs on the web server -- to translate hand-written code into machine-executable code on the fly. The link between the running application and your hand-crafted code is never severed, because that scripting code is translated every time it is invoked -- in other words, for every web page that your application renders."

"As you might have gathered from the name, the use of an interpreter rather than a compiler is the major difference between a scripting language and a compiled language."

"If you've come from a compiled-language background, you might be concerned by all this talk of translating code on the fly -- how does it affect the application's performance?"

"These concerns are valid -- translating code on the web server every time it's needed is certainly more expensive, performance-wise, than executing pre-compiled code, as it requires more effort on the part of your machine's processor. The good news is that there are ways to speed up scripted languages, including techniques such as code "

"There's also an upside to scripted languages in terms of performance -- namely, your performance while developing an application."

"Imagine that you've just compiled a shiny new Java application, and launched it for the first time ... and then you notice a typo on the welcome screen. To fix it, you have to stop your application, go back to the source code, fix the typo, wait for the code to recompile, and restart your application to confirm that it is fixed. And if you find another typo, you'll need to repeat that process again. Lather, rinse, repeat."

"In a scripting language, you can fix the typo and just reload the page in your browser -- no restart, no recompile, no nothing. It's as simple as that."

"Ruby, from its very beginnings, was built as a programming language that adheres to the principles of object oriented programming ("

"). Before getting into Ruby specifics, I'd like to introduce you to some fundamental concepts of OOP. Now I know that theory can seem a bit dry to those who are itching to start coding, but we'll cover a lot of ground in this short section, so don't skip it. This discussion will hold you in good stead -- trust me."

"OOP is a programming paradigm that first surfaced in the 1960s, but didn't gain traction until the 1980s with C++. The core idea behind it is that programs should be composed of individual entities, or objects, each of which has the ability to communicate with other objects around it. Additionally, each object may have the facility to store data internally, as depicted in Figure 3.1."

"Objects in an OOP application are often modeled on real-world objects, so even non-programmers can usually recognize the basic role that an object plays."

"And, just like the real world, OOP defines objects with similar characteristics as belonging to the same class. A class is a construct for defining properties for objects that are alike, and equipping them with functionality. For example, a class named Car might define the attributes color and mileage for its objects, and assign them functionality -- actions such as "open the trunk," "start the engine," and "change gears." These different actions are known as methods, although you'll often see Rails enthusiasts refer to the methods of a controller as "actions" -- you can safely consider the two terms to be interchangeable."

"Understanding the relationship between a class and its objects is integral to understanding how OOP works. For instance, one object can invoke functionality on another object, and can do so without affecting other objects of the same class. So, if one car object was instructed to open its trunk (think of KITT, the talking car from the classic 80s television show "Knight Rider," if it helps with the metaphor), then its trunk would open, but the trunk of other cars would remain closed. Similarly, if our high-tech talking car were instructed to change color to red, then it would do so, but other cars would not. (""

"" was a popular series in the 1980s that featured modern-day cowboy Michael Knight (played by David Hasselhoff) and his opinionated, talking, black Pontiac "

" named KITT. Having seen the show is not critical to understanding object oriented programming?just knowing that the car could talk will suffice!)"

"When we create a new object in OOP, we base it on an existing class. The process of creating new objects from a class is called instantiation. Figure 3.2 illustrates the concept."

"As I mentioned, objects can communicate with each other and invoke functionality (methods) on other objects. Invoking an object's methods can be thought of as asking the object a question, and getting an answer in return."

"Consider the example of our famous talking car again. Let's say we ask the talking car object to report its current mileage. This question is not ambiguous -- the answer that the object gives is called a return value, and is shown in Figure 3.3."

"In some cases, the question and answer analogy doesn't quite fit. In these situations, we might rephrase the analogy to consider the question to be an instruction, and the answer a status report indicating whether or not the instruction was executed successfully. This might look something like the diagram in Figure 3.4."

"Sometimes we need a bit more flexibility with our instructions. For example, if we wanted to tell our car to change gear, we need to tell it not only to change gear, but also which gear to change to. The process of asking these kinds of questions is referred to as passing an argument to the method."

"An argument is an input value that's provided to a method. An argument can be used in two ways:"

"An example is shown in Figure 3.5, where the method is "change gear," and the number of the gear to which the car must change (two) is the argument."

"A more general view of all of these different types of communication between objects is this: invoking an object's methods is accomplished by sending messages to it. As one might expect, the object sending the message is called the sender, and the object receiving the message is called the receiver."

"Armed with this basic knowledge about object oriented programming, let's look at some Ruby specifics."

"Learning the syntax of a new language has the potential to induce the occasional yawn. So, to make things more interesting, I'll present it to you in a practical way that lets you play along at home: we'll use the interactive Ruby shell."

"Windows users, don't forget to use the Open Ruby Console option from the Instant Rails control panel, to make sure the environment you're using contains the right settings."

"irb allows you to issue Ruby commands interactively, one line at a time. This is great for playing with the language, and it's also great for debugging, as we'll see in Chapter 11, Debugging, Testing, and Benchmarking."

"In this example, I've simply thrown the number 1 at the Ruby shell, and got back what appears to be the very same number."

"Looks can be deceiving, though -- it's actually not the very same number. What we were handed back is in fact a fully-featured Ruby object."

"Remember our discussion about object oriented programming in the previous section? Well, in Ruby, absolutely everything is treated as an object with which we can interact -- each object belongs to a certain class, therefore each object is able to store data and functionality in the form of methods."

"We touched on senders and receivers earlier. In this example, we've sent the class message to the "

" object is the receiver (there's no sender, as we're sending the message from the interactive command line rather than from another object). The value that's returned by the method we've invoked is "

"Since everything in Ruby (including a class) is an object, we can actually send the very same message to the "

" begins with a capital letter. A method in Ruby is always written in lowercase, whereas the first letter of a class is always capitalized."

"Getting used to thinking in terms of objects can take some time. Let's look at a few different types of objects, and see how we can interact with them."

"Literal objects are character strings or numbers that appear directly in the code, as did the number 1 that was returned in the previous section. We've seen numbers in action; next, let's look at a string literal."

"A string literal is an object that contains a string of characters, such as a name, an address, or an especially witty phrase. In the same way that we created the 1 literal object in the previous example, we can easily create a new string literal object, then send it a message. A string literal is created by enclosing the characters that make up the string in single or double quotes, like this:"

"This String object has a wealth of embedded functionality. For example, we can ascertain the number of characters that our string literal comprises by sending it the length message:"

"Every application needs a way to store information. Enter: variables and constants. As their names imply, these two data containers have their own unique roles to play."

"A constant is an object that's assigned a value once, and once only (usually when the application starts up). Constants are therefore used to store information that doesn't need to change within a running application. As an example, a constant might be used to store the version number for an application. Constants in Ruby are always written using uppercase letters, as shown below:"

"Variables, in contrast, are objects that are able to change at any time. They can even be reset to nothing, which frees up the memory space that they previously occupied. Variables in Ruby always start with a lowercase character:"

"There's one more special (and, one might say, evil) thing about a variable -- its scope. The scope of a variable is the part of the program to which a variable is visible. If you try to access a variable from outside its scope (i.e. from a part of an application to which that variable is not visible), you generally won't be able to."

"The notable exception to the rules defining a variable's scope are global variables. As the name implies, a global variable is "

" from any part of the program. While this might sound convenient at first, usage of global variables is discouraged -- the fact that they can be written to and read from any part of the program introduces security concerns."

"Let's return to the string literal example we saw earlier. Assigning a String to a variable allows us to invoke on that variable the same methods we invoked on the string literal earlier:"

" and PHP, so it can seem confusing at first if you're used to programming in those languages. However, once you have a few basics under your belt, punctuation in Ruby begins to feel quite intuitive and can greatly enhance the readability of your code."

"One of the most common punctuation characters in Ruby is the period (.). As we've seen, Ruby uses the period to separate the receiver from the message that's being sent to it, in the form "

"If you need to comment a line, either for documentation purposes or to temporarily take a line of code out of the program flow, use a hash mark (#). Comments may start at the beginning of a line, or they may appear further along, after some Ruby code:"

"Ruby doesn't require us to use any character to separate commands, unless we want to chain multiple statements together on a single line. In this case, a semicolon ("

") is used as the separator. However, if you put every statement on its own line (as we've been doing until now), the semicolon is completely optional."

"If you chain multiple statements together in the interactive shell, only the output of the last command that was executed will be displayed to the screen:"

" libraries out there, you might have run screaming from your computer when you saw all the parentheses that are involved in the "

"In Ruby, the use of parentheses for method calls is optional in cases in which no arguments are passed to the method. The following statements are therefore equal:"

"It's common practice to include parentheses for method calls with multiple arguments, such as the "

"Until now, we've looked at cases where Ruby uses less punctuation than its competitors. In fact, Ruby makes heavy use of expressive punctuation when it comes to the naming of methods."

"A regular method name, as we've seen, is a simple, alphanumeric string of characters. If a method has a potentially destructive nature (for example, it directly modifies the receiving object rather than changing a copy of it), it's commonly suffixed with an exclamation mark (!)."

"Punctuation is also used in the names of methods that return boolean values. A boolean value is a value that's either true or false; these values are commonly used as return values for methods that ask yes/no questions. Such methods end in a question mark, which nicely reflects the fact that they have yes/no answers:"

"These naming conventions make it easy to recognize methods that are destructive, and those that return boolean values, making your Ruby code more readable."

"Let's build on the theory that we covered at the start of this chapter as we take a look at Ruby's implementation of OOP."

"As we already know, the structure of an application based on OOP principles is focused on interaction with objects. These objects are often representations of real-world objects, like a Car. Interaction with an object occurs when we send it a message or ask it a question. If we really did have a "

"As I mentioned before, in contrast to other object oriented programming languages such as Python and PHP, in Ruby, everything is an object. Especially when compared with PHP, Ruby's OOP doesn't feel like a "tacked-on" afterthought -- it was clearly intended to be a core feature of the language from the beginning, which makes using the OOP features in Ruby a real pleasure."

"As we saw in the previous section, even the simplest of elements in Ruby (like literal strings and numbers) are objects to which you can send messages."

"As in any other OOP language, in Ruby, each object belongs to a certain class (for example, "

"). As we saw in the discussion at the beginning of this chapter, a class can group objects of a certain kind, and equip those objects with common functionality. This functionality comes in the form of methods, and in the object's ability to store information. For example, a "

"In Ruby, the instantiation of a new object that's based on an existing class is accomplished by sending that class the new message. The result is a new object of that class. The following few lines of code show an extremely basic class definition into Ruby -- the third line is where we create an instance of the class that we just defined."

"Another basic principle in OOP is encapsulation. According to this principle, objects should be treated as independent entities, each taking care of its own internal data and functionality. If we need to access an object's information -- for instance, its internal variables -- we make use of the object's interface, which is the subset of the object's methods that are made available for other objects to call."

"Ruby provides objects with functionality at two levels -- the object level, and class level -- and it adheres to the principle of encapsulation while it's at it! Let's dig deeper."

"At the object level, data storage is handled by instance variables (a name that's derived from the instantiation process mentioned above). Think of instance variables as storage containers that are attached to the object, but to which other objects do not have direct access."

"To store or retrieve data from these variables, another object must call an accessor method on the object. An accessor method has the ability to set (and get) the value of the object's instance variables."

"Let's look at how instance variables and accessor methods relate to each other, and how they're implemented in Ruby."

" objects are likely to differ, as each car will have a different mileage. Therefore, mileage is held in an instance variable."

"). And what's more, instance variables don't even need to be declared! There's only one problem: we don't have any way to retrieve or change them once they do exist. This is where instance methods come into play."

"Data storage and retrieval is not the only capability that can be bound to a specific object -- functionality, too, can be bound to objects. We achieve this binding through the use of instance methods, which are specific to an object. Invoking an instance method (in other words, sending a message that contains the method name to an object) will invoke that functionality on the receiving object only."

"Instance methods are defined using the def keyword, and end with the end keyword. Enter the following example into a new Ruby shell:"

" object instantiated from this class will (possibly using some fancy robotics connected to our Ruby program) open its trunk when its "

"While the indentation of code is a key element of the syntax of languages such as Python, in Ruby, indentation is purely cosmetic -- it aids readability, but does not affect the code in any way. In fact, while we're experimenting with the Ruby shell, you needn't be too worried about indenting any of the code. However, when we're saving files that will be edited later, you'll want the readability benefits that come from indenting nested lines."

"The Ruby community has agreed upon two spaces as being optimum for indenting blocks of code such as class or method definitions. We'll adhere to this indentation scheme throughout this book."

"Since we don't want the trunks of all cars to open at once, we've made this functionality available as an instance method."

"I know, I know: we still haven't modified any data. We use accessor methods for this task."

"An accessor method is a special type of instance method, and is used to read or write to an instance variable. There are two types: readers (sometimes called "getters") and writers (or "setters")."

"A reader method will look inside the object, fetch the value of an instance variable, and hand this value back to us. A writer method, on the other hand, will look inside the object, find an instance variable, and assign the variable the value that it was passed."

" objects. Once again, exit from the Ruby shell so that we can create an entirely new "

" class definition. Our class definition is getting a bit longer now, so enter each line carefully. If you make a typing
... read the whole article


comments:(log in to vote on this article or comment on it)