Ruby On Rails

Document Sample
Ruby On Rails Powered By Docstoc
					Introduction to Ruby

WING Group Meeting
   9 Jun 2006
   Min-Yen Kan
                   What is Ruby?
   An interpreted language
       a.k.a dynamic, scripting
       e.g., perl
   Object Oriented
       Single inheritance
   High level
       Good support for system calls, regex and CGI
   Relies heavily on convention for syntax
                       Hello World
#!/ usr/bin/env ruby            shell script directive to run ruby
                                     Needed to run any shell script
puts “Hello world”              Call to method puts to write out
                                 “Hello world” with CR

                                Make program executable

$ chmod a+x helloWorld.rb
$ helloWorld.rb
Hello world
                      Basic Ruby
   Everything is an object
   Variables are not typed
   Automatic memory allocation and garbage
   Comments start with # and go to the end of the
       You have to escape \# if you want them elsewhere
   Carriage returns mark the end of statements
   Methods marked with def … end
                 Control structures
If…elsif…else…end               elsif keeps blocks at same
case when <condition> then      case good for checks on
   <value>… else… end            multiple values of same
                                 expression; can use ranges
unless <condition> … end
                                      grade = case score
while <condition>… end                    when 90..100 then “A”
                                          when 80..90 then “B”
until <condition>… end                    else “C”

#.times (e.g. 5.times())        Looping constructs use end
#.upto(#) (e.g. 3.upto(6))       (same as class definitions)

<collection>.each {block}       Various iterators allow code
                                 blocks to be run multiple times
             Ruby Naming Conventions
   Initial characters
       Local variables, method parameters, and method names 
        lowercase letter or underscore
       Global variable  $
       Instance variable  @
       Class variable  @@
       Class names, module names, constants  uppercase letter
   Multi-word names
       Instance variables  separate words with underscores
       Class names  use MixedCase
   End characters
       ? Indicates method that returns true or false to a query
       ! Indicates method that modifies the object in place rather than
        returning a copy (destructive, but usually more efficient)
                     Another Example
class Temperature
  Factor = 5.0/9                Factor is a constant
 def store_C(c)                 5.0 makes it a float
   @celsius = c

 def store_F(f)                 4 methods that get/set
   @celsius = (f - 32)*Factor
 end                              an instance variable
 def as_C
 end                            Last evaluated
  def as_F                        statement is
    (@celsius / Factor) + 32
                                  considered the return
end # end of class definition     value
                             Second Try
class Temperature
  Factor = 5.0/9
                                  attr_accessor creates setter
  attr_accessor :c                  and getter methods
  def f=(f)
                                    automatically for a class
    @c = (f - 32) * Factor          variable

  def f                           initialize is the name for a
    (@c / Factor) + 32
  end                               classes’ constructor
  def initialize (c)
    @c = c                        Don’t worry - you can always
                                    override these methods if you
                                    need to
t =
puts t.f # 77.0
t.f = 60 # invokes f=()           Calls to methods don’t need () if
puts t.c # 15.55                    unambiguous
              Regular Expressions

/[A-Z]/i                    First class objects in
/[^>]+/                      ruby
/<A[^>]+>.*<\/A>/im         Sandwiched between
/([^\t]+)/                  Quiz: How do you
                             make a regexp for
/^([^\t]+)\t([^\t]+)$/       <A>…</A>?
         Input and Output - tsv files
f = ARGV[0]
                          ARGV is a special array
while ! f.eof?
  line = f.gets            holding the
  if line =~ /^#/          command-line tokens
  elsif line =~ /^\s*$/
    next                  Gets a line
    puts line             If it’s not a comment or
  end                         a blank line
                          Print it
                 Processing TSV files
h =
                                Declare a hash table
f = ARGV[0]
while ! f.eof?                  Get lines without \n or \r\n - chomp
  line = f.gets.chomp
  if line =~ /^\#/
                                split lines into fields delimited with
    next                           tabs
  elsif line =~ /^\s*$/
                                Store some data from each field into
  else                             the hash
    tokens = line.split /\t/
    h[tokens[2]] = tokens[1]
  end                           Sort the keys - sort method takes a
end                               block of code as input
                                each creates an iterator in which k is
keys =                            set to a value at each pass
  h.keys.sort {|a,b| a <=> b}
keys.each {|k|
                                #{…} outputs the evaluated
  puts "#{k}\t#{h[k]}" }          expression in the double quoted
   Allow passing chunks of code in to methods
   Receiving method uses “yield” command to call
    passed code (can call yield multiple times)

   Single line blocks enclosed in {}
   Multi-line blocks enclosed in do…end

   Can use parameters
    [ 1, 3, 4, 7, 9 ].each {|i| puts i }
    Keys = h.keys.sort {|a,b| a <=> b }
                 Running system commands
require 'find'                                 require reads in another
                                                ruby file - in this case a
Find.find('.') do                               module called Find
  if filename =~ /\.txt$/i
    url_output =                               Find returns an array, we
      filename.gsub(/\.txt$/i, ".html")         create an iterator
    url = `cat #{filename}`.chomp               filename to go thru its
    cmd = "curl #{url} -o #{url_output}";       instances
    puts cmd
                                               We create a new variable
                                                to hold a new filename
end                                             with the same base but
                                                different .html extension
                                               We use backticks `` to
 • curl is a command in mac os to               run a system command
 retrieve a URL to a file, like wget in         and (optionally) save the
 unix                                           output into a variable
                         CGI example
require 'cgi'
                                          CGI requires library
cgi ="html3")                    Create CGI object
size = cgi.params.size

if size > 0 # processing form
  in = cgi.params['t'].first.untaint
                                          If parameters passed
  cgi.out { cgi.html { cgi.head               Process variable t
  cgi.body { "Welcome, #{in}!" }              untaint variables if
  } }                                          using them in
  puts <<FORM
Content-type: text/html

<HTML><BODY><FORM>                        No parameters?
Enter your name: <INPUT TYPE=TEXT             create form using here
NAME=t><INPUT TYPE=SUBMIT>                     document “<<“
                            Reflection examine aspects of the program from within the program itself.

#print out all of the objects in our system
ObjectSpace.each_object(Class) {|c| puts c}

#Get all the methods on an object
“Some String”.methods

#see if an object responds to a certain method

#see if an object is a type
   High-level interpreted OO language
   No types; objects can reflect
   Native support of regex, iterators, system calls
    and CGI
   Relies on convention to limit variability
   OO encourages modular, maintainable code (if
   Strong support for CGI and unit testing

Only the basic here, multiple inheritance,
 exception handling, threading and testing are
 not covered
   Marshal - serialize data for load/save between
    program executions
   Date
   GetOptLong - manipulate command line
    arguments and switches
   Tempfile
   Mutex - semaphores for parallel code

   Net::URI
   Socket - different socket types
   CGI
   CGI::Session
   rdoc - ruby javadoc                        Programming Ruby
   rake - ruby make                            by Dave Thomas
   eruby - embedded ruby                       (the Pickaxe Book)
    (in HTML; think php)
   rubygems - ruby package       
   Irb - interactive ruby        
    (good for debugging)          
   Ruby on Rails (rails)         
        For building web applications
        Based on Model-View-
         Contoller architecture
        further integration of ruby with
         database backend         

Shared By: