Ruby and Rails Introduction by rubyrails.ninja

Ruby is a programming language created in 1995. It was influenced by other programming languages such as Perl, Smalltalk, Eiffel, Ada and Lisp.

Ruby is friendly for beginners. Ruby’s community is big and there are a lot of documentations available. There are also a lot of ready-to-use tools that are called Ruby gems.

Rails is the Ruby's web development toolkit that allows you to develop fast web application. It was create in 2005.

Rails framework uses also gems to facilitate and accelarate development. The community is very active and open source oriented.

Let’s go into Ruby and Rails programming ! Mini course curriculum I Ruby language

a) Dynamic types b) Loops and iterators ) Errors handling d) Native libraries e) Classes and modules f) Gems g) Irb console and files .rb h) What to do with Ruby ? II Rails framework

a) MVC (model, view, controller) b) Gemfile c) Bundle and Rake d) Routes e) Config directory f) Lib directory g) Server and console h) Scaffolding I Ruby language

a) Dynamic types

You don’t have to choose one type for your Ruby’s variable : # this is a comment

a = 1 puts a.class # this is a fixnum integer

a = "string" puts a.class # this is a string

a = 3,23 puts a.class # this is a float

a = [] puts a.class # this is an array

a = Object.new puts a.class # this is a personal object

a = 2.0 puts a.class puts a.to_i puts a.to_i.class

a = "my wonderful string" a.is_a?(String) # true a.respond_to?(:to_s) # true In Ruby, everything is an object! Basic types are threated as object too :

a=25420 # integer a.succ # a successor , a + 1 a.to_s a.class

b = "abracadabra" # string b.size b << "alcatraz" b.start_with?("ab", "abra") b.include?("bra") b.split("a").reject(&:empty?) # split command cuts your # string with the choosen caracter into array and # delete empty record

c = [1,2,3,4,5,6,7,8,9,0] # array c.first c.take(3) c.include?(5) c.drop(3) c.push(1) c << 2 << 3 c.reverse c.delete_if {|x| x <= 5 }

d = [ ["label 1",1,0],["label 2",2,0.2], ["label 3",3,0],["label 4",4,0.4] ] # multi dimensional array d.map { |x| x[0] if x[1] > 1 && x[2].is_a?(Float) }.compact! # Keeps the first sub array element if the second sub # array element is # superior to integer 1 and if the # third sub array element is a float. The result is # cleaned from nil element with compact command. # the ! Caracter is used to destruct the original object # to replace with new datas

e = { "the_one" => 10, "the_two" => 6, "the_three" => 12 } # hash with key / value puts e["the_one"] # the_one is the key b) Loops and iterators i, max = 0, 5 while i <= max do puts "#{i} is not the max" i+=1 end i, max = 0, 5 until i >= max do puts "#{i} is not the max" i+=1 end for i in 0..5 puts "#{i} is inferior to 6" end

(0..5).each do |i| puts "#{i} is inferior to 6" end

5.times do puts "one time" end

# there are also array iterators a = ["one","two","three","for","five","six","seven","eight"] a.each do |record| puts record end a.each_slice(2) { |my_slice| puts my_slice} a.each_with_index do |record,index| puts "#{record} #{index}" end

# and for hashs a = {"zero" => 0, "one" =>1, "two" =>2, "three" => 3} a.each_key {|key| puts key} a.each {|key, value| puts "#{key} is #{value}" } c) Errors handling

#begin rescue ensure i, max, max_retry = 0, 100, 5

begin # i+=1 # some code using i rescue Exception => e # if an error occurs in begin bloc # puts e.message # retry if i < max_retry ensure # doing important things here end until i >= max

# raise def inverse(x) raise ArgumentError, "Argument is not numeric" unless x.is_a? Numeric 1.0 / x end puts inverse(2) puts inverse("not a number")

d) Native Libraries

Ruby language have a lot of standard libraries for basic objects : String, Integer, Float, Array, Hash.

But there are also libraries for more complex objects : Class, Complex, Math, Enumerable, Time, File, Dir, IO, Thread, Process, Exception, ..

a = Time.now b = Math.sqrt(4) file = File.open(filename, 'r') filenames = Dir.entries("test_directory") e) Classes and modules

When you need to create programs, you can use modules and classes to build your thinking.

Imagine that we wanted to create a program that collects tweets and analyzes them to find specific elements using machine learning. Then we will create a module that can be called TweetsAnalysis with two classes. The first is the one that would be used to interact with Twitter (connexion, tweets extraction). The second class will be used to analyze the tweets.

module TweetsAnalysis class TwitterInteraction def initialize # do some inits end def connect # specific method to connect Twitter API end def method # do other stuffs end end class TweetsAnalyser def initialize # do some inits end def method # do other stuffs end end end

credentials = [login,password,API_code] include TweetsAnalysis

twit = TwitterInteraction.new twit.connect(credentials) collected_datas = twit.method

analyser = TweetsAnalyser.new analyser.method(collected_datas) f) Gems

Ruby has a dedicated package manager : Rubygems. This manager allows you to install and use external packages. There are a lot of different gems available .. you can install them using the command "ruby gem install the_gem_you_want"

# Browser automation .. require 'watir-webdriver'

browser = Watir::Browser.new :chrome # open browser browser.goto("https://rubyrails.ninja") # go to page

# Playing with twitter .. require 'twitter_oauth'

@twitter_client = TwitterOAuth::Client.new( :consumer_key => '', :consumer_secret => '', :token => '', :secret => '' ) res = @twitter_client.update('I can schedule my tweets!')

# Do you want to use google speech-to-text API ? require 'speech'

audio = Speech::AudioToText.new("my_audio_file.wav") puts audio.to_text

# HTTP Protocols require 'net/http' require "uri"

uri = URI.parse("https://rubyrails.ninja") response = Net::HTTP.get_response(uri) # Will print response.body Net::HTTP.get_print(uri) # Playing with Youtube .. # This snippet will get every user id that comment on # the youtube channels you choose require 'yt' ls_channel_url= ["https://www.youtube.com/user/whatyouwant"]

Yt.configure do |config| config.client_id = '' config.client_secret = 'secret' config.api_key = 'api key' end

ls_comments_user = [] # global list ls_channel_url.each do |url| # for each channel channel = Yt::Channel.new url: url videos = channel.videos # get video list comment_user = [] # channel list videos.each do |vid| # for each video in channel cnt=video.comment_count # get comment count comment_user << vid.comment_threads.take(cnt).map(&:author_display_name) # add comments author’s name to channel list end ls_comments_user << comment_user.flatten # add channel list to global list end result = ls_comments_user.flatten.uniq # result : global list of users who comment specific channels g) Irb console and files .rb

There are two ways to execute Ruby code.

You can create a file with .rb extension in order to execute this file with the ruby interpreter. Example, create a file my_first_program.rb with the code below. Once done, execute it with the command line "ruby my_first_program.rb test 2 0.35"

#!/usr/bin/env ruby # encoding: UTF-8

def main argv argv.each do |record| puts record end end

main(ARGV)

The second way to execute Ruby code is the live console. Just type "irb" in your terminal and the prompt appears.

2.2.5 :001 > def method(parameters) 2.2.5 :002?> parameters.each do |record| 2.2.5 :003 > puts record 2.2.5 :004?> end 2.2.5 :005?> end => :method 2.2.5 :006 > method(["test",1,0.35]) test 1 0.35 => ["test", 1, 0.35] h) What to do with Ruby ?

Well … you can build almost everything with it. From blockchain to machine learning, without forget browser automation, facebook marketing, image or audio processing, natural language processing, …, there are no limits. The only limits you will meet are your thinking limits:)

There are different ways to package your code. You can build scripts (file.rb) to acheive specific tasks as shown in the previous pages and execute them in terminal.

You can create an application with a GUI (graphical user interface) with the "shoesrb".

You can websites, email autoresponder, chatbots and web application with Rails framework.

As you see, with a bit of work, you can acheive all your dreams:)

I am here to help you to do that !

Let’s see now how Rails works.. II Rails framework

a - MVC

Rails is the Ruby web framework. This framework has been created in order to facilitate and to accelarate web application creation. Creating a Rails application is quick because everything you create is fully covered. You can use the database of your choice : MySQL, PostgreSQL, SQLite, MongoDB, Redis, RDDB, couchDB, rethinkDB, strokeDB.

Let’s see what MVC is. The browser execute controller that interact with model and the database through ActiveRecord. The controller can then use the views to render informations and routing through ActionView. Another more detailled view here :

Ruby and Rails is a fullstack framework. It can handle both front-end and back-end. The front-end is the client part. It is composed of html, and stylesheet (css). You can use components into the front-end to make dynamic webpages. The back-end is the server side. Ruby on Rails allow you to interact directly with the database. Someone fill a form and that will create the database entries automatically. Simple !

To simply create a Rails application :

rails new my_new_app You can now create anything you want in your rails app :

rails g controller my_controller rails g model my_model rails g mailer my_mailer

Once your application is created, you can noticed that there is a particular tree. I will explain you below every important things to know about Rails tree.

Typical tree from a Rails application : ├── app │ ├── assets │ ├── controllers │ ├── helpers │ ├── mailers │ ├── models │ └── views ├── bin ├── config │ ├── environments │ ├── initializers │ ├── locales ├── config.ru ├── db │ ├── migrate │ ├── schema.rb │ └── seeds.rb ├── Gemfile ├── Gemfile.lock ├── lib ├── log │ ├── development.log │ └── production.log ├── out_histo ├── package. ├── public │ ├── assets ├── Rakefile ├── README.md ├── test ├── tmp └── vendor The app directory is the main part of your Ruby on Rails application.

It contains assets directory (, stylesheets, fonts, images, ..) you need. You can create a new asset category if needed for your app (like videos if you have a lot a videos).

It also contains controllers directory in which you will find every controller you created. Controllers are the interface that routes and displays the content of pages. If you want to create static pages, generate a simple controller with the command : rails g controller StaticPages

There is also a model directory where you can modify your models to fit to your needs. Models are the central part of a Rails app in my opinion. That is where you create your application structure. User model, Newsletter model, product model, …

There is the views directory used to write your html pages. This is here that you have to integrate html parts with javascript/css calls.

The helpers directory is connected to the views part. Helpers are made to lighten your views and keep them simple and skinny.

And there is the mailer directory where you can create some mailers that interact with your Rails app. Someone sign ups in your application, send him an email just after to keep contact.

I will give you an example of how Rails works. I will detail how the model, the controller and the view are related. I use a newsletter model that will catch email from page form. We use email and origine fields.

Copy paste commands below. They will create model, controller and views. rails g model newsletter email:string origine:string rails g controller newsletter The model class Newsletter < ActiveRecord::Base attr_accessible :email, :origine validates_uniqueness_of :email end

The controller class NewslettersController < ApplicationController def new @newsletter = Newsletter.new end

def create @newsletter = Newsletter.new(params[:newsletter]) if @newsletter.save redirect_to :back, notice: 'Thank You for signup' else redirect_to :back, alert: 'Email error' end end end

The view (app/views/newsletters/new.html.erb) <%= form_for @newsletter do |f| %> <%= f.text_field :email, placeholder: "Your email address" %> <%= f.hidden_field :origine, value: "page origine" %> <%= f.submit "Signup NOW !" %> <% end %>

When routing visitor from an url, Rails will use the new controller method that will create a global variable @newsletter. Then, the controller will display the corresponding view new.html.erb. When validating the form, the create controller method will be triggered from input datas. Before saving the newsletter (@newsletter.save), the model will test the uniqueness of the email field in the database. If there is another entry with the email field, then the model will trigger an error.

Some of Rails motto are : DRY (don’t repeat yourself), Convention over configuration, Fat model skinny controller. Those motto are guidelines to follow to keep your application simple and maintainable. b – Gemfile

The Gemfile is the file containing every gems you need to use in your rails application. Once you add a new gem to it, you have to execute "bundle install" command in order to update your Rails listing. Every gem is used in a specific way (devise is the user management gem for Rails application, letsrate is a rating gem, …). And you can specify which version you want to use (in case of conflicts). Here is my Gemfile for rubyrails.ninja

gem 'rails', '3.2.21' gem 'therubyracer', platforms: :ruby gem 'test-unit' gem 'passenger'

# Bundle edge Rails instead: # gem 'rails', :git => 'git://.com/rails/rails.git'

gem 'mysql2', '~> 0.3.18' gem 'devise' gem 'valid_email' gem 'ahoy_matey', "1.5.2" gem 'activeuuid' gem 'fluent-logger' gem 'browser' gem 'activemerchant' gem 'letsrate', "1.0.8" gem 'mail_form' gem 'simple_form' gem 'rails-i18n' gem 'delayed_job_active_record' gem 'devise-async' gem 'daemons' gem 'rack-tracker' gem 'omniauth-facebook' gem 'chartkick' gem "highcharts-rails" gem "heatmap" gem 'shortener', :git => 'git://github.com/gitgary/shortener' gem 'ahoy_email' gem 'invisible_captcha' gem 'vanity' geù ‘dkim’ c – Bundle and Rake

Bundler is a Ruby dependancy management tool.

« Bundler: a gem to bundle gems. Bundler makes sure Ruby applications run the same code on every machine. It does this by managing the gems that the application depends on. Given a list of gems, it can automatically download and install those gems, as well as any other gems needed by the gems that are listed». You need to execute bundle command in rails to update gem list after adding or deleting some gems. bundle install will make the trick.

Rake is a software task management tool.

« Rake is Ruby Make, a standalone Ruby utility that replaces the Unix utility 'make', and uses a 'Rakefile' and .rake files to build up a list of tasks. In Rails, Rake is used for common administration tasks, especially sophisticated ones that build off of each other. »

You can get a list of Rake tasks available by typing rake --tasks. After update migration files, run rake db:migrate. To truncate your database, use rake db:reset db:migrate. If you are using delayed_job, you can clean pending task by rake jobs:clear or execute task without waiting for delay by rake jobs:work. To get all your application routing, execute rake routes.

d - Routes

The Rails router recognizes URLs and dispatches them to a controller's action, or to a Rack application. It can also generate paths and URLs, avoiding the need to hardcode strings in your views.

There is a file in your Rails config directory that is specially important for routing visitors. This file routes.rb is where you will define your routes. e – Config directory

The config directory contains different important things :

- database.yml is the file you need to configure the access to your database, you can also add another yaml configuration files in this directory,

- application.rb is the file where you can customize components for the whole application,

- The environments directory contains specific configuration files for each environnement (development, test and production). You can use different configurations depending on whether you are in development mode or production,

You can access those configurations from model or controller with Rails.configuration.variable

- routes.rb is the file that routes user from an url to a specific page (controller#method),

- The locales directory store translation files if your application is multilingual,

- The initializer directory is the place where you put specific configuration files for the gems include in your application.

f – Lib directory

The lib directory is the place where you can put your own Ruby modules and classes. For example, this is there that I put machine learning module used in a model or a controller. The idea behind is that you can create a complex module using existing gems in that directory. g – Server and console

When coding on your project, before production deployment, you just need to test your developments. Use the light rails webserver (before Webrick, Puma in rails 5.x) to do such actions :

prompt@admin:~/my_app_directory$ rails s => Booting Puma => Rails 5.1.0 application starting in development on http://localhost:3000 => Run `rails server -h` for more startup options Puma starting in single mode... * Version 3.8.2 (ruby 2.2.5-p319), codename: Sassy Salamander * Min threads: 5, max threads: 5 * Environment: development * Listening on tcp://0.0.0.0:3000 Use Ctrl-C to stop

For back-end debugging, you can use rails console that allow you every query to be executed as in your rails application :

prompt@admin:~/my_app_directory$ rails c Running via Spring preloader in process 2703 Loading development environment (Rails 5.1.0) 2.2.5 :001 > User.last (0.3ms) SET @@SESSION.sql_mode = CONCAT(CONCAT(@@sql_mode, ',STRICT_ALL_TABLES'), ',NO_AUTO_VALUE_ON_ZERO'), @@SESSION.sql_auto_is_null = 0, @@SESSION.wait_timeout = 2147483 User Load (0.1ms) SELECT `users`.* FROM `users` ORDER BY `users`.`id` DESC LIMIT 1 => # h – Scaffolding

Creating model, view and controller can be more simple with scaffolding. This is one of the powerful features of Ruby on Rails. It allows from very few commands and code to have a CRUD (Create-Read-Update-Delete, the 4 basic functions of a database) complete on a given component. Choose the model name and use the following command :

rails g scaffold my_model

This command will create everything you need : controller , model, view, helper and asset : invoke active_record create db/migrate/20130124100759_create_my_models.rb create app/models/my_model.rb invoke test_unit create test/unit/my_model_test.rb create test/fixtures/my_models.yml route resources :my_models invoke scaffold_controller create app/controllers/my_models_controller.rb invoke erb create app/views/my_models create app/views/my_models/index.html.erb create app/views/my_models/edit.html.erb create app/views/my_models/show.html.erb create app/views/my_models/new.html.erb create app/views/my_models/_form.html.erb invoke test_unit create test/functional/my_models_controller_test.rb invoke helper create app/helpers/my_models_helper.rb invoke test_unit create test/unit/helpers/my_models_helper_test.rb invoke assets

invoke coffee create app/assets/javascripts/my_models.js.coffee invoke scss create app/assets/stylesheets/my_models.css.scss invoke scss identical app/assets/stylesheets/models.css.scss Conclusion :

Those mini courses are over. You now have a little knowledge about the basics uses of Ruby and Rails. You also know the abilities offered by this language and its web framework.

What do you think about them ? Do them make you want to learn Ruby or Rails ? Are they good written ? What does it miss by your opinion ? Your answers can help me to improve those tutorials :)

If you want to learn coding, I am interested into your needs. Employed since 13 years, I would like to quit my job to become online teacher.

I am actually launching online trainings I created few advanced Ruby and Rails online courses, dealing with blockchains, chatbots, machine learning, marketing funnel, browser automation, .... And I am thinking about offering personal coaching. That is why your needs and your opinions interest me.

I am coding since almost 20 years and I use Ruby and Rails since 8 years so I think I can teach you the best way to learn code with Ruby and Rails that are wonderful tools when mastered.

Do not hesitate to write me an email :)