Ruby on Rails

What is Ruby?

Ruby is a dynamic, reflective, object-oriented, general-purpose programming language.  It was desig100px-Ruby_logo_svgned and developed in the mid-1990s by Yukihiro “Matz” Matsumoto in Japan.

According to its authors, Ruby was influenced by Perl, Smalltalk, Eiffel, Ada, and Lisp.  It supports multiple programming paradigms, including functional, object-oriented, and imperative. It also has a dynamic type system and automatic memory management.

Ruby 2.2.0 was released on Christmas Day in 2014.  The release includes speed-ups, bug fixes, and library updates and removes some deprecated APIs. Most notably, Ruby 2.2.0 introduces changes to memory handling – an incremental garbage collector, support for garbage collection of symbols and the option to compile directly against jemalloc.

Philosophy

Yukihiro Matsumoto, the creator of Ruby

Yukihiro Matsumoto, the creator of Ruby

Matsumoto has said that Ruby is designed for programmer productivity and fun, following the principles of good user interface design. At a Google Tech Talk in 2008 Matsumoto further stated, “I hope to see Ruby help every programmer in the world to be productive, and to enjoy programming, and to be happy. That is the primary purpose of Ruby language.”

Ruby is said to follow the principle of least astonishment (POLA), meaning that the language should behave in such a way as to minimize confusion for experienced users. Matsumoto has said his primary design goal was to make a language that he himself enjoyed using, by minimizing programmer work and possible confusion.

https://en.wikipedia.org/wiki/Ruby_(programming_language)


 

What is Ruby on Rails?

150px-Ruby_on_Rails_svgRuby on Rails, or simply Rails, is a web application framework written in Ruby under MIT License. Rails is a model–view–controller (MVC) framework, providing default structures for a database, a web service, and web pages. It encourages and facilitates the use of web standards such as JSON or XML for data transfer, and HTML, CSS and JavaScript for display and user interfacing. In addition to MVC, Rails emphasizes the use of other well-known software engineering patterns and paradigms, including convention over configuration (CoC), don’t repeat yourself (DRY), and the active record pattern.

David Heinemeier Hansson extracted Ruby on Rails from his work on the project management tool Basecamp at the web application company also called Basecamp.  Hansson first released Rails as open source in July 2004, but did not share commit rights to the project until February 2005. In August 2006, the framework reached a milestone when Apple announced that it would ship Ruby on Rails with Mac OS X v10.5 Leopard,  which was released in October 2007.

Ruby on Rails 3.2 is the latest in the series of releases.

Framework structure

Ruby on Rails is separated into various packages, namely ActiveRecord (an object-relational mapping system for database access), Active Resource (provides web services), Action Pack, Active Support and Action Mailer. Prior to version 2.0, Ruby on Rails also included the Action Web Service package that is now replaced by Active Resource. Apart from standard packages, developers can make plugins to extend existing packages.

Deployment

Ruby on Rails is often installed using RubyGems, a package manager which is included with current versions of Ruby. Many free Unix-like systems also support installation of Ruby on Rails and its dependencies through their native package management system.

Ruby on Rails is typically deployed with a database server such as MySQL or PostgreSQL, and a web server such as Apache running the Phusion Passenger module.

Philosophy and design

Ruby on Rails is intended to emphasize Convention over Configuration (CoC), and the Don’t Repeat Yourself (DRY) principle.

Convention over Configuration means a developer only needs to specify unconventional aspects of the application. For example, if there is a class Sale in the model, the corresponding table in the database is called sales by default. It is only if one deviates from this convention, such as calling the table “products sold”, that the developer needs to write code regarding these names. Generally, Ruby on Rails conventions lead to less code and less repetition.

Don’t repeat yourself means that information is located in a single, unambiguous place. For example, using the ActiveRecord module of Rails, the developer does not need to specify database column names in class definitions. Instead, Ruby on Rails can retrieve this information from the database based on the class name.

See https://en.wikipedia.org/wiki/Ruby_on_Rails


Introduction to Ruby on Rails
From Michael Hartl (2015) Ruby on Rails Tutorial
Available online at: https://www.railstutorial.org/book/

Ruby on Rails (or just “Rails” for short) is a web development framework written in the Ruby programming language. Since its debut in 2004, Ruby on Rails has rapidly become one of the most powerful and popular tools for building dynamic web applications. Rails is used by companies as diverse as Airbnb, Basecamp, Disney, GitHub, Hulu, Kickstarter, Shopify, Twitter, and the Yellow Pages. There are also many web development shops that specialize in Rails, such as ENTP, thoughtbot, Pivotal Labs, Hashrocket, and HappyFunCorp, plus innumerable independent consultants, trainers, and contractors.

What makes Rails so great? First of all, Ruby on Rails is 100% open-source, available under the permissive MIT License, and as a result it also costs nothing to download or use. Rails also owes much of its success to its elegant and compact design; by exploiting the malleability of the underlying Ruby language, Rails effectively creates a domain-specific language for writing web applications. As a result, many common web programming tasks—such as generating HTML, making data models, and routing URLs—are easy with Rails, and the resulting application code is concise and readable.

Rails also adapts rapidly to new developments in web technology and framework design. For example, Rails was one of the first frameworks to fully digest and implement the REST architectural style for structuring web applications (which we’ll be learning about throughout this tutorial). And when other frameworks develop successful new techniques, Rails creator David Heinemeier Hansson and the Rails core team don’t hesitate to incorporate their ideas. Perhaps the most dramatic example is the merger of Rails and Merb, a rival Ruby web framework, so that Rails now benefits from Merb’s modular design, stable API, and improved performance.

Finally, Rails benefits from an unusually enthusiastic and diverse community. The results include hundreds of open-source contributors, well-attended conferences, a huge number of gems (self-contained solutions to specific problems such as pagination and image upload), a rich variety of informative blogs, and a cornucopia of discussion forums and IRC channels. The large number of Rails programmers also makes it easier to handle the inevitable application errors: the “Google the error message” algorithm nearly always produces a relevant blog post or discussion-forum thread.


YouTube – How to Build a Blog Engine in 15 Minutes with Ruby on Rails
David Heinemeier Hansson

“From the beginning, Rails has benefited from a palpable sense of excitement, starting with the famous 15-minute weblog video by Rails creator David Heinemeier Hansson. That video and its successors are a great way to get a taste of Rails’ power, and I recommend watching them. But be warned: they accomplish their amazing fifteen-minute feat using a feature called scaffolding, which relies heavily on generated code, magically created by the Rails generate scaffold command.” [From Michael Hartl (2015) Ruby on Rails Tutorial]


RSpec
(https://en.wikipedia.org/wiki/RSpec)
RSpec is a behavior-driven development (BDD) framework for the Ruby programming language, inspired by JBehave. It contains its own mocking framework that is fully integrated into the framework based upon JMock. The framework can be considered a domain-specific language (DSL) and resembles a natural language specification.


 

RSpec Official Website
(http://rspec.info/about/)

Behaviour Driven Development for Ruby.Making TDD Productive and Fun.
To kick things off, install RSpec and run rspec --init to set up your project to use RSpec.
History
RSpec began life in 2005 as an experiment by Steven Baker, with early contributions from Dave Astels and Aslak Hellesøy. David Chelimsky joined the team that summer, and accepted leadership of the project in 2006. David also built rspec-rails, which provided tight integration with Ruby on Rails.RSpec 1.0 was released in May of 2007, and included many of the features that are still present in RSpec today. RSpec 1’s runner had many great features but had reached a point where it was slow and hard to continue evolving it.In late 2008, Chad Humphries built Micronaut, a new spec runner, to address these problems. Micronaut also included a new metadata system that provided much greater flexibility than RSpec 1 had.In early 2010, after the release of RSpec 1.3, David and Chad began working on RSpec 2. The project got split into separate, modular pieces that could be used individually or all together. Micronaut was used as the basis of rspec-core, the new runner. RSpec 2 was released in October 2010 after nearly a year of effort.

In November 2012, after leading the project for 6 years, David decided to move on to other things. He asked Myron Marston to take over as lead RSpec maintainer and Andy Lindeman to take over as lead rspec-rails maintainer.

Work on RSpec 3 began in July 2013 and it was released in June 2014. RSpec 3 was a bit of a “spring cleaning” for RSpec, removing much cruft (some of which dated back to RSpec 1!). It also provided verifying doubles, composable matchers, a new syntax that allows RSpec to be used with no monkey patching, and many other new features. Andy Lindeman retired from the team and asked Aaron Kromer to take over as rspec-rails maintainer.

Today, RSpec continues to improve and evolve thanks to the input of a large community and the work of hundreds of contributors.


 

Behaviour Driven Development in Ruby with RSpecThe RSpec Book
(https://pragprog.com/book/achbd/the-rspec-book)

The RSpec Book will introduce you to RSpec, Cucumber, and a number of other tools that make up the Ruby BDD family. Replete with tutorials and practical examples, the RSpec Book will help you get your BDD on, taking you from executable requirements to working software that is clean, well tested, well documented, flexible and highly maintainable.

Chelimsky, D., Astels, D., Dennis, Z., Hellesøy, A., Helmkamp, B., North, D. (2010) Behaviour-Driven Development with RSpec, Cucumber, and Friends

Behaviour-Driven Development (BDD) gives you the best of Test Driven Development, Domain Driven Design, and Acceptance Test Driven Planning techniques, so you can create better software with self-documenting, executable tests that bring users and developers together with a common language.

Get the most out of BDD in Ruby with The RSpec Book, written by the lead developer of RSpec, David Chelimsky.
This book uses Rails 3, RSpec 2, Ruby 1.8.7, and Cucumber 0.9.2You’ll get started right away with RSpec 2 and Cucumber by developing a simple game, using Cucumber to express high-level requirements in language your customer understands, and RSpec to express more granular requirements that focus on the behavior of individual objects in the system. You’ll learn how to use test doubles (mocks and stubs) to control the environment and focus the RSpec examples on one object at a time, and how to customize RSpec to “speak” in the language of your domain.You’ll develop Rails 3 applications and use companion tools such as Webrat and Selenium to express requirements for web applications both in memory and in the browser. And you’ll learn to specify Rails views, controllers, and models, each in complete isolation from the other.Whether you’re developing applications, frameworks, or the libraries that power them, The RSpec Book will help you write better code, better tests, and deliver better software to happier users.


About Ruby
(https://www.ruby-lang.org/en/about/)

Wondering why Ruby is so popular? Its fans call it a beautiful, artful language. And yet, they say it’s handy and practical. What gives?

The Ideals of Ruby’s Creator

Ruby is a language of careful balance. Its creator, Yukihiro “Matz” Matsumoto, blended parts of his favorite languages (Perl, Smalltalk, Eiffel, Ada, and Lisp) to form a new language that balanced functional programming with imperative programming.

He has often said that he is “trying to make Ruby natural, not simple,” in a way that mirrors life.

Building on this, he adds:

Ruby is simple in appearance, but is very complex inside, just like our human body1.

About Ruby’s Growth

Since its public release in 1995, Ruby has drawn devoted coders worldwide. In 2006, Ruby achieved mass acceptance. With active user groups formed in the world’s major cities and Ruby-related conferences filled to capacity.

Graph courtesy of Gmane.

Ruby-Talk, the primary mailing list for discussion of the Ruby language, climbed to an average of 200 messages per day in 2006. It has dropped in recent years as the size of the community pushed discussion from one central list into many smaller groups.

Ruby is ranked among the top 10 on most of the indices that measure the growth and popularity of programming languages worldwide (such as the TIOBE index). Much of the growth is attributed to the popularity of software written in Ruby, particularly the Ruby on Rails web framework.

Ruby is also completely free. Not only free of charge, but also free to use, copy, modify, and distribute.

Seeing Everything as an Object

Initially, Matz looked at other languages to find an ideal syntax. Recalling his search, he said, “I wanted a scripting language that was more powerful than Perl, and more object-oriented than Python2.”

In Ruby, everything is an object. Every bit of information and code can be given their own properties and actions. Object-oriented programming calls properties by the name instance variables and actions are known as methods. Ruby’s pure object-oriented approach is most commonly demonstrated by a bit of code which applies an action to a number.

5.times { print "We *love* Ruby -- it's outrageous!" }

In many languages, numbers and other primitive types are not objects. Ruby follows the influence of the Smalltalk language by giving methods and instance variables to all of its types. This eases one’s use of Ruby, since rules applying to objects apply to all of Ruby.

Ruby’s Flexibility

Ruby is seen as a flexible language, since it allows its users to freely alter its parts. Essential parts of Ruby can be removed or redefined, at will. Existing parts can be added upon. Ruby tries not to restrict the coder.

For example, addition is performed with the plus (+) operator. But, if you’d rather use the readable word plus, you could add such a method to Ruby’s builtin Numeric class.

class Numeric
  def plus(x)
    self.+(x)
  end
end

y = 5.plus 6
# y is now equal to 11

Ruby’s operators are syntactic sugar for methods. You can redefine them as well.

Blocks: a Truly Expressive Feature

Ruby’s block are also seen as a source of great flexibility. A programmer can attach a closure to any method, describing how that method should act. The closure is called a block and has become one of the most popular features for newcomers to Ruby from other imperative languages like PHP or Visual Basic.

Blocks are inspired by functional languages. Matz said, “in Ruby closures, I wanted to respect the Lisp culture3.”

search_engines =
  %w[Google Yahoo MSN].map do |engine|
    "http://www." + engine.downcase + ".com"
  end

In the above code, the block is described inside the do ... end construct. The map method applies the block to the provided list of words. Many other methods in Ruby leave a hole open for a coder to write their own block to fill in the details of what that method should do.

Ruby and the Mixin

Unlike many object-oriented languages, Ruby features single inheritance only, on purpose. But Ruby knows the concept of modules (called Categories in Objective-C). Modules are collections of methods.

Classes can mixin a module and receive all its methods for free. For example, any class which implements the each method can mixin the Enumerable module, which adds a pile of methods that use each for looping.

class MyArray
  include Enumerable
end

Generally, Rubyists see this as a much clearer way than multiple inheritance, which is complex and can be too restrictive.

Ruby’s Visual Appearance

While Ruby often uses very limited punctuation and usually prefers English keywords, some punctuation is used to decorate Ruby. Ruby needs no variable declarations. It uses simple naming conventions to denote the scope of variables.

  • var could be a local variable.
  • @var is an instance variable.
  • $var is a global variable.

These sigils enhance readability by allowing the programmer to easily identify the roles of each variable. It also becomes unnecessary to use a tiresome self. prepended to every instance member.

Beyond the Basics

Ruby has a wealth of other features, among which are the following:

  • Ruby has exception handling features, like Java or Python, to make it easy to handle errors.
  • Ruby features a true mark-and-sweep garbage collector for all Ruby objects. No need to maintain reference counts in extension libraries. As Matz says, “This is better for your health.”
  • Writing C extensions in Ruby is easier than in Perl or Python, with a very elegant API for calling Ruby from C. This includes calls for embedding Ruby in software, for use as a scripting language. A SWIG interface is also available.
  • Ruby can load extension libraries dynamically if an OS allows.
  • Ruby features OS independent threading. Thus, for all platforms on which Ruby runs, you also have multithreading, regardless of if the OS supports it or not, even on MS-DOS!
  • Ruby is highly portable: it is developed mostly on GNU/Linux, but works on many types of UNIX, Mac OS X, Windows 95/98/Me/NT/2000/XP, DOS, BeOS, OS/2, etc.

Other Implementations of Ruby

Ruby, as a language, has a few different implementations. This page has been discussing the reference implementation, in the community often referred to as MRI (“Matz’s Ruby Interpreter”) or CRuby (since it is written in C), but there are also others. They are often useful in certain situations, provide extra integration to other languages or environments, or have special features that MRI doesn’t.

Here’s a list:

  • JRuby is Ruby atop the JVM (Java Virtual Machine), utilizing the JVM’s optimizing JIT compilers, garbage collectors, concurrent threads, tool ecosystem, and vast collection of libraries.
  • Rubinius is ‘Ruby written in Ruby’. Built on top of LLVM, Rubinius sports a nifty virtual machine that other languages are being built on top of, too.
  • MacRuby is a Ruby that’s tightly integrated with Apple’s Cocoa libraries for Mac OS X, allowing you to write desktop applications with ease.
  • mruby is a lightweight implementation of the Ruby language that can be linked and embedded within an application. Its development is led by Ruby’s creator Yukihiro “Matz” Matsumoto.
  • IronRuby is an implementation “tightly integrated with the .NET Framework”.
  • MagLev is “a fast, stable, Ruby implementation with integrated object persistence and distributed shared cache”.
  • Cardinal is a “Ruby compiler for Parrot Virtual Machine” (Perl 6).

Some of those implementations, including MRI, follow the guidelines of RubySpec, a “complete executable specification for the Ruby programming language”.


Sinatra
(https://en.wikipedia.org/wiki/Sinatra_%28software%29)

Sinatra is a free and open source software web application library and domain-specific language written in Ruby. It is an alternative to other Ruby web application frameworks such as Ruby on Rails, Merb, Nitro, and Camping. It is dependent on the Rack web server interface.

Designed and developed by Blake Mizerany, Sinatra is small and flexible. It does not follow the typical model–view–controller pattern used in other frameworks, such as Ruby on Rails. Instead, Sinatra focuses on “quickly creating web-applications in Ruby with minimal effort.”[1]

Some notable companies and institutions that use Sinatra include Apple, BBC, the British Government’sGovernment Digital Service, LinkedIn, the National Security Agency, Engine Yard, Heroku, GitHub,and Songbird. Travis CI provides much of the financial support for Sinatra’s development.[9]

Sinatra was created and open-sourced in 2007.


Sinatra Official Site
(http://www.sinatrarb.com/)

Sinatra

require 'sinatra'

get '/hi' do
  "Hello World!"
end

and smoke it

$ gem install sinatra
$ ruby hi.rb
== Sinatra has taken the stage ...
>> Listening on 0.0.0.0:4567