-
Notifications
You must be signed in to change notification settings - Fork 3
/
what-is-ruby-rails.html
279 lines (279 loc) · 53 KB
/
what-is-ruby-rails.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
<!DOCTYPE html>
<!--[if IE 9]><html class="lt-ie10" lang="en" > <![endif]-->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>What is Ruby on Rails? · RailsApps</title>
<meta name="viewport" content="width=device-width">
<link href="https://plus.google.com/117374718581973393536" rel="publisher">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/foundation/5.2.2/css/normalize.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/foundation/5.2.2/css/foundation.min.css">
<link rel="stylesheet" href="http://railsapps.github.io/css/railsapps.css" />
<link rel="stylesheet" href="http://railsapps.github.io/css/syntax.css" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.6.2/modernizr.min.js"></script>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="http://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
<script type="text/javascript">
window.analytics=window.analytics||[],window.analytics.methods=["identify","group","track","page","pageview","alias","ready","on","once","off","trackLink","trackForm","trackClick","trackSubmit"],window.analytics.factory=function(t){return function(){var a=Array.prototype.slice.call(arguments);return a.unshift(t),window.analytics.push(a),window.analytics}};for(var i=0;i<window.analytics.methods.length;i++){var key=window.analytics.methods[i];window.analytics[key]=window.analytics.factory(key)}window.analytics.load=function(t){if(!document.getElementById("analytics-js")){var a=document.createElement("script");a.type="text/javascript",a.id="analytics-js",a.async=!0,a.src=("https:"===document.location.protocol?"https://":"http://")+"cdn.segment.io/analytics.js/v1/"+t+"/analytics.min.js";var n=document.getElementsByTagName("script")[0];n.parentNode.insertBefore(a,n)}},window.analytics.SNIPPET_VERSION="2.0.9",
window.analytics.load("l1stqfqqbf");
window.analytics.page();
window.analytics.ready(function () {
ga('require', 'linker');
ga('linker:autoLink', ['railscomposer.com','learn-rails.com','blog.railsapps.org','tutorials.railsapps.org']);
});
</script>
</head>
<body>
<div class="fixed">
<nav class="top-bar" data-topbar>
<ul class="title-area">
<li class="name">
<a href="http://railsapps.github.io/" class="brand">RailsApps Project</a>
</li>
<li class="toggle-topbar menu-icon"><a href="#"><span>Menu</span></a></li>
</ul>
<section class="top-bar-section">
<ul class="right">
<li><a href="https://tutorials.railsapps.org/" class="google">Tutorials</a></li>
<li><a href="http://twitter.com/rails_apps" class="twitter">Twitter</a></li>
<li><a href="http://blog.railsapps.org/" class="twitter">Blog</a></li>
<li><a href="https://github.com/RailsApps" class="github">GitHub Repository</a></li>
</ul>
</section>
</nav>
</div>
<div class="row">
<div class="large-12 columns">
<div class="content wikistyle gollum textile">
<h1>What is Ruby on Rails?</h1>
<h4>by Daniel Kehoe</h4>
<p><em>Last updated 11 October 2013</em></p>
<p>In-depth primer on Ruby and Rails, “What is Ruby on Rails?” Explains what is important about Ruby and Rails.</p>
<p>This article introduces basic concepts of web development, explains why Ruby on Rails is a popular framework for web development, and looks at Rails from several perspectives so you’ll be prepared to learn more about Rails. You don’t need a technical background to read this article. Technical terms are introduced and explained in easy-to-understand language. If you are an experienced web developer, you’ll get an introduction to the specifics of Rails, with fundamental concepts explained systematically and comprehensively.</p>
<h3>
<a href="http://learn-rails.com/learn-ruby-on-rails.html"><img src="http://railsapps.github.io/images/learn-rails-cover-130x161.jpg" title="Learn Ruby on Rails" alt="Learn Ruby on Rails"></a> Get the Book</h3>
<p>New to Rails? Get the book <a href="http://learn-rails.com/learn-ruby-on-rails.html">Learn Ruby on Rails</a>.</p>
<h2>Ruby</h2>
<p>Ruby is a programming language. It was created 20 years ago by Yukihiro “Matz” Matsumoto. By most measures of programming language popularity, Ruby <a href="https://sites.google.com/site/pydatalog/pypl/PyPL-PopularitY-of-Programming-Language">ranks among the top ten</a>, though usually as tenth (or so) in popularity, and largely due to the popularity of Rails. Like Java or the C language, Ruby is a general-purpose programming language, though it is best known for its use in web programming.</p>
<h2>Rails</h2>
<p>Rails is a software library that extends the Ruby programming language. David Heinemeier Hansson is its creator. He gave it the name “Ruby on Rails,” though it is often just called “Rails.”</p>
<p>It is software code that is added to the Ruby programming language. Technically, it is a <a href="http://en.wikipedia.org/wiki/Package_manager">package library</a> (specifically, a <a href="http://en.wikipedia.org/wiki/Rubygem">RubyGem</a>), that is installed using the operating system <a href="http://en.wikipedia.org/wiki/Command-line_interface">command-line interface</a>.</p>
<p>Rails is a framework for building websites. As such, Rails establishes conventions for easier collaboration and maintenance. These conventions are codified as the Rails <span class="caps">API</span> (the <a href="http://en.wikipedia.org/wiki/Application_programming_interface">application programming interface</a>, or directives that control the code). The Rails <span class="caps">API</span> is documented <a href="http://api.rubyonrails.org/">online</a> and described in books, articles, and blog posts. Learning Rails means learning how to use the Rails conventions and its <span class="caps">API</span>.</p>
<p>Rails combines the Ruby programming language with <span class="caps">HTML</span>, <span class="caps">CSS</span>, and JavaScript to create a <a href="http://en.wikipedia.org/wiki/Web_application">web application</a> that runs on a web server. Because it runs on a web server, Rails is considered a server-side, or “back end,” <a href="http://en.wikipedia.org/wiki/Web_application_framework">web application development platform</a> (the web browser is the “front end”). Later, this article will describe web applications in greater depth and show why a web development framework is needed to build complex websites.</p>
<p>Rails, in a larger sense, is more than a software library and an <span class="caps">API</span>. Rails is the central project of a vast community that produces software libraries that simplify the task of building complex websites. Members of the Rails community share many core values, often use the same tools, and support each other with an informal network that is built on volunteerism. Overlapping the informal community is an economic network that includes jobs, recruiters, consulting firms, conferences, businesses that build websites with Rails, and investors that fund startups. Rails is popular among web startups, significantly because the pool of open source software libraries (RubyGems, or “gems”) makes it possible to build complex sites quickly.</p>
<p>Read on for a more detailed look at Rails. First, we’ll look at why Rails uses the Ruby programming language. We’ll consider why Rails is popular, review some basic concepts, then look at Rails from six different perspectives to understand it better.</p>
<h2>Why Ruby?</h2>
<p>In a podcast from <a href="http://thisdeveloperslife.com/post/1-0-5-homerun">This Developer’s Life</a> and in an <a href="http://www.oreillynet.com/network/2005/08/30/ruby-rails-david-heinemeier-hansson.html">interview from 2005</a>, David Heinemeier Hansson, the creator of Rails, describes building an online project management application named BaseCamp in 2004. He had been using the <span class="caps">PHP</span> programming language because he could get things done quickly but was frustrated because of a lack of abstraction and frequently repetitive code that made <span class="caps">PHP</span> “dirty.” Hansson wanted to use the “clean” software enginering abstractions supported in the Java programming language but found development in Java was cumbersome. He tried Ruby and was excited about the ease of use (he calls it pleasure) he found in the Ruby language.</p>
<p>Ruby is known among programmers for a terse, uncluttered syntax that doesn’t require a lot of extra punctuation. Compared to Java, Ruby is streamlined, with less code required to create basic structures such as data fields. Ruby is a modern language that makes it easy to use high-level abstractions such as metaprogramming. In particular, metaprogramming makes it easy to develop a “domain specific language” that customizes Ruby for a particular set of uses (Rails and many gems use this “<span class="caps">DSL</span>” capability).</p>
<p>Ruby’s key advantage is RubyGems, the package manager that makes it easy to create and share software libraries (gems) that extend Ruby. RubyGems provides a simple system to install gems. Anyone can upload a gem to the central <a href="https://rubygems.org/">RubyGems website</a>, making the gem immediately available for installation by anyone. The RubyGems website is where you’ll obtain the most recent version of Rails. And it is where you will obtain all the gems that help you build complex websites.</p>
<p>Ruby has several disadvantages (at least when programmers want to argue). Its processing performance is slow relative to C++ or Java. The execution speed of a language is seldom important, though, relative to the benefits gained by programmer productivity and the general level of performance required by most websites. For websites that require lots of simultaneous activity, Ruby is not well-suited to the sophisticated software engineering required to execute simultaneous activity efficiently (standard Ruby lacks “parallelism”, though some versions support it). Lastly, some programmers complain that Ruby programs (and especially Rails) contain “too much magic” (that is, complex operations that are hidden behind simple directives). These concerns haven’t stopped Rails from becoming a popular web development platform.</p>
<h4>Do You Need to Study Ruby to Learn Rails?</h4>
<p>Let’s digress for a moment. If you are reading this because you want to learn Rails, you may want to know if you must learn the Ruby programming language before learning Rails.</p>
<p>The short answer is “no,” with one caveat. To avoid feeing overwhelmed when you first begin learning Rails, it is advisable to spend at least an hour with an introduction to Ruby so you are comfortable with the syntax of the language. You should be prepared to recognize correct formatting when you type Ruby code in your text editor. You can find several good online tutorials listed on the <a href="http://railsapps.github.io/ruby-and-rails.html">Ruby and Rails</a> resource page. Get started with a quick lesson from <a href="http://rubymonk.com/">RubyMonk</a> or <a href="http://tryruby.org/">Try Ruby</a>.</p>
<p>Be assured that you will indeed learn Ruby as you develop proficiency with Rails. Whether you study Ruby or not, you’ll develop Ruby skills as you learn Rails. Rails is largely a “domain specific language” that has its own set of directives distinct from the Ruby core. As you learn the Rails “language” you’ll be using the Ruby language syntax.</p>
<p>Your hardest challenge will be to learn the names of the structures you see in code examples. This is why it is helpful to work your way through a short introduction to Ruby. You’ll need to be able to recognize when you are looking at an array or a hash. You should recognize when you are looking at an iterator or the Ruby block syntax. Eventually, you’ll recognize more exotic Ruby formulations such as the lambda. It is okay if you can’t write a lambda function or even know when to use one; many Rails developers start work before learning Ruby thoroughly.</p>
<p>As experienced Rails developers, we hope you will make an effort to learn Ruby as you learn Rails. Don’t be lazy; when you encounter a bit of Ruby you don’t understand, make an effort to find out what is going on. Spend time with a Ruby textbook or interactive course as you get more proficient with Rails. By all means, if you love the precision and order of programming languages, dive into the study of Ruby from the beginning. But don’t delay starting Rails while you learn Ruby; realistically, you’ll retain more knowledge of Ruby if you learn it as you build things in Rails.</p>
<h2>Why Rails?</h2>
<p>Rails is popular and widely used because its conventions are pervasive and astute. Any web application has complex requirements that include basic functions such as generating <span class="caps">HTML</span>, processing form submissions, or accessing a database. Without a web application development framework, a programmer has a mammoth task to implement all the required infrastructure. Even with a web application development framework, a programmer can take an idiosyncratic approach, building something that no one else can easily take apart and understand. The singular virtue of Rails is that Heinemeier Hansson, and the core team that joined him, decided that there is one best way to implement much of the infrastructure required by a web application. Many of the implementation decisions appear arbitrary. In fact, though Heinemeier Hansson is often lambasted as autocratic in his approach to improving Rails, the Rails <span class="caps">API</span> reflects deep experience and intelligence in implementing the requirements of a web application development framework. The benefit is that every developer who learns the “Rails way” produces a web application that any other Rails developer can unravel and understand more quickly than if they encountered idiosyncratic code without as many conventions. That means collaboration is easier, development is quicker, and there’s a larger pool of open source libraries to enhance Rails.</p>
<p>The advantage of establishing conventions might seem obvious, but when Rails was released in 2004, web development was dominated by <span class="caps">PHP</span>, which lent itself to idiosyncratic code produced by solo webmasters, and Java frameworks such as Struts, which were often seen as burdened by an excess of structure. Other frameworks, such as Apple’s WebObjects, Adobe’s ColdFusion, and Microsoft’s .<span class="caps">NET</span> Framework, were in wide use but the frameworks were products controlled by the companies and built by small teams, which tended to restrict innovation. Today <span class="caps">PHP</span>, Java frameworks, and .<span class="caps">NET</span> remain popular, largely among solo webmasters (<span class="caps">PHP</span>), enterprise teams (Java), and Windows aficionados (.<span class="caps">NET</span>) but Rails has become very popular and has influenced development of other server-side frameworks.</p>
<p>The design decisions that went into the first version of Rails anchored a virtuous circle that led to Rails’s growth. Within the first year, Rails caught the attention of prominent software engineers, notably Martin Fowler and Dave Thomas (proponents of <a href="http://en.wikipedia.org/wiki/Agile_software_development">agile software development</a> methodologies). Rails is well-matched to the practices of agile software development, particular in its emphasis on software testing and “convention over configuration.” The interest and advocacy of opinion leaders from the agile camp led to greater visibility in the wider open source community, culminating in a <a href="http://itc.conversationsnetwork.org/shows/detail658.html">keynote lecture by Heinemeier Hansson</a> at the 2005 O’Reilly Open Source Convention. Because Rails was adopted by software engineers who are influencers and trend setters, it is often said that Rails is favored by “the cool kids.” If that is so, it is largely because Rails is well-suited to software engineering practices that are promoted by thought leaders like Fowler and Thomas.</p>
<h2>Understanding Rails Guiding Principles</h2>
<p>The popularity of Rails is an outgrowth of the Rails “philosophy” or guiding principles.</p>
<h4>Rails is Opinionated</h4>
<p>In the mid-1990s, web applications were often written in Perl, a programming language that promised, “There’s more than one way to do it.” Perl is a prime example of “non-opinionated” software; there’s no “right way” or “best way” to solve programming problems in Perl. Famously, Perl’s <a href="http://perldoc.perl.org/perlfunc.html">documentation</a> states, “In general, [Perl’s built-in functions] do what you want, unless you want consistency.”</p>
<p>In contrast, Rails is said to be “opinionated.” There is a “Rails way” for many of the problems that must be solved by a web application developer. If you follow the Rails conventions, you’ll have fewer decisions to make and you’ll find more of what you need is already built. The benefit is faster development, improved collaboration, and easier maintenance.</p>
<h4>Rails is Omakase</h4>
<p>Omakase is a Japanese phrase that means “I’ll leave it to you.” Customers at sushi restaurants can order <em>omakase</em>, entrusting the chef to make a pleasing selection instead of making their own à la carte choices. In a famous essay Heinemeier Hansson declared <a href="http://david.heinemeierhansson.com/2012/rails-is-omakase.html">Rails is Omakase</a>, and said, “A team of chefs picked out the ingredients, designed the APIs, and arranged the order of consumption on your behalf according to their idea of what would make for a tasty full-stack framework…. When we, or in some cases I — as the head chef of the omakase experience that is Rails — decide to include a dish, it’s usually based on our distilled tastes and preferences. I’ve worked in this establishment for a decade. I’ve poured well in the excess of ten thousand hours into Rails. This doesn’t make my tastes right for you, but it certainly means that they’re well formed.”</p>
<p>Understanding that Rails is omakase means accepting that many of the opinions enshrined in the Rails <span class="caps">API</span> are the decisions of a <a href="http://en.wikipedia.org/wiki/Benevolent_Dictator_for_Life">Benevolent Dictator for Life</a>, informed by discussion with other developers who have made significant contributions to the Rails code base. For the most part, Heinemeier Hansson’s “opinions” will serve you well.</p>
<h4>Convention Over Configuration</h4>
<p>“Convention over configuration” is an example of Rails as “opinionated software.” It is an extension of the concept of a default, a setting or value automatically assigned without user intervention. Some software systems, notably Java web application frameworks, need multiple configuration files, each with many settings. For example, a configuration file might specify that a database table named “sales” corresponds to a class named “Sales.” The configuration file permits flexibility (a developer can easily change the setting if the table is named “items_sold”). Instead of relying on extensive configuration files, Rails makes assumptions. By convention, if you create a model object in Rails named “User,” it will save data to a database table named “users” without any configuration required. Rails will also assume the table name is plural if the class name is singular.</p>
<p>“Convention over configuration” means you’ll be productive. You won’t spend time setting up configuration files. You’ll spend less time thinking about where things go and what names to assign. And, because other developers have learned the same conventions, it is easier to collaborate.</p>
<h4>Don’t Repeat Yourself</h4>
<p>Known by the acronym <span class="caps">DRY</span>, “Don’t Repeat Yourself” is a principle of software development formulated by Andy Hunt and Dave Thomas and widely advocated among Rails developers. In its simplest form, it is an admonition to avoid duplication. When code is duplicated, an application becomes more complex, making it more difficult to maintain and more vulnerable to unintended behavior (bugs). The <span class="caps">DRY</span> principle can be extended to development processes as well as code. For example, manual testing is repetititive; automated testing is <span class="caps">DRY</span>. Software design patterns that introduce abstraction or indirection can make code more <span class="caps">DRY</span>; for example, by eliminating repetitive <em>if-then</em> logic.</p>
<p>Code reuse is a fundamental technique in software development. It existed long before Andy Hunt and Dave Thomas promoted the <span class="caps">DRY</span> principle. Rails takes advantage of Ruby’s metaprogramming features to not just reuse code but eliminate code where possible. With a knowledge of Rails conventions, it’s possible to create entire simple web applications with only a few lines of code.</p>
<h2>Where Rails Gets Complicated</h2>
<p>It helps to understand the guiding principles of Rails. But it’s even more helpful to know how (and why) Rails is complicated by departures from the guiding principles.</p>
<h4>When Rails has No Opinion</h4>
<p>As you gain experience with Rails, you may encounter areas where Rails doesn’t state an opinion. For example, as of early 2013, there is no “official” approach to queueing background jobs. (Tasks that take time, such as contacting a remote server, are best handled as “background jobs” that won’t delay display of a web page.) Much of the lively debate that drives development of new versions of Rails is focused on thrashing out the “opinions” that eventually will be enshrined in the Rails <span class="caps">API</span>.</p>
<h4>Omakase But Substitutions Are Allowed</h4>
<p>Implicit in the notion of “Rails is omakase” is an understanding that “substitutions are allowed.” Most of Heinemeier Hansson’s preferences are accepted by all Rails developers. However, many experienced developers substitute items on the menu at the Rails café. This has led to the notion that <a href="http://words.steveklabnik.com/rails-has-two-default-stacks">Rails has Two Default Stacks</a>, as described in an essay by Steve Klabnik. Professional developers often substitute an alternative testing framework or use a different syntax for creating page views than the “official” version chosen by Heinemeier Hansson. This complicates learning because introductory texts often focus on the omakase selections but you’ll encounter alternatives in blog posts and example code.</p>
<h4>Conventions or Magic?</h4>
<p>One of the joys of programming is knowing that everything that happens in an application is explained by the code. If you know where to look, you’ll see the source of any behavior. For a skilled programmer, “convention over configuration” adds obscurity. Without a configuration file, there is no obvious code that reveals that data from a class named “Person” is saved to a datatable named “people.” As a beginner, you’ll simply accept the magic and not confound yourself trying to find how it works. It’s not always easy to learn the conventions. For example, you may have a User object and a “users” datatable. Rails will also expect you to create a “controller object.” Should it be named “UserController” (singular) or “UsersController” (plural)? You’ll only know if you let Rails generate the code or you pay close attention to tutorials and example code.</p>
<h4>
<span class="caps">DRY</span> to Obscurity</h4>
<p>The risk that “convention over configuration” leads to obscurity is compounded by the “Don’t Repeat Yourself” principle. To avoid repetitive code, Rails often will offer default behavior that looks like magic because the underlying implementation is hidden in the depths of the Rails code library. You can implement a simple web application with only a few lines of custom code but you may wonder where all the behavior comes from. This can be frustrating when, as a beginner, you attempt to customize your application to do more than what’s shown in simple tutorials.</p>
<h2>How Rails Works</h2>
<p>With an understanding in place of the Rails guiding principles and its challenges, let’s start from scratch to get a clear picture of how Rails works. We’ll start by explaining how a web application is used to create a website. You may already know most of this, but let’s review because it will help explain how Rails works.</p>
<p>You’re running a web browser on your computer (probably to read this article). A web browser combines three kinds of files—<span class="caps">HTML</span>, <span class="caps">CSS</span>, and JavaScript—to display web pages. A browser obtains the files from a web server. The web server can be remote (connected by the Internet) or on your own computer (when you are doing development).</p>
<p>You might have learned how to create <span class="caps">HTML</span>, <span class="caps">CSS</span>, and JavaScript files. <span class="caps">HTML</span> (<a href="http://en.wikipedia.org/wiki/HTML">HyperText Markup Language</a>) is a convention for creating structured documents that combine content (such as text, images, or video) with generic typographic, layout and design elements (such as headlines and tables). <span class="caps">CSS</span> (<a href="http://en.wikipedia.org/wiki/Cascading_Style_Sheets">Cascading Style Sheets</a>) directives apply a specific appearance to typographic, layout and design elements. <a href="http://en.wikipedia.org/wiki/JavaScript">JavaScript</a> is a programming language supported by all web browsers that is used to manipulate <span class="caps">HTML</span> and <span class="caps">CSS</span> elements, particularly for implementing interactive features such as tabs and modal windows. You can learn about <span class="caps">HTML</span>, <span class="caps">CSS</span>, and JavaScript in a typical “Introduction to Web Design” course that teaches how to make “static websites.”</p>
<p>Web servers deliver <span class="caps">HTML</span>, <span class="caps">CSS</span>, and JavaScript, either from static files that are stored on the server, or from an “application server” that creates files dynamically using a programming language such as Ruby. A software program written in Ruby and organized using Rails conventions is a “web application.” Rails combines the Ruby programming language with <span class="caps">HTML</span>, <span class="caps">CSS</span>, and JavaScript to create a web application. Rails uses Ruby to dynamically assemble <span class="caps">HTML</span>, <span class="caps">CSS</span>, and JavaScript files from component files (often adding content from a database).</p>
<p>Why create a web application? A web browser needs only a single <span class="caps">HTML</span> file to display a web page (<span class="caps">CSS</span> and JavaScript files are optional). However, if you are creating several web pages, you might want to assemble the <span class="caps">HTML</span> file from smaller components. For example, you might make a small file that will be included on every page to make a footer (Rails calls these “partials”). Consider another example: If you are displaying content from a database, you might not want the complex programming code that accesses the database mixed into your <span class="caps">HTML</span> (programmers call this <a href="http://en.wikipedia.org/wiki/Separation_of_concerns">separation of concerns</a> and it makes for more modular, maintainable programs). Finally, if you are using a web application server such as the one supplied with Rails, you can add features to your website that have been developed and tested by other people so you don’t have to build everything yourself. These are all reasons to create a web application.</p>
<p>Now that you’ve seen how Rails combines the Ruby programming language with <span class="caps">HTML</span>, <span class="caps">CSS</span>, and JavaScript to create a web application, we can examine Rails more closely.</p>
<h2>Six Perspectives On a Rails Application</h2>
<p>To understand Rails, let’s take a look at different aspects of a Rails web application.</p>
<p>Like the blind men encountering the elephant, you’ll understand Rails better by examining it from six different perspectives.</p>
<h3>Web Browser’s Perspective</h3>
<p>As we’ve seen, from the perspective of the web browser, Rails is simply a program that generates <span class="caps">HTML</span>, <span class="caps">CSS</span>, and JavaScript files. These files are generated dynamically. You can’t see them on the server side but you can view these files by using the web developer tools that are built in to every browser (choose the menu item “Web Developer Tools” in Google Chrome or “Web Developer Toolbar” in Firefox).</p>
<h3>Coder’s Perspective</h3>
<p>What do you see on your computer if you are looking at a Rails application?</p>
<p>You’ll see a set of files that you can edit with your text editor to create your web application. The files are organized with a specific structure. The structure is the same for every Rails application; this commonality is what makes it easy to collaborate with other Rails developers. To use Rails, you must learn about this structure and the purpose of each of the folders and files.</p>
<p>Here is how Rails files are organized:</p>
<pre>
+-app
| +-assets
| | +-images
| | +-javascripts
| | +-stylesheets
| +-controllers
| +-helpers
| +-mailers
| +-models
| +-views
+-config
+-db
+-features
+-lib
+-log
+-public
+-script
+-spec
</pre>
<p>The Rails file structure exists for the convenience of developers. “Assets” such as images, <span class="caps">CSS</span> stylesheet files, and JavaScript files get their own folders. Other folders are a place for configuration files (“config”) and testing files (“features” and “spec”) As you investigate the Rails file structure, you’ll see other folders that don’t have an evident purpose. For example, the folders for “controllers,” “models,” and “views” are important but may not have an obvious function. These folders correspond to a more abstract organizational system, one imposed by software architecture.</p>
<p>From a coder’s perspective, we can say that Rails is a set of files organized in a specific way. We use text editors to edit the files to make a web application. But what’s in the files?</p>
<h3>Software Architect’s Perspective</h3>
<p>The contents of the files (particularly the files written in the Ruby language) are organized according to a higher level abstraction we call “software architecture.”</p>
<p>Software is purely conceptual; it takes shape as text files but it comes into being in the mind of programmers. Aside from certain features that are required by computer design (programs must read strings of characters from filesystems), a software program can be a conceptual abstraction that is absolutely unique to the mind of its creator. In practice, most programming languages impose a standard set of abstractions that reflect the common needs of most programmers. We keep lists with an abstraction we call an array; we perform an operation on each element of an array with an abstraction we call an iterator. Every programming language documents these basic abstractions in a language reference (for example, see the <a href="http://www.ruby-doc.org/">Ruby <span class="caps">API</span></a>).</p>
<p>In Ruby (as in many other <a href="http://en.wikipedia.org/wiki/Object-oriented_programming">object-oriented</a> languages), an “object” is the fundamental abstraction which is the basis for all other abstractions. Ruby tutorials say, “In Ruby, everything is an object,” and then show that all objects have <a href="http://en.wikipedia.org/wiki/State_(computer_science)">state</a> (data or “attributes”), behavior (procedures or “methods”), and identity (unique existence among all other objects). Objects are described with a <a href="http://en.wikipedia.org/wiki/Class_(computer_programming)">class</a> definition that describes attributes and methods; objects are used by a program as <a href="http://en.wikipedia.org/wiki/Instance_(computer_science)">instances</a> that have identical methods but differing data. Ruby provides a standard syntax for defining classes, creating instances, and calling methods.</p>
<p>At a higher level of abstraction, programmers find that code can be often be optimally organized according to patterns that other experienced developers will recognize. Code is easier to write when it fits a pattern you’ve encountered before; it’s easier to analyze and understand code that another programmer has written if it matches a widely known <a href="http://en.wikipedia.org/wiki/Software_pattern">software design pattern</a>. One example is the <a href="http://en.wikipedia.org/wiki/Model%E2%80%93View%E2%80%93Controller">Model–view–controller</a> pattern that is fundamental to organizing Rails applications. Though the <span class="caps">MVC</span> pattern is enshrined in the file structure of a Rails application, it also exists in the form of a hierarchy of Rails classes, notably ActionController (controller), ActionView (view), and ActiveRecord (model), which are Objects that can be subclassed to be used as components of your web application.</p>
<p>From the perspective of a software architect, a Rails web application is organized as a hierarchy of classes defined by the <a href="http://api.rubyonrails.org/">Rails <span class="caps">API</span></a>.</p>
<h3>Time Traveler’s Perspective</h3>
<p>So far, we’ve seen how a web application is organized from the perspective of a web browser, the filesystem, and software architecture. There’s a temporal perspective that is just as important. Every software development project has this temporal aspect; it’s not unique to Rails, but it’s important to understand if you are going to do development with Rails.</p>
<p>A web application is developed over time; often we make mistakes and need to roll back to a previous version of our work. Computers are data storage machines as much as they are machines for manipulating or communicating data. However, the original concept of a computer file system didn’t allow for travel backward in time; files in disk storage preserve only the most recent version of your work. As programmers, we’ve had to add <a href="http://en.wikipedia.org/wiki/Revision_control">version control systems</a> (sometimes known as revision control or source control systems) to recover earlier versions of our work.</p>
<p>There are several popular revision control systems; <a href="http://en.wikipedia.org/wiki/Git_(software)">git</a> is used most often by Rails developers. The metaphor of computer folders and files is easy to understand, at least for people who have worked where 20th century office supplies are still used. Git doesn’t offer any similar real-world metaphor which means it is much more difficult to understand how it works. Nonetheless, you must learn to use git if you intend to build more than the simplest Rails application.</p>
<p>Superficially, you can think of git as a series of snapshots of the your project’s filesystem. You can save a snapshot at any time with a “git commit” command in the Terminal. Then you can recover files from that snapshot.</p>
<p>Git is important not just for backing up and recovering files (after all, backup software such as Apple’s Time Machine can do that). You can use git with <a href="https://github.com/">GitHub</a> for remote backup of your projects. More importantly, git and GitHub are the primary mechanisms for collaborating on Rails application development, whether open source or proprietary projects. You will use git and GitHub constantly on any real-world Rails project.</p>
<p>Strictly speaking, git and GitHub are not part of Rails (they are tools that can be used on any development project). But Rails and the gems that go into a complex web application would not exist without git and GitHub so it’s important to recognize the essential role of these tools as part of a Rails project.</p>
<p>From the time traveler’s perspective, we can say that a Rails project is a series of snapshots of files stored in a git repository.</p>
<h3>Gem Hunter’s Perspective</h3>
<p>You read earlier that Ruby’s key advantage is RubyGems, the package manager that makes it easy to create and share software libraries (gems) that extend Ruby. Rails is popular because developers have written and shared so many gems that provide useful features for building websites.</p>
<p>We can think of a Rails application as a collection of gems that provide basic functionality, plus custom code that adds unique features for a particular website. In fact, when a developer begins work on an existing Rails web project, he or she will often first investigate what gems are used by the application.</p>
<p>Every Rails application has a Gemfile in the application root directory. The Gemfile lists each gem that is used by the application. The Gemfile is used by a utility program (named Bundler) that adds each gem to the Ruby programming environment. Some gems are required by every Rails application, for example, a database adaptor that allows Rails to connect to databases. Other gems are used to make development easier, for example, gems for testing that help programmers find bugs. Still other gems add functionality to the website, such as gems for logging in users or processing credit cards.</p>
<p>The art of selecting gems is one of the skills of an experienced Rails developer. There are gems that are recommended by Rails original creators (notably, David Heinemeier Hansson). Skilled developers often replace these “official” gems with alternative sets of gems that have gained popularity more recently. Knowing what gems to use, or why, is an aspect of learning Rails that is seldom explicit.</p>
<p>As you learn more about Rails, you’ll learn about the gems that are most frequently added to Rails projects.</p>
<h3>Tester’s Perspective</h3>
<p>Among development platforms for the web, Rails uniquely includes a “baked-in” test framework. This reflects the platform creator’s commitment to a methodology of software development known as <em>Test Driven Development</em> (<span class="caps">TDD</span>). Though test driven development is optional, not required, for any Rails development project, it is so often used (and expected) that we can’t fully understand Rails without considering the tester’s perspective.</p>
<p>Software is always tested. Sometimes only by its users (who don’t know they are guinea pigs) but more often (and more responsibly), before it is released. Historically, on large corporate software projects, a quality assurance process might involve a team of engineers systematically testing every feature of a software product from the point of view of the user. To the QA team, <em>integration testing</em> meant every component was tested to work when assembled together. <em>Acceptance testing</em>, which can be the same as integration testing, meant the team evaluated the product to make sure it performed as described in a requirements specification. In this context of large enterprise software projects, QA testing was something of a software engineering specialty and automated testing was part of the practice, since it often was practical to write software programs to test software programs. If a testing regimen is thorough, automated testing will include <em>unit tests</em>, small test programs to test discrete parts of a software program, in isolation from the rest of the program, often at the class or method level.</p>
<p>Testing serves several purposes. First, it improves the user experience by finding problems before the product is released to customers. Second, it provides oversight for managers, as a verification that the project has been implemented as specified or promised. However, to a software engineer who is skilled at writing tests, the function of testing in the service of quality assurance is often secondary to testing as a method of programming. Instead of tests simply verifying that what you’ve written works, tests can become an integral part of the programming process. Rather than writing unit tests after you’ve written a piece of code, you can write your tests <em>first</em>. This is the essence of Test Driven Development. It may seem odd, or time-consuming, but for a skilled <span class="caps">TDD</span> practitioner, it brings coherence to the programming process. First, by writing tests before a writing a specific implementation, the developer will give thought to what needs to be accomplished and think through alternatives and edge cases. Second, by writing tests before writing implementation code, the developer will have complete test coverage for the project. Software products typically contain much hidden interdependency. With good test coverage, programmers (especially those on a team) can rip out and replace code to change features and (just as important) can refactor code, rearranging code to be more obvious or more efficient. Running a test suite after refactoring provides assurance that nothing inadvertently breaks after the changes.</p>
<p>Just as writing unit tests can bring coherence to writing portions of a software application, the overall process of developing an application can be improved by writing automated acceptance tests before implementing any parts of a project. Behavior Driven Development (<span class="caps">BDD</span>) is similar to Test Driven Development but focuses on writing specifications for a project in the form of descriptive stories that can be the basis for automated acceptance tests.</p>
<p>Before Rails, automated testing was rarely part of web development. A web application would be tested by users and (maybe) a QA team. Rails introduced the discipline of Test Driven Development to the wider web development community. Behavior Driven Development is less commonly used on Rails projects (less so among startups, more frequently among consulting firms and enterprise projects) but <span class="caps">TDD</span> is common and seen as a necessary skill of an experienced Rails developer.</p>
<h2>Rails Stack</h2>
<p>The set of technologies or software libraries that are used to develop an application or deliver web pages is called a technology “stack.” For example, Mark Zuckerberg developed Facebook in 2004 using the <a href="http://en.wikipedia.org/wiki/LAMP_(software_bundle)"><span class="caps">LAMP</span></a> stack consisting of Linux (operating system), Apache (web server), MySQL (database), and <span class="caps">PHP</span> (programming language). Rails, as a web development framework, and Ruby, as a programming language, can be used with a choice of operating systems (Linux, Mac OS X, Windows), databases (SQLite, MySQL, PostgreSQL, and others), and web servers (Apache, Nginx, and others).</p>
<p>As a beginner, your technology stack will include Ruby on Rails, the WEBrick web server (it comes with Ruby), the SQLite database, and the Linux, Mac OS X, or Windows operating system (whatever is installed on your computer).</p>
<p>The Rails stack can also include a variety of software libraries (gems) that add features to a website or make development easier. Sometimes the choice of components in a stack is driven by the requirements of an application. At other times, the stack is a matter of personal preference. Just as craftsmen and aficionados debate the merits of favorite tools and techniques in any other profession, Rails developers avidly dispute what’s the best Rails stack for development. At times it seems discussion leads to more heat than light.</p>
<p>Sometimes it is not easy to determine what’s at stake or even what’s being discussed. You’ll be challenged as you seek to sort out technical issues from matters of style or preference. But you can learn much about Rails by following these debates. These debates are a source for much innovation and improvement of the Rails framework. In the end, the power of the crowd prevails; usually the best components in the Rails stack are the most popular.</p>
<p>The proliferation of choices for the Rails stack can make learning difficult, particularly because the set of components promoted by David Heinemeier Hansson (the creator of Rails) is not the same set of components used by many leading Rails developers. For example, Heinemeier Hansson recommends the default Test::Unit library for test-driven development; many developers add the RSpec gem instead.</p>
<p>Tutorials for the RailsApps project resolve the debate by using components for the Rails stack that are most often used by the leading developers.</p>
<h2>What’s Next?</h2>
<p>At this point, if you’ve read the entire article, you’ve gotten an excellent introduction to Rails. You haven’t see any Rails code yet. But you’ve got the context and background that will help make sense of everything you encounter in Rails.</p>
<h3>
<a href="http://learn-rails.com/learn-ruby-on-rails.html"><img src="http://railsapps.github.io/images/learn-rails-cover-130x161.jpg" title="Learn Ruby on Rails" alt="Learn Ruby on Rails"></a> Get the Book</h3>
<p>The book <a href="http://learn-rails.com/learn-ruby-on-rails.html">Learn Ruby on Rails</a> is best Rails book for beginners.</p>
<h3>Ready to Install Rails?</h3>
<p>The <a href="http://railsapps.github.io/installing-rails.html">Install Rails</a> article from the RailsApps project will show you how to install Rails.</p>
<p>The article doesn’t offer shortcuts. It is an installation guide that professional developers use to configure their working environment for real-world Rails development.</p>
<h3>Would You Like to Build a Rails Application?</h3>
<p>The <a href="http://railsapps.github.io/">RailsApps project</a> provides example applications that developers use as starter apps. Hundreds of developers use the apps, report problems as they arise, and propose solutions. Rails changes frequently; each application is known to work and serves as your personal “reference implementation” so you can stay up to date. Each is accompanied by a tutorial so there is no mystery code.</p>
<p>You can use the <a href="http://railsapps.github.io/rails-composer/">Rails Composer</a> tool to generate any of the examples as a starter app. Then customize the code for a complete working Rails web application.</p>
</div>
<div class="comments" id="comments">
<div class="content wikistyle gollum">
<h2>Comments</h2>
</div>
<p>Is this helpful? Your encouragement fuels the project. Please tweet or add a comment. Couldn't get something to work? For the example apps and tutorials, it's best to open an issue on GitHub so we can help you.</p>
<div id="disqus_thread"></div>
<script type="text/javascript">
/* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
var disqus_shortname = 'railsapps'; // required: replace example with your forum shortname
/* * * DON'T EDIT BELOW THIS LINE * * */
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
<a href="http://disqus.com" class="dsq-brlink">comments powered by <span class="logo-disqus">Disqus</span></a>
</div><!-- class="comments" -->
</div><!-- class="columns" -->
</div><!-- class="row" -->
<footer class="row">
<div class="large-12 columns">
<div class="row">
<div class="medium-4 large-4 columns">
<dl class="footer_nav">
<dt>RailsApps · Getting Started</dt>
<dd><a href="http://railsapps.github.io/ruby-and-rails.html">Ruby on Rails</a></dd>
<dd><a href="http://railsapps.github.io/what-is-ruby-rails.html">What is Ruby on Rails?</a></dd>
<dd><a href="http://learn-rails.com/learn-ruby-on-rails.html">Learn Ruby on Rails</a></dd>
<dd><a href="https://tutorials.railsapps.org/rails-tutorial">Rails Tutorial</a></dd>
<dd><a href="http://learn-rails.com/ruby-on-rails-tutorial-for-beginners">Ruby on Rails Tutorial for Beginners</a></dd>
<dd><a href="http://railsapps.github.io/installing-rails.html">Install Ruby on Rails</a></dd>
<dd><a href="http://railsapps.github.io/installrubyonrails-mac.html">Install Ruby on Rails - Mac OS X</a></dd>
<dd><a href="http://railsapps.github.io/installrubyonrails-ubuntu.html">Install Ruby on Rails - Ubuntu</a></dd>
<dd><a href="http://railsapps.github.io/rubyonrails-nitrous-io.html">Ruby on Rails - Nitrous.io</a></dd>
<dd><a href="http://railsapps.github.io/updating-rails.html">Update Rails</a></dd>
<dd><a href="http://railsapps.github.io/rails-composer/">Rails Composer</a></dd>
<dd><a href="http://railsapps.github.io/">Rails Examples</a></dd>
<dd><a href="http://railsapps.github.io/rails-examples-tutorials.html">Rails Starter Apps</a></dd>
</dl>
</div>
<div class="medium-4 large-4 columns">
<dl class="footer_nav">
<dt>RailsApps · Articles</dt>
<dd><a href="http://railsapps.github.io/rails-authorization.html">Rails Authorization</a></dd>
<dd><a href="http://railsapps.github.io/rails-google-analytics.html">Analytics for Rails</a></dd>
<dd><a href="http://railsapps.github.io/rails-heroku-tutorial.html">Heroku and Rails</a></dd>
<dd><a href="http://railsapps.github.io/rails-javascript-include-external.html">JavaScript and Rails</a></dd>
<dd><a href="http://railsapps.github.io/rails-environment-variables.html">Rails Environment Variables</a></dd>
<dd><a href="http://railsapps.github.io/rails-git.html">Git and Rails</a></dd>
<dd><a href="http://railsapps.github.io/rails-github.html">Rails GitHub</a></dd>
<dd><a href="http://railsapps.github.io/rails-send-email.html">Send Email with Rails</a></dd>
<dd><a href="http://railsapps.github.io/rails-haml.html">Haml and Rails</a></dd>
<dd><a href="http://railsapps.github.io/rails-default-application-layout.html">Rails Application Layout</a></dd>
<dd><a href="http://railsapps.github.io/rails-html5-boilerplate.html">HTML5 Boilerplate for Rails</a></dd>
<dd><a href="http://railsapps.github.io/rails-3-2-example-gemfile.html">Example Gemfiles for Rails</a></dd>
<dd><a href="http://railsapps.github.io/rails-application-templates.html">Rails Application Templates</a></dd>
<dd><a href="http://railsapps.github.io/rails-product-planning.html">Rails Product Planning</a></dd>
<dd><a href="http://railsapps.github.io/rails-project-management.html">Rails Project Management</a></dd>
</dl>
</div>
<div class="medium-4 large-4 columns">
<dl class="footer_nav">
<dt>RailsApps · Tutorials</dt>
<dd><a href="http://railsapps.github.io/twitter-bootstrap-rails.html">Rails Bootstrap</a></dd>
<dd><a href="http://railsapps.github.io/rails-foundation.html">Rails Foundation</a></dd>
<dd><a href="http://railsapps.github.io/rails-omniauth/">OmniAuth Tutorial</a></dd>
<dd><a href="http://railsapps.github.io/tutorial-rails-devise.html">Rails Devise Tutorial</a></dd>
<dd><a href="http://railsapps.github.io/tutorial-rails-devise-rspec-cucumber.html">Devise RSpec</a></dd>
<dd><a href="http://railsapps.github.io/tutorial-rails-bootstrap-devise-cancan.html">Devise Bootstrap</a></dd>
<dd><a href="http://railsapps.github.io/rails-devise-roles">Role-Based Authorization</a></dd>
<dd><a href="http://railsapps.github.io/rails-devise-pundit">Rails Authorization with Pundit</a></dd>
<dd><a href="https://tutorials.railsapps.org/rails-stripe-membership-saas">Rails Membership Site with Stripe</a></dd>
<dd><a href="https://tutorials.railsapps.org/rails-recurly-subscription-saas">Rails Subscription Site with Recurly</a></dd>
<dd><a href="https://tutorials.railsapps.org/rails-prelaunch-signup">Startup Prelaunch Signup Application</a></dd>
</dl>
<dl class="footer_nav">
<dt>RailsApps Profile</dt>
<dd><a href="https://plus.google.com/108039160165742774777?rel=author">Google</a></dd>
<dd><a href="https://plus.google.com/117374718581973393536" rel="publisher">Find us on Google+</a></dd>
</dl>
</div>
</div>
</div>
</footer>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/foundation/5.2.2/js/foundation.min.js"></script>
<script>
$(document).foundation();
</script>
</body>
</html>