Docstoc

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
    collection
   Comments start with # and go to the end of the
    line
       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
                                 level
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”
                                        end

#.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
 end

 def store_F(f)                 4 methods that get/set
   @celsius = (f - 32)*Factor
 end                              an instance variable
 def as_C
   @celsius
 end                            Last evaluated
  def as_F                        statement is
    (@celsius / Factor) + 32
  end
                                  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
  end

  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
  end
end
                                    override these methods if you
                                    need to
t = Temperature.new(25)
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[^>]+/im
/<A[^>]+>.*<\/A>/im         Sandwiched between
                             //
/[^\t]/
/([^\t]+)/                  Quiz: How do you
                             make a regexp for
/^([^\t]+)\t([^\t]+)$/       <A>…</A>?
         Input and Output - tsv files
f = File.open ARGV[0]
                          ARGV is a special array
while ! f.eof?
  line = f.gets            holding the
  if line =~ /^#/          command-line tokens
    next
  elsif line =~ /^\s*$/
    next                  Gets a line
  else
    puts line             If it’s not a comment or
  end                         a blank line
end
f.close
                          Print it
                 Processing TSV files
h = Hash.new
                                Declare a hash table
f = File.open 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
    next
  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
f.close
                                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
                                  string
                      Blocks
   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
  |filename|
  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
    `#{cmd}`
                                               We create a new variable
  end
                                                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 = CGI.new("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
else
                                               commands
  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 “<<“
</FORM></BODY></HTML>
FORM
end
                            Reflection
...to 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
obj.respond_to?(:length)

#see if an object is a type
obj.kind_of?(Numeric)
obj.instance_of?(FixNum)
                     Summary
   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
    needed)
   Strong support for CGI and unit testing

Only the basic here, multiple inheritance,
 exception handling, threading and testing are
 not covered
                      Modules
   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
                                References
   rdoc - ruby javadoc                        Programming Ruby
   rake - ruby make                            by Dave Thomas
   eruby - embedded ruby                       (the Pickaxe Book)
    (in HTML; think php)
   rubygems - ruby package                 http://www.ruby-lang.org
    manager                                 http://www.rubyforge.org
   Irb - interactive ruby                  http://www.rubycentral.org
    (good for debugging)                    http://www.ruby-doc.org
                                            http://www.rubygarden.org
   Ruby on Rails (rails)                   http://www.stlruby.org
        For building web applications
        Based on Model-View-
         Contoller architecture
                                            http://www.rubyquiz.com
        further integration of ruby with
         database backend                   http://www.zenspider.com/Langua
                                               ges/Ruby/QuickRef.html

				
DOCUMENT INFO
Shared By:
Tags:
Stats:
views:20
posted:10/26/2011
language:English
pages:18