Tutorials on using Ruby on Rails to quickly develop Web applications _ruby topics

Source: Internet
Author: User
Tags reflection create database smarty template ruby on rails

Ruby on Rails is shaking the whole Web development landscape. Let us first understand the underlying technology:

Ruby is a free, simple, intuitive, extensible, portable, and interpreted scripting language for fast and simple object-oriented programming. Like Perl, it supports many of the features of working with text files and performing system administration tasks.
Rails is a complete, open source Web framework written in Ruby, designed to use simpler and less code to write applications that are actually in use.

As a complete framework, this means that all of the layers in Rails are constructed to work together, so you don't have to repeat it yourself, you can use a single language entirely. In Rails, all content (from templates to control streams to business logic) is written in Ruby. Rails supports reflection (reflection) and Run-time extensions based on configuration files and annotations.

This article introduces the components of Rails in detail and describes how it works.
Rails Introduction

The first thing you need to understand about Rails is its model/view/controller (MODEL/VIEW/CONTROLLER,MVC) architecture. While this technique is not specific to rails-not even the WEB application-specific (as opposed to other programs), rails has a very clear and single-minded way of thinking about MVC. If you do not use the MVC method, the usefulness of Rails will be greatly reduced (compared to the case of following its pattern).
Model

The model part of a Rails application is primarily the underlying database it uses. In fact, in many cases, Rails applications are one way to perform operations on data in a relational database management system (RDBMS) in a managed fashion.

The ActiveRecord class is a core part of Rails that maps a relational table to a Ruby object, making it the data that the controller can manipulate and display in the view. Rails applications are particularly inclined to use a widely used MySQL database, but there are also bindings to many other RDBMS, such as IBM? DB2?

If you want, you can add Ruby code to perform additional validation in the application model, enforce data associations, or trigger other actions. The Ruby file in the application's app/models/directory can invoke multiple authentication methods for ActiveRecord. However, you can also leave the model code as a stub rather than relying on the constraints of the RDBMS that holds the data. For example, the application that I developed in this example contains only this skeleton model code (at least initially):
Listing 1. Skeleton Model APP/MODELS/CONTACT.RB

Class Contacts < ActiveRecord::Base end


Controller

The controller executes the application's logic in its abstract form. That is, the Ruby script in the application's app/controllers/directory can import the model data into variables, save them back, or modify and process them. However, the controller does not care about how users can properly display or enter data. In the usual MVC model, this allows users to interact with the same controller in a variety of ways: The local GUI, the Web interface, and the voice interface used by people with weak vision can interact with the same controller.

However, Rails is not as versatile as that, and instead it is limited to providing and collecting data on Web pages. Nonetheless, you can modify the layout of those Web pages-colors, fonts, tables, style sheets, and so on-regardless of the controller code.
View

The Rails view is where we write Ruby code. Rails contains a very good template language for. rhtml, which combines pure HTML with embedded Ruby code. The most superficial appearance of the Rails application interface is usually controlled by a CSS style sheet. The. rhtml format is an enhanced HTML. In fact, a simple HTML file is itself a legitimate RHTML template, but you should not ignore the scripting controls that RHTML gives you.

RHTML is a real template format--not just a way to embed code in HTML--it's a much more efficient approach. If you are familiar with PHP, consider the comparison between PHP itself and the Smarty template. In other words, the embedded script simply mixes the code with the HTML that was not interpreted, and the code part is still responsible for executing the print statement when something needs to be exported to the client.

In contrast, the template engine adds a set of custom tags to HTML that allows you to represent conditions, loops, and other logic as part of an enhanced HTML tag.

Generate code

The tools provided by Rails are primarily a set of code generators. I prefer this approach to the development environment that forces me to use a rigorous workspace and IDE. Rails won't get in the way of you, but it will save you most of your hand-programmed work-or, by providing a "free" preliminary (First-pass) bracket (scaffolding), at least help you easily divide the work that needs to be hand-coded into multiple parts.

The scaffolding concept is a core concept in Rails. A very simple application might have no coding at all, so that Rails can dynamically generate client HTML pages at run time. The first time you generate code, you create a rough bracket; you can then generate more detailed controllers, views, and models that can be customized. However, you do not need to generate too many at the beginning.

Rails has a fixed and very common organization for its files, but the organization is relatively strict. If you try to force other files and code to be organized, you may have to make an effort to modify the Rails environment. Again, I can't find a reason not to use the organization that Rails provides, and in most cases it's "fits Your Brain" (as the proponents of Ruby like to say). For example, if you are designing a framework from scratch (at least if you think in Ruby mode), then these directory names and their organizations may be very close to your choice.

Building a simple application

There are tutorials on the Ruby on Rails Web site that will completely guide you through creating a simple Rails application (see Resources). The example program here is similar because the way to start building a Rails application correctly is OK. Because the length of this introduction is relatively short, I highly recommend one of those longer tutorials so that you can make a more comprehensive foundation.

The sample application is a basic address book. It demonstrates the general steps for creating an application:

Build the model (create the MySQL database and table in this step).
Build the application (including generating codebase and directories).
Start Rails (and configure access to the database).
Create some content (including building the scaffolding model and controller, and tell the controller to use that bracket).

We will examine each step in detail.
Generate AddressBook Model

The first thing you need to do for any application is to create a database of data for it. Technically this step does not have to be first, but it needs to be done early, and it should be obvious that the database should be created before any application code (even auto-generated code) is written. So let's create a database in the MySQL database and create the first table in this database. (Read other documents to learn how to install a MySQL or other RDBMS.) )

We assume that MySQL is installed and available.
Listing 2. Creating MySQL databases and tables

[~/sites]$ cat Addressbook.sql
CREATE DATABASE IF not EXISTS addressbook;
Use AddressBook;
CREATE TABLE IF not EXISTS contacts (
 ID smallint (5) unsigned not NULL auto_increment,
 name varchar (a) NOT NULL D Efault ',
 created_on timestamp not NULL,
 updated_on timestamp (#) NOT NULL,
 PRIMARY KEY (id),
 UNIQUE KEY Name_key (name)
Type=myisam comment= ' List of Contacts ';
[~/sites]$ Cat Addressbook.sql | Mysql

There are some places in this first table that need attention. The most important thing is that each table must have an ID column, and the column name is the ID. Rails uses primary key column IDs to complete various record-keeping and referencing tasks. Domain created_on and updated_on are not needed, but if you use them, Rails will automatically maintain them "in the background", and in most cases there is nothing wrong with using them. So, the "real" data you want to add is just the name of the Address book content.

Another slightly odd aspect is that Rails uses singular and plural names for different content. Depending on the context, the various entries are renamed in the singular or plural form. The name of the table should be in the plural format. I don't have the experience of using irregular plural words; words like datum and data may cause problems with Rails.
Build AddressBook Application

Now that you have a database that you can interact with, you can create a addressbook application. The first step is to simply run rails to generate basic directory and Bracket code:
Listing 3. Generate Basic code and directories

[~/sites]$ rails addressbook
Create
Create App/apis create
app/controllers
Create App/helpers
Create App/models
Create app/views/layouts Create
config/environments
Create Components
[...]
Create Public/images
Create public/javascripts Create
public/stylesheets
Create Script
[...]
Create README
Create script/generate
create Script/server
[...]

I cut out the output of running rails, ignoring those lines just to remind you of the various files and directories you've created. Try it on your system to browse all the generated files. I've already shown some of the most important files and directories in my code.
Run Rails

Once you have created the addressbook/directory and the subdirectories you need, you need to perform a unique initial configuration. First, you set up the database by modifying the YAML configuration file, as follows:
Listing 4. Configuring Database Access

[~/sites]$ cd addressbook
[~/sites/addressbook]$ head-6 config/database.yml # After editing
development:
 Adapter:mysql
 database:addressbook
 host:localhost
 username:some_user
 password:password_if_ Needed

Finally, you need to provide the data. Rails comes with its own single functional Web server, Webrick, which is very suitable for our experiments. You might also follow the instructions on the Ruby on Rails Web site to configure Apache or other servers to service Rails applications via FCGI (or regular CGI, but the regular CGI will be slower).
Listing 5. Start Webrick Server

[~/sites/addressbook]$ Ruby script/server-d
=> Rails application started on http://0.0.0.0:3000
[ 2005-03-21 17:57:38] Info webrick 1.3.1
[2005-03-21 17:57:38] Info ruby 1.8.2 (2004-12-25) [powerpc-darwin7.8.0]

Create some content

To see a welcome page on the Webrick port, the previous steps are sufficient. For example, on my local system, you can now access http://gnosis-powerbook.local:3000/. However, to manipulate custom databases, you need to generate a little more code. You can use script generate to complete this task, which is created in the addressbook/application directory:
Listing 6. Scaffolding model and controller code generation

[~/sites/addressbook]$ Ruby Script/generate model contact
   exists app/models/
   exists test/unit/
   exists test/fixtures/
   Create app/models/contact.rb Create
   test/unit/contact_test.rb
   Create test/fixtures/ Contacts.yml
[~/sites/addressbook]$ Ruby script/generate Controller contact
   exists app/controllers/
   exists app/helpers/
   create app/views/contact
   exists test/functional/
   create App/controllers/contact _CONTROLLER.RB
   Create test/functional/contact_controller_test.rb
   Create app/helpers/contact_helper.rb

Note that in the corresponding table name, you should use the singular contact instead of the plural contacts.

Now you need to edit one or more of the generated files (just a little editing) to get the controller to use the bracket:
Listing 7. Tell the controller to use the bracket

[~/sites/addressbook]$ Cat App/controllers/contact_controller.rb
Class Contactcontroller < Applicationcontroller
Model:contact
Scaffold:contact
End

You can now view and modify the contents of the database by using a URL similar to http://rails.server/contact/(http://gnosis-powerbook.local:3000/contact/in my test case). After you enter some data, it looks like Figure 1 and Figure 2:
Figure 1. List Contacts

Figure 2. Edit a contact

Create customizable content

The preceding code creates a fully functional interface to view and modify the database, but all formatting, display, and business logic (such as the ones that are already there) are dynamically completed by Rails without any significant modifications. To create more customizable content, you need to generate some more code. All we need now is for Rails to explicitly write all the scaffolding that it implicitly generates at runtime so that we can modify it.
Figure 8. Explicit controller and view code generation

[~/sites/addressbook]$ Ruby Script/generate Scaffold Contact
 dependency Model
   [...]
   Create app/views/contacts
   exists test/functional/
   create app/controllers/contacts_controller.rb
   Create test/functional/contacts_controller_test.rb
   Create app/helpers/contacts_helper.rb
   Create App/views /layouts/contacts.rhtml
   Create public/stylesheets/scaffold.css
   Create app/views/contacts/list.rhtml
   Create app/views/contacts/show.rhtml
   Create app/views/contacts/new.rhtml
   Create app/views/ Contacts/edit.rhtml

Now that you have more to do, try to modify some of the content. (Note that this code has reused the plural format contacts, I don't know why; now we need to accept it.) Try to modify some colors and fonts in the CSS:
Listing 9. Configuring cascading Style Sheets

[~/sites/addressbook]$ head-8 public/stylesheets/scaffold.css body
{background-color: #ffe; color: #338;}
Body, p, OL, UL, TD {
 Font-family:verdana, Arial, Helvetica, Sans-serif;
 Font-size:  13px;
}
TD {BORDER:1PX solid;}
A {color: #eef; Background-color: #446;}
a:hover {color: #fff; Background-color: #000;}

You already have this piece of code, so what CONTACTS_CONTROLLER.RB do? In terms of its operation, it is more explicit and configurable than the contact_controller.rb that appears in the previous code. The controller is similar to the following:
Listing 10. Controller APP/CONTROLLERS/CONTACTS_CONTROLLER.RB

Class Contactscontroller < Applicationcontroller
 def list
  @contacts = Contact.find_all End
 def show
  @contact = Contact.find (@params [' id '])
 end
 def create
  @contact = contact.new (@params [' Contact '] "
  if @contact. Save
   flash[' notice '] = ' contact is successfully created. '
   Redirect_to:action => ' list '
  else
   render_action ' new '
  end
 

As mentioned earlier, the main task of a controller is to import data into a variable. Object contact is the ActiveRecord object-relational mapping provided by the model. Variables @contacts or @contact are the data given in their appropriate methods. You can access those methods themselves through URLs, such as HTTP://RAILS.SERVER/CONTACTS/SHOW/2 (this method shows a contact with the id "2").

The controller in this example eventually connects to the view, the RHTML file, which uses the data values that the controller imports into the variable. For example, this is part of the list view:
Listing 11. List views app/views/contacts/list.rhtml

[...]
<% for contacts in @contacts%>
 <tr>
 <% for column in Contact.content_columns%>
  <td> <%=h contact.send (column.name)%></td> <% end%> <td><%=
  ' show ': action = > ' Show ',: ID => contact.id%></td>
  <td><%= link_to ' edit ': Action => ' edit ',: ID => Co Ntact.id%></td>
  <td><%= link_to ' Destroy ': Action => ' Destroy ',: ID => contact.id </td>
 </tr>
<% end%>
[...]

Method contactscontroller.list The Import variable @contacts, the Flow Control tab in RHTML takes a single record out of the array.

Modify Model

The initial model contains only the name of the contact person. Unfortunately, I have no room in this article to extend this model to include actual contact data, such as phone numbers, addresses, emails, and so on. Typically, those data should be stored in a child table, and the external keywords of the child table are associated with the table contacts. The Rails model uses custom code like this to indicate the association:
Listing 12. Custom code APP\MODELS\PHONE.RB

Class Phone < activerecord::base
 belongs_to:contact
End

Before we finish, let's modify the data model slightly to see how it affects the application. First, add a column:
Listing 13. Adding First_met data to a model

$ cat Add-contact-date.sql use
addressbook;
ALTER TABLE contacts ADD first_met date;
$ Cat Add-contact-date.sql | Mysql

Now that the underlying model has been modified, the back-end version of the http://rails.server/contact/--bracket will be adjusted directly to what you do not need. The controller and view are fully automated based on the model. However, the application version on http://rails.server/contacts/uses our hand-written files and is not as automated.

The list view Contact.content_columns as part of the template loop, automatically finding all the columns, no matter what they are. However, other views, such as edit, have been generated, and new data fields need to be added. For example:
Listing 14. Edit View app/views/contacts/edit.rhtml

 
 

So what does the application that you modify manually look like? The difference from the default is not very large, but in Figures 3 and 4 you can see that the modifications are in effect:
Figure 3. List contacts, after modification

Figure 4. Edit Contact, modify

Conclusion

Rails provides you with an extremely fast way to develop flexible Web applications, and this article is just a superficial introduction to using rails. The complete framework contains a number of practical classes and methods that can accomplish the most of the actions that web-based applications use.

The biggest value of rails is that it breeds a system of "rails thinking" because all the support code you need makes it complete. This is a huge advantage relative to other toolkits and frameworks that just give the raw material to use. Rails Development provides you with a smooth path to implementing a 50%-shape (half-formed) idea as a fully functional WEB application.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.