26
Tue, Nov
1 New Articles

Ruby on Rails in 2,057 Words

Web Languages
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

If you've been following the latest technologies and trends at all lately, you have undoubtedly encountered the phrase "Ruby on Rails" (also often referred to as "RoR" or just "Rails") and discussion about why it's the best technology in the world or whether it's just another over-hyped buzzword. Rest assured, Ruby on Rails is the real deal, and it's here to stay. Rails has definitely gained a lot of merit since its inception, and while it may or may not be the best fit for your next Web-based application, it is important that all Web developers and Web architects have at least a fundamental understanding of the features that Rails brings to the table.

Brief History of Ruby on Rails

A common misconception is that Ruby on Rails is by itself a single technology. It's not. It is important to understand that Ruby on Rails actually consists of two major technologies. The first component is called Ruby. Ruby, by itself, is "just" a programming language. Ruby was released to the general public in 1995 by its creator, Yukihiro "Matz" Matsumoto. Ruby has syntax similar to Perl and object-oriented features similar to Alan Kay's Smalltalk. Ruby is a strongly-typed (i.e., expressions such as "4" + 5 are illegal), single-pass interpreted language.

The second major component (and the cornerstone of the hype) of Ruby on Rails is Rails. Rails is a Web application framework written completely in the Ruby programming language (and hence the derived name, Ruby on Rails). A Web application framework is a set of tools and libraries that make it "easy" to create Web-based applications. The sad reality is that within most development projects, a sizeable amount of time is spent not solely on the application logic itself, but rather on a foundation and a set of reusable components for use throughout. It's these reusable artifacts that are collectively referred to as the application's framework; this is precisely where Rails can lend a helping hand. The Rails framework debuted nearly three years ago, in July of 2004. David Heinemeier Hansson, Rails' creator, actually created the Rails framework while working at 37signals on a project called Basecamp. He immediately saw the value in making the framework available to the public and released it as an open-source project for the world to take advantage of all the great things Rails has to offer.

Reduce Your Development Time

Does Rails provide any new function with respect to other technologies? Not really. However, it does allow you to accomplish the same tasks in potentially a fraction of the time. Rails offers the potential for teams to build a wide range of complex Web sites in weeks instead of months, without sacrificing quality of code. Rails promotes good programming practices, which leads to intuitive and easy-to-maintain code. Continue reading to experience the benefits of Rails.

Features and Benefits of Rails

Rails has many features that provably make a reduced development schedule and an easy-to-maintain project a reality. Some of its key benefits include these:

  • MVC framework—The Rails framework is an instance of the ever-popular MVC (Model-View-Controller) framework; it offers components to easily model your data, elegantly present it to the user, and simplify the interaction between the user and the model(s).
  • Fewer lines of code—Rails removes much of the tedious work (e.g., writing a heavy-weight data access layer or a transaction manager layer) from an application's framework and instead allows you to spend more time on your actual application logic.
  • Ruby gems—Ruby packages additional libraries in what's called a gem (e.g., Active Record, whose description is forthcoming, is a Ruby gem); this packaging system makes it easy to obtain new libraries and resolve dependencies between libraries.
  • Easy code testing—Since Rails ships with its own Web server for most platforms, you can easily write your code and immediately test it without having to go through lengthy deployment processes; Ruby also has full support for application breakpoints to aid in debugging.

Introduction to Ruby Gems

As mentioned, a Ruby gem is an additional component to the Ruby programming language. In the general sense, understanding and knowing which gems are available is what will lead you to successful projects; let the gems do the work for you! The following list offers high-level explanations of a small subset of the available Ruby gems.

Active Record

To quote the official definition, "Active Record is a Ruby gem that connects business objects and database tables to create a persistable domain model where logic and data are presented in one wrapping. It is an implementation of the object-relational mapping (ORM)." In essence, this means you no longer need to spend your valuable time creating the ORM layer. In the J2EE world, this is where you'd normally spend countless hours creating Java beans and data access objects (DAOs). Rails simply waves goodbye. Active Record shields the need for SQL constructs within your application code but does support it for times when absolutely necessary. Per the Active Record documentation, some of its major features include these:

  • Automated mapping between classes and tables, attributes and columns
    class Person < ActiveRecord::Base; end

    ...gets automatically mapped to the "person" table below...

    CREATE TABLE person (
          id int NOT NULL,
          first_name varchar(63),
          last_name varchar(63),
          PRIMARY KEY(id)
    );
  • Associations between objects controlled by simple meta-programming macros
    class Patient < ActiveRecord::Base
          has_many :medical_records
          has_one :primary_physician
    end
  • Inheritance hierarchies
    class Animal < ActiveRecord::Base; end
    class Pet < Animal; end
    class Cat < Pet; end
  • Transaction support on both a database and an object level
    # Database-only transaction
    Account.transaction do
          david.withdrawal(100)
          mary.deposit(100)
    end

    # Data and object transaction
    Account.transaction(david, mary) do
          david.withdrawal(100)
          mary.deposit(100)
    end
  • Logging support for Log4r and Logger,which allows you to take a step-by-step look at what the data access layer is doing
    ActiveRecord::Base.logger = Logger.new(STDOUT)
    ActiveRecord::Base.logger = Log4r::Logger.new("Application Log")

As you can see from just some of the examples above, Ruby on Rails abstracts a lot of the typical data access logic so that you never need to work with the raw SQL and database structures. Again, this allows you to spend more time on your business logic than on primitive (with respect to the application) components.

Action Pack

Action Pack handles both the View and Controller parts of Rails. It splits a response to a Web request into a Controller part (performing the logic) and a View part (rendering a template). This is known as an "action," which will normally create, read, update, or delete (CRUD) a Model part before choosing to either render a template or redirect to another action. Action Pack implements these actions as methods on Action Controllers and uses Action Views to implement the template rendering. Action Controllers are then responsible for handling all the actions relating to a certain part of an application. Per the Action Pack documentation, these are some of its major features:

  • Simple URL routing—Incoming URL requests get mapped to an action within an Action Controller, which is a Ruby class that has a set of public methods that handle the particular action. As an example, if Rails received a request for http://yourco.com/statement/display/54, Rails would hand this request to StatementController::display(54) for processing.
  • View templates—View templates are essentially the HTML to give back to browser requests (think JSP files) and are stored with the rhtml filename extension. Text within <% %> is executable Ruby code, similar to that found in Java Server Pages (JSPs).
  • Helpers for forms, dates, action links, and text
    <% text_field "post", "title", "size" => 30 %>
    <% html_date_select(Date.today) %>
    <% truncate(post.title, 25) %>
  • Javascript and AJAX integration
    link_to_function "Greeting", "alert('Hello World!')"
    link_to_remote "Delete this post", :update => "posts",
                      :url => { :action => "destroy", :id => post.id
    }

Action Web Service

Action Web Service implements server-side support for SOAP and XML-RPC Web service protocols. It integrates with Action Pack so that you can easily publish APIs via the Web Service Definition Language (WSDL). For more information, please visit the official Rails Action Web Service page.

Action Mailer

Almost all of today's Web applications need to communicate with its users in some fashion, so it should be easy to achieve, right? Of course! Ruby's Action Mailer allows you to either send or receive email from within your application. Here's an example snippet of how to send an email message:

def send_message(user)
  recipients user.email_address
  subject "Greetings from Rails!"
  from This email address is being protected from spambots. You need JavaScript enabled to view it.
  body "Your first Rails email message."
end

No more writing 50 to 100 lines of code to simply send an email, as is necessary in some other languages! Although it's not covered here, Action Mailer makes it easy to send file attachments as well.

That's Great, But What Are Its Weaknesses?

As always, it's important to understand both a technology's strengths and its weaknesses. Rails, like any other technology, certainly has its weaknesses. I'd have to say Rails' biggest weaknesses is its relative (to competing technologies) immaturity. While it debuted nearly three years ago, it hasn't been deployed nearly to the extent of some of its competitors (J2EE, PHP, ASP, .NET, etc.) such that the technologies can be accurately compared. Depending on the type of project in which you're involved, its relative "immaturity" may or may not be a show-stopper; that's a decision you'll have to make. It's noteworthy that the number of business-class Web sites using Rails is constantly growing. In the future, we can surely expect to see a wealth of technological comparisons (backed by documented results) as well as a rich set of texts explaining how to deploy Rails applications in those "advanced" scenarios. The best piece of advice I can offer here is to simply study, download, install, and work with Rails to get a feel for how it will work for you.

Supported Environments

Ruby on Rails ships in either source or binary form and is supported on most major *nix platforms, OS X, and Windows. As noted directly on the official Ruby on Rails Web site, Rails works with a wealth of Web servers and databases. Recommended Web servers include Apache or lighttpd running FastCGI, SCGI, or Mongrel. To make things even easier, Rails ships with WEBrick, its own pure-Ruby Web server. This means you can simply download Ruby and immediately start creating your first Rails Web site without the hassle and overhead of configuring a Web server. Potential databases include MySQL, PostgreSQL, SQLite, Oracle, SQL Server, DB2, or Firebird.

In terms of development environments to work with Ruby code, surely any text editor will suffice, but there is also an excellent Eclipse-based plug-in available called RadRails that makes developing Rails applications even easier. Whether or not you're already an Eclipse user, if you're going to work with Rails, RadRails is definitely worth an evaluation.

The Rails Community

Since its inception, Ruby on Rails has been increasingly gaining notoriety, so a lot of public communities have spawned into existence. There are a variety of resources out there for Rails developers, including mailing lists for help, wikis containing a breadth of Rails information, IRC chat rooms for real-time discussion, and much more! While you can find these resources just about anywhere, an excellent starting point is the official Ruby on Rails community Web site. All of these resources and communities help foster the maturity of the Rails framework; developers from all over the world can share their ideas and experiences to help lead you to successful projects.

Try Ruby on Rails for Yourself

In no way have I come remotely close to touching on all that Rails has to offer, but hopefully I have convinced you that Rails is worth spending a few hours of your time to investigate. If writing less code with less room for mistakes on Web-related projects is what you're seeking, Rails is definitely worth giving a try. Where do you go from here? Well, the wealth of simple tutorials on the Web can introduce you to Rails development and allow you to experience the niceties and benefits firsthand. Who knows, the next time your boss asks you to throw together a Web site, you might be able to put something together in no time! Don't take my word for it, though; give Ruby on Rails a try for yourself.

Joe Cropper is a Software Engineer at IBM in Rochester, Minnesota. Joe works as part of the System i Software Final System Test team, and his areas of expertise include database, multi-tiered client-server technologies, and a variety of object-oriented programming languages. Joe can be reached via email at This email address is being protected from spambots. You need JavaScript enabled to view it..

Joe Cropper is a Software Engineer at IBM in Rochester, Minnesota. He works as part of the Cloud Systems Software Development organization, focusing on virtualization and cloud management solutions. Joe has held a number of roles in other organizations as well, ranging from IBM i and Electronic Support. His areas of expertise include virtualization and cloud management, OpenStack, Java EE, and multi-tiered applications. Joe can be reached via email at This email address is being protected from spambots. You need JavaScript enabled to view it..

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: