Ruby and Rails Introduction by Rubyrails.Ninja

Ruby and Rails Introduction by Rubyrails.Ninja

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 c) 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 make 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, javascript and stylesheet (css). You can use Ruby on Rails 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.

View Full Text

Details

  • File Type
    pdf
  • Upload Time
    -
  • Content Languages
    English
  • Upload User
    Anonymous/Not logged-in
  • File Pages
    22 Page
  • File Size
    -

Download

Channel Download Status
Express Download Enable

Copyright

We respect the copyrights and intellectual property rights of all users. All uploaded documents are either original works of the uploader or authorized works of the rightful owners.

  • Not to be reproduced or distributed without explicit permission.
  • Not used for commercial purposes outside of approved use cases.
  • Not used to infringe on the rights of the original creators.
  • If you believe any content infringes your copyright, please contact us immediately.

Support

For help with questions, suggestions, or problems, please contact us