Ruby on Rails – Installation

Ruby on Rails – Installation ”; Previous Next To develop a web application using Ruby on Rails Framework, you need to install the following software − Ruby The Rails Framework A Web Server A Database System We assume that you already have installed a Web Server and a Database System on your computer. You can use the WEBrick Web Server, which comes with Ruby. Most websites however use Apache or lightTPD web servers in production. Rails works with many database systems, including MySQL, PostgreSQL, SQLite, Oracle, DB2 and SQL Server. Please refer to a corresponding Database System Setup manual to set up your database. Let”s look at the installation instructions for Rails on Windows and Linux. Rails Installation on Windows Follow the steps given below for installing Ruby on Rails. Step 1: Check Ruby Version First, check if you already have Ruby installed. Open the command prompt and type ruby -v. If Ruby responds, and if it shows a version number at or above 2.2.2, then type gem –version. If you don”t get an error, skip Install Ruby step. Otherwise, we”ll install a fresh Ruby. Step 2: Install Ruby If Ruby is not installed, then download an installation package from rubyinstaller.org. Follow the download link, and run the resulting installer. This is an exe file rubyinstaller-2.2.2.x.exe and will be installed in a single click. It”s a very small package, and you”ll get RubyGems as well along with this package. Please check the Release Notes for more detail. Step 3: Install Rails Install Rails − With Rubygems loaded, you can install all of Rails and its dependencies using the following command through the command line − C:> gem install rails Note − The above command may take some time to install all dependencies. Make sure you are connected to the internet while installing gems dependencies. Step 4: Check Rails Version Use the following command to check the rails version. C:> rails -v Output Rails 4.2.4 Congratulations! You are now on Rails over Windows. Rails Installation on Linux We are installing Ruby On Rails on Linux using rbenv. It is a lightweight Ruby Version Management Tool. The rbenv provides an easy installation procedure to manage various versions of Ruby, and a solid environment for developing Ruby on Rails applications. Follow the steps given below to install Ruby on Rails using rbenv tool. Step 1: Install Prerequisite Dependencies First of all, we have to install git – core and some ruby dependences that help to install Ruby on Rails. Use the following command for installing Rails dependencies using yum. tp> sudo yum install -y git-core zlib zlib-devel gcc-c++ patch readline readline-devel libyaml-devel libffi-devel openssl-devel make bzip2 autoconf automake libtool bison curl sqlite-devel Step 2: Install rbenv Now we will install rbenv and set the appropriate environment variables. Use the following set of commands to get rbenv for git repository. tp> git clone git://github.com/sstephenson/rbenv.git .rbenv tp> echo ”export PATH = “$HOME/.rbenv/bin:$PATH”” >> ~/.bash_profile tp> echo ”eval “$(rbenv init -)”” >> ~/.bash_profile tp> exec $SHELL tp> git clone git://github.com/sstephenson/ruby-build.git ~/.rbenv/plugins/ruby-build tp> echo ”export PATH = “$HOME/.rbenv/plugins/ruby-build/bin:$PATH”” << ~/.bash_profile tp> exec $SHELL Step 3: Install Ruby Before installing Ruby, determine which version of Ruby you want to install. We will install Ruby 2.2.3. Use the following command for installing Ruby. tp> rbenv install -v 2.2.3 Use the following command for setting up the current Ruby version as default. tp> rbenv global 2.2.3 Use the following command to verify the Ruby version. tp> ruby -v Output ruby 2.2.3p173 (2015-08-18 revivion 51636) [X86_64-linux] Ruby provides a keyword gem for installing the supported dependencies; we call them gems. If you don”t want to install the documentation for Ruby-gems, then use the following command. tp> echo “gem: –no-document” > ~/.gemrc Thereafter, it is better to install the Bundler gem, because it helps to manage your application dependencies. Use the following command to install bundler gem. tp> gem install bundler Step 4: Install Rails Use the following command for installing Rails version 4.2.4. tp> install rails -v 4.2.4 Use the following command to make Rails executable available. tp> rbenv rehash Use the following command for checking the rails version. tp> rails -v Output tp> Rails 4.2.4 Ruby on Rails framework requires JavaScript Runtime Environment (Node.js) to manage the features of Rails. Next, we will see how we can use Node.js to manage Asset Pipeline which is a Rails feature. Step 5: Install JavaScript Runtime Let us install Node.js from the Yum repository. We will take Node.js from EPEL yum repository. Use the following command to add the EPEL package to the yum repository. tp> sudo yum -y install epel-release Use the following command for installing the Node.js package. tp> sudo yum install nodejs Congratulations! You are now on Rails over Linux. Step 6: Install Database By default, Rails uses sqlite3, but you may want to install MySQL, PostgreSQL, or other RDBMS. This is optional; if you have the database installed, then you may skip this step and it is not mandatory that you have a database installed to start the rails server. For this tutorial, we are using PostgreSQL database. Therefore use the following commands to install PostgreSQL. tp> sudo yum install postgresql-server postgresql-contrib Accept the prompt, by responding with a y. Use the following command to create a PostgreSQl database cluster. tp> sudo postgresql-setup initdb Use the following command to start and enable PostgreSQL. tp> sudo systemctl start postgresql tp> sudo systemctl enable postgresql Keeping Rails Up-to-Date Assuming you have installed Rails using RubyGems, keeping it up-to-date is relatively easy. We can use the same command in both Windows and Linux platform. Use the following command − tp> gem update rails Output The following screenshot shows a Windows command prompt. The Linux terminal also provides the same output. This will automatically update your Rails installation. The next time you restart your application, it will pick up this latest version of Rails. While using this command, make sure you are connected to the internet. Installation Verification You

Ruby on Rails – References Guide

Ruby on Rails – Quick Reference Guide ”; Previous Next Here we have listed out all the important functions, scripts, validations etc. You can bookmark this page for easy access. Ruby on Rails – Rake Utility Ruby on Rails – The Scripts Ruby on Rails – The Plugins Ruby on Rails – The Generators Ruby on Rails – Model Relations Ruby on Rails – Controller Methods Ruby on Rails – Layouts Ruby on Rails – Render Ruby on Rails – HTML Forms Ruby on Rails – RXML Ruby on Rails – html.erb Ruby on Rails – HTML Links Ruby on Rails – Session and Cookies Ruby on Rails – User Input Validations Ruby on Rails – Maths Functions Ruby on Rails – Finders Ruby on Rails – Nested with-scope Ruby on Rails – Callback Functions Print Page Previous Next Advertisements ”;

Ruby on Rails – Routes

Ruby on Rails – Routes ”; Previous Next The routing module provides URL rewriting in native Ruby. It”s a way to redirect incoming requests to controllers and actions. It replaces the mod_rewrite rules. Best of all, Rails” Routing works with any web server. Routes are defined in app/config/routes.rb. Think of creating routes as drawing a map for your requests. The map tells them where to go based on some predefined pattern − Rails.application.routes.draw do Pattern 1 tells some request to go to one place Pattern 2 tell them to go to another … end Example Let us consider our library management application contains a controller called BookController. We have to define the routes for those actions which are defined as methods in the BookController class. Open routes.rb file in library/config/ directory and edit it with the following content. Rails.application.routes.draw do get ”book/list” get ”book/new” post ”book/create” patch ”book/update” get ”book/list” get ”book/show” get ”book/edit” get ”book/delete” get ”book/update” get ”book/show_subjects” end The routes.rb file defines the actions available in the applications and the type of action such as get, post, and patch. Use the following command to list all your defined routes, which are useful for tracking down routing problems in your application, or giving you a good overview of the URLs in an application you”re trying to get familiar with. library> rake routes What is Next? Next, we will create the code to generate screens to display data and to take input from the user. Print Page Previous Next Advertisements ”;

Ruby on Rails – Introduction

Ruby on Rails – Introduction ”; Previous Next What is Ruby? Before we ride on Rails, let us recapitulate a few points of Ruby, which is the base of Rails. Ruby is the successful combination of − Smalltalk”s conceptual elegance, Python”s ease of use and learning, and Perl”s pragmatism. Ruby is − A high-level programming language. Interpreted like Perl, Python, Tcl/TK. Object-oriented like Smalltalk, Eiffel, Ada, Java. Why Ruby? Ruby originated in Japan and now it is gaining popularity in US and Europe as well. The following factors contribute towards its popularity − Easy to learn Open source (very liberal license) Rich libraries Very easy to extend Truly object-oriented Less coding with fewer bugs Helpful community Although we have many reasons to use Ruby, there are a few drawbacks as well that you may have to consider before implementing Ruby − Performance Issues − Although it rivals Perl and Python, it is still an interpreted language and we cannot compare it with high-level programming languages like C or C++. Threading model − Ruby does not use native threads. Ruby threads are simulated in the VM rather than running as native OS threads. Sample Ruby Code Here is a sample Ruby code to print “Hello Ruby” # The Hello Class class Hello def initialize( name ) @name = name.capitalize end def salute puts “Hello #{@name}!” end end # Create a new object h = Hello.new(“Ruby”) # Output “Hello Ruby!” h.salute Output − This will produce the following result − Hello Ruby! Embedded Ruby Ruby provides a program called ERB (Embedded Ruby), written by Seki Masatoshi. ERB allows you to put Ruby codes inside an HTML file. ERB reads along, word for word, and then at a certain point, when it encounters a Ruby code embedded in the document, it starts executing the Ruby code. You need to know only two things to prepare an ERB document − If you want some Ruby code executed, enclose it between <% and %>. If you want the result of the code execution to be printed out, as a part of the output, enclose the code between <%= and %>. Here”s an example. Save the code in erbdemo.rb file. Note that a Ruby file will have an extension .rb − <% page_title = “Demonstration of ERB” %> <% salutation = “Dear programmer,” %> <html> <head> <title><%= page_title %></title> </head> <body> <p><%= salutation %></p> <p>This is an example of how ERB fills out a template.</p> </body> </html> Now, run the program using the command-line utility erb. tp> erb erbdemo.rb This will produce the following result − <html> <head> <title>Demonstration of ERb</title> </head> <body> <p>Dear programmer,</p> <p>This is an example of how ERb fills out a template.</p> </body> </html> What is Rails? An extremely productive web-application framework. Written in Ruby by David Heinemeier Hansson. You could develop a web application at least ten times faster with Rails than you could with a typical Java framework. An open source Ruby framework for developing database-backed web applications. Configure your code with Database Schema. No compilation phase required. Full Stack Framework Includes everything needed to create a database-driven web application, using the Model-View-Controller pattern. Being a full-stack framework means all the layers are built to work seamlessly together with less code. Requires fewer lines of code than other frameworks. Convention over Configuration Rails shuns configuration files in favor of conventions, reflection, and dynamic runtime extensions. Your application code and your running database already contain everything that Rails needs to know! Rails Strengths Rails is packed with features that make you more productive, with many of the following features building on one other. Metaprogramming Where other frameworks use extensive code generation from scratch, Rail framework uses Metaprogramming techniques to write programs. Ruby is one of the best languages for Metaprogramming, and Rails uses this capability well. Rails also uses code generation but relies much more on Metaprogramming for the heavy lifting. Active Record Rails introduces the Active Record framework, which saves objects into the database. The Rails version of the Active Record discovers the columns in a database schema and automatically attaches them to your domain objects using metaprogramming. Convention over configuration Most web development frameworks for .NET or Java force you to write pages of configuration code. If you follow the suggested naming conventions, Rails doesn”t need much configuration. Scaffolding You often create temporary code in the early stages of development to help get an application up quickly and see how major components work together. Rails automatically creates much of the scaffolding you”ll need. Built-in testing Rails creates simple automated tests you can then extend. Rails also provides supporting code called harnesses and fixtures that make test cases easier to write and run. Ruby can then execute all your automated tests with the rake utility. Three environments Rails gives you three default environments: development, testing, and production. Each behaves slightly differently, making your entire software development cycle easier. For example, Rails creates a fresh copy of the Test database for each test run. Print Page Previous Next Advertisements ”;

Ruby on Rails – Views

Ruby on Rails – Views ”; Previous Next A Rails View is an ERb program that shares data with controllers through mutually accessible variables. If you look in the app/views directory of the library application, you will see one subdirectory for each of the controllers, we have created: book. Each of these subdirectories was created automatically when the same-named controller was created with the generate script. Rails let”s you know that you need to create the view file for each new method. Each method you define in the controller needs to have a corresponding erb file, with the same name as the method, to display the data that the method is collecting. So let”s create view files for all the methods we have defined in the book_controller.rb. While executing these views, simultaneously check these actions are applicable into the database or not. Creating View File for list Method Create a file called list.html.erb using your favourite text editor and save it to app/views/book. After creating and saving the file, refresh your web browser. You should see a blank page; if you don”t, check the spelling of your file and make sure that it is exactly the same as your controller”s method. Now, display the actual content. Let us put the following code into list.html.erb. <% if @books.blank? %> <p>There are not any books currently in the system.</p> <% else %> <p>These are the current books in our system</p> <ul id = “books”> <% @books.each do |c| %> <li><%= link_to c.title, {:action => ”show”, :id => c.id} -%></li> <% end %> </ul> <% end %> <p><%= link_to “Add new Book”, {:action => ”new” }%></p> The code to be executed is to check whether the @books array has any objects in it. The .blank? method returns true if the array is empty, and false if it contains any objects. This @books object was created in controller inside the list method. The code between the <%= %> tags is a link_to method call. The first parameter of link_to is the text to be displayed between the <a> tags. The second parameter is what action is called when the link is clicked. In this case, it is the show method. The final parameter is the id of the book that is passed via the params object. Now, try refreshing your browser and you should get the following screen because we don”t have any book in our library. Creating View File for new Method Till now, we don”t have any book in our library. We have to create few books in the system. So, let us design a view corresponding to the new method defined in the book_controller.rb. Create a file called new.html.erb using your favorite text editor and save it to app/views/book. Add the following code to the new.html.erb file. <h1>Add new book</h1> <%= form_tag :action => ”create” do %> <p><label for = “book_title”>Title</label>: <%= text_field ”books”, ”title” %></p> <p><label for = “book_price”>Price</label>: <%= text_field ”books”, ”price” %></p> <p><label for = “book_subject_id”>Subject</label>: <%= collection_select(:books, :subject_id, @subjects, :id, :name, prompt: true) %></p> <p><label for = “book_description”>Description</label><br/> <%= text_area ”books”, ”description” %></p> <%= submit_tag “Create” %> <% end -%> <%= link_to ”Back”, {:action => ”list”} %> Here form_tag method interprets the Ruby code into a regular HTML <form> tag using all the information supplied to it. This tag, for example, outputs the following HTML − <form action = “/book/create” method = “post”> Next method is text_field that outputs an <input> text field. The parameters for text_field are object and field name. In this case, the object is book and the name is title. Rails method called collection_select, creates an HTML select menu built from an array, such as the @books one. There are five parameters, which are as follows − :book − The object you are manipulating. In this case, it”s a book object. :subject_id − The field that is populated when the book is saved. @books − The array you are working with. :id − The value that is stored in the database. In terms of HTML, this is the <option> tag”s value parameter. :name − The output that the user sees in the pull-down menu. This is the value between the <option> tags. The next used is submit_tag, which outputs an <input> button that submits the form. Finally, there is the end method that simply translates into </form>. Go to your browser and visit http://localhost:3000/book/new. This will give you the following screen. Enter some data in this form and then click the Create button. Here i have added the following details into the fields − Title: Advance Physics Price: 390 Subject: Physics Description: This is test to create new book When you click the Create button, it will call the create method, which does not need any view because this method is using either list or new methods to view the results. So, when you click the Create button, the data should submit successfully and redirect you to the list page, in which you now have a single item listed as follows − If you click the link, you should see another Template is missing error, since you haven”t created the template file for show method yet. Creating View File for show Method This method will display the complete detail about any book available in the library. Create a show.html.erb file under app/views/book and populate it with the following code − <h1><%= @book.title %></h1> <p> <strong>Price: </strong> $<%= @book.price %><br /> <strong>Subject :</strong> <%= @book.subject.name %><br /> <strong>Created Date:</strong> <%= @book.created_at %><br /> </p> <p><%= @book.description %></p> <hr /> <%= link_to ”Back”, {:action => ”list”} %> This is the first time you have taken the full advantage of associations, which enable you to easily pull data from related objects. The format used is @variable.relatedObject.column. In this instance, you can pull the subject”s name value through the @book variable using the belongs_to associations. If click on any listed record then it will show you the following screen. Creating View File for

Ruby – Ruby on Rails Tutorial

Ruby on Rails Tutorial PDF Version Quick Guide Resources Job Search Discussion Ruby on Rails is an extremely productive web application framework written in Ruby by David Heinemeier Hansson. This tutorial gives you a complete understanding on Ruby on Rails. Audience This tutorial has been designed for beginners who would like to use the Ruby framework for developing database-backed web applications. Prerequisites You need to have a basic knowledge of Ruby and object-oriented programming to understand this tutorial. In addition, you need to be familiar with internet and websites programming in general. Print Page Previous Next Advertisements ”;

Ruby – Home

Ruby Tutorial PDF Version Quick Guide Resources Job Search Discussion Ruby is a scripting language designed by Yukihiro Matsumoto, also known as Matz. It runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX. This tutorial gives a complete understanding on Ruby. Audience This tutorial has been prepared for beginners to help them understand the basic to advanced concepts related to Ruby Scripting languages. Prerequisites Before you start practicing with various types of examples given in this tutorial, we are making an assumption that you are already aware of computer programs and programming languages in general. Print Page Previous Next Advertisements ”;