ruby on rails on oracle 2009.5.20 hoon lee department of logistics information technology
TRANSCRIPT
목차0. Overview1. Oracle 11g
Oracle.com, Installation, Registration, …
2. Ruby in Twenty MinutesIRB, Module, Method, String, Class, …
3. Ruby on Railsrubyonrails.org, Download,
Installation, …
4. Ruby on Rails on OracleSetup, Install, Create, Edit, Browser, …
5. Another way using OracleCreate, Edit, Script, Browser, …
6. Reference
2
0. Overview
Who made it?, What does it?– Ruby has made by Yukihiro Matsumoto on 1993.– Ruby is object oriented script language. (ex: Perl,
Python, PHP)– Rails has made by David Heinemeier Hansson in
37signals.– Rails has been developed to Web Application
Development Framework by using Ruby language.
3
Yukihiro Matsumoto David Heinemeier Hansson
1. Oracle 11g
SQL Plus – Connection to SCOTT
20
Before the change on Oracle Control
After the change on Oracle Control
SQL> update dba_users set lock_date = NULL where username = ‘SCOTT’;
1. Oracle 11g
Environment for RoR – tnsname.ora, listener.ora
22
LISTENER = (DESCRIPTION_LIST = (DESCRIPTION = (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521)) (ADDRESS = (PROTOCOL = TCP)(HOST = 211.212.234.18)(PORT = 1521)) ) )
LISTENER = (DESCRIPTION_LIST = (DESCRIPTION = (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521)) (ADDRESS = (PROTOCOL = TCP)(HOST = 211.212.234.18)(PORT = 1521)) ) )
listener.ora
tnsname.oraSample programs use a tnsname(RAILS) in Ruby on Rails.
1. Oracle 11g
Tip - “Microsoft LoopBack Adapter”– IP: 192.168.0.1-> tnsname.ora-> listener.ora
23
Oracle 11g doesn’t support localhost(127.0.0.1)
1. Oracle 11g
Tip – OracleDBConsoleorcl– Start Type: Manual
24
Oracle 11g has a bug with OracleDBConsoleorcl
2. Ruby in Twenty Minutes
Interactive Ruby– IRB: stands for Interactive Ruby
28
irb(main):001:0> "Hello World"=> "Hello World"irb(main):002:0>
2. Ruby in Twenty Minutes
Ruby Obeyed You!– to print out “Hello World”– puts is the basic command to print something– puts always returns nil(absolutely-positively-nothing
value)
Your Free Calculator is Here– Basic calculate, Math objects
29
irb(main):002:0> puts "Hello World"Hello World=> nilirb(main):003:0>
irb(main):003:0> 3+2=> 5irb(main):004:0> 3*2=> 6irb(main):005:0> 3**2=> 9irb(main):006:0> Math.sqrt(9)=> 3.0irb(main):007:0>
2. Ruby in Twenty Minutes
– Modules, Group Code by Topic– Modules serve two roles in Ruby. – One role = grouping similar methods together under a
familiar name– Method with a parameter
Definition of the method
• nil tells us that it knows we’re done defining the method
30
irb(main):007:0> a = 3 ** 2=> 9irb(main):008:0> b = 4 ** 2=> 16irb(main):009:0> Math.sqrt(a+b)=> 5.0irb(main):010:0>
irb(main):010:0> def hirb(main):011:1> puts "Hello World!"irb(main):012:1> end=> nilirb(main):013:0>
2. Ruby in Twenty Minutes
The Brief, Repetitive Lives of a Method– Calling a method
• If method doesn’t take parameters, empty parentheses aren't needed
– Method with parameter
• The braces(“#{name}”) is turned into a string
31
irb(main):013:0> hHello World!=> nilirb(main):014:0> h()Hello World!=> nilirb(main):015:0>
irb(main):015:0> def h(name)irb(main):016:1> puts "Hello #{name}!"irb(main):017:1> end=> nilirb(main):018:0> h("Matz")Hello Matz!=> nilirb(main):019:0>
2. Ruby in Twenty Minutes
Holding Spots in a String– Method with default parameter
• The parentheses are optional on #023• The braces(“#{name}”) is capitalized properly
32
irb(main):019:0> def h(name = "World")irb(main):020:1> puts "Hello #{name.capitalize}!"irb(main):021:1> end=> nilirb(main):022:0> h "chris"Hello Chris!=> nilirb(main):023:0> hHello World!=> nil
2. Ruby in Twenty Minutes
Evolving Into a Greeter– “Greeter” class with methods
• @name is an instance variable, is a available to all the methods in the class
33
irb(main):024:0> class Greeterirb(main):025:1> def initialize(name = "World")irb(main):026:2> @name = nameirb(main):027:2> endirb(main):028:1> def say_hiirb(main):029:2> puts "Hi #{@name}!"irb(main):030:2> endirb(main):031:1> def say_byeirb(main):032:2> puts "Bye #{@name}, come back soon."irb(main):033:2> endirb(main):034:1> end=> nil
2. Ruby in Twenty Minutes
• Create a greeter object g. it’s name is with “Pat”.
• If we want to get at the name directly? Can’t do it.• Instance variables are hidden away inside the object.
34
irb(main):035:0> g = Greeter.new("Pat")=> #<Greeter:0x16cac @name="Pat">irb(main):036:0> g.say_hiHi Pat!=> nilirb(main):037:0> g.say_byeBye Pat, come back soon.=> nil
rb(main):038:0> g.@nameSyntaxError: compile error(irb):52: syntax error, unexpected tIVARg.@name ^ from (irb):52
2. Ruby in Twenty Minutes
Under the Object’s Skin– The hidden methods exist in Greeter objects?
• this is all of the methods for Greeter objects, including ones defined by ancestor classes.
• to not include ancestors by passing it the parameter false
35
irb(main):039:0> Greeter.instance_methods=> ["inspect", "clone", "to_yaml", "public_methods", "display", "instance_variable_defined?", "equal?", "freeze", "methods", "respond_to?", "dup", "instance_variables", "__id__", "method", "eql?", "h", "id", "to_yaml_properties", "singleton_methods", "taguri", "send", "taint", "frozen?", "taguri=", "instance_variable_get", "say_hi", "__send__", "instance_of?", "to_a", "type", "to_yaml_style", "protected_methods", "object_id", "instance_eval", "==", "===", "instance_variable_set", "say_bye", "kind_of?", "extend", "to_s", "hash", "class", "tainted?", "=~", "private_methods", "nil?", "untaint", "is_a?"]
irb(main):040:0> Greeter.instance_methods(false)=> ["say_bye", "say_hi"]
2. Ruby in Twenty Minutes
• Which methods our greeter object responds to?• “to_s” is used to convert something to a string.
Altering Classes - It’s Never Too Late– Access to an object’s variables
• The changes will be present in any new objects.
36
irb(main):041:0> g.respond_to?("name")=> falseirb(main):042:0> g.respond_to?("say_hi")=> trueirb(main):043:0> g.respond_to?("to_s")=> true
irb(main):044:0> class Greeterirb(main):045:1> attr_accessor :nameirb(main):046:1> end=> nil
2. Ruby in Twenty Minutes
• Using attr_accessor defined two new methods, name to get the value, and name= to set it.
37
irb(main):047:0> g = Greeter.new("Andy")=> #<Greeter:0x3c9b0 @name="Andy">irb(main):048:0> g.respond_to?("name")=> trueirb(main):049:0> g.respond_to?("name=")=> trueirb(main):050:0> g.say_hiHi Andy!=> nilirb(main):051:0> g.name="Betty"=> "Betty"irb(main):052:0> g=> #<Greeter:0x3c9b0 @name="Betty">irb(main):053:0> g.name=> "Betty"irb(main):054:0> g.say_hiHi Betty!=> nil
2. Ruby in Twenty Minutes
Greeting Anything and Everything, MegaGreeter Neglects None!– Create a file, and run it.
• To quit IRB, type “quit”, “exit” or just hit Control-D
38
#!/usr/bin/env rubyclass MegaGreeter attr_accessor :names # Create the object def initialize(names = "World") @names = names end # Say hi to everybody def say_hi if @names.nil? puts "..." elsif @names.respond_to?("each") # @names is a list of some kind, iterate! @names.each do |name| puts "Hello #{name}!" end else puts "Hello #{@names}!" end end ri20min.rb
2. Ruby in Twenty Minutes
39
# Say bye to everybody def say_bye if @names.nil? puts "..." elsif @names.respond_to?("join") # Join the list elements with commas puts "Goodbye #{@names.join(", ")}. Come back soon!" else puts "Goodbye #{@names}. Come back soon!" end endend
if __FILE__ == $0 mg = MegaGreeter.new mg.say_hi mg.say_bye # Change name to be "Zeke" mg.names = "Zeke" mg.say_hi mg.say_bye # Change the name to an array of names mg.names = ["Albert", "Brenda", "Charles", "Dave", "Englebert"] mg.say_hi mg.say_bye # Change to nil mg.names = nil mg.say_hi mg.say_byeend ri20min.rb
2. Ruby in Twenty Minutes
• Save this file as “ri20min.rb”, and run it as “ruby ri20min.rb”
• Sharp mark(#) is a comment line, but first line of the file tells how to run the file.
Cycling and Looping - a.k.a. Iteration
• The variable between pipe characters is the parameter for this block(@names)
40
Hello World!Goodbye World. Come back soon!Hello Zeke!Goodbye Zeke. Come back soon!Hello Albert!Hello Brenda!Hello Charles!Hello Dave!Hello Englebert!Goodbye Albert, Brenda, Charles, Dave, Englebert. Comeback soon!...... ruby ri20min.rb
@names.each do |name| puts "Hello #{name}!“end
2. Ruby in Twenty Minutes
Blocks, the Highly Sparkling Glint on the Edge of Ruby– The real power of block
• Elements are joined/sequenced by parameter. Prints out like string.
Kicking Off the Script
• __FILE__ contains the name of current file. • $0 is the name of the file used to start the program• This check says “If this is the main file being used…” This allows
a file to be used as a library, and not to execute code in that context, but if the file is being used as an executable, then execute that code
41
elsif @names.respond_to?("join") # Join the list elements with commas puts "Goodbye #{@names.join(", ")}. Come back soon!"
if __FILE__ == $0
3. Ruby on Rails
Smart people saying nice things– “Rails is the most well thought-out web development
framework I’ve ever used. And that’s in a decade of doing web applications for a living. I’ve built my own frameworks, helped develop the Servlet API, and have created more than a few web servers from scratch. Nobody has done it like this before.”- James Duncan Davidson, Creator of Tomcat and Ant –
– “Ruby on Rails is a breakthrough in lowering the barriers of entry to programming. Powerful web applications that formerly might have taken weeks or months to develop can be produced in a matter of days.”- Tim O'Reilly, Founder of O'Reilly Media -
44
3. Ruby on Rails
– “It is impossible not to notice Ruby on Rails. It has had a huge effect both in and outside the Ruby community... Rails has become a standard to which even well-established tools are comparing themselves to.”- Martin Fowler, Author of Refactoring, PoEAA, XP Explained –
– “What sets this framework apart from all of the others is the preference for convention over configuration making applications easier to develop and understand.”- Sam Ruby, ASF board of directors -
– “Rails is the killer app for Ruby.”- Yukihiro Matsumoto, Creator of Ruby -
45
3. Ruby on Rails
Install a Rails– Run “gem install rails”
51
Ref) C:\Ruby\lib\ruby\gems\1.8\cache/doc/gems/specifications
if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<rake>, [">= 0.8.3"]) s.add_runtime_dependency(%q<activesupport>, ["= 2.3.2"]) s.add_runtime_dependency(%q<activerecord>, ["= 2.3.2"]) s.add_runtime_dependency(%q<actionpack>, ["= 2.3.2"]) s.add_runtime_dependency(%q<actionmailer>, ["= 2.3.2"]) s.add_runtime_dependency(%q<activeresource>, ["= 2.3.2"])
if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<rake>, [">= 0.8.3"]) s.add_runtime_dependency(%q<activesupport>, ["= 2.3.2"]) s.add_runtime_dependency(%q<activerecord>, ["= 2.3.2"]) s.add_runtime_dependency(%q<actionpack>, ["= 2.3.2"]) s.add_runtime_dependency(%q<actionmailer>, ["= 2.3.2"]) s.add_runtime_dependency(%q<activeresource>, ["= 2.3.2"])
rails-2.3.2.gemspec
3. Ruby on Rails
54
Run a Web Server– Move “cd path/to/your/new/application”– Run “ruby script/server”
#!/usr/bin/env rubyrequire File.dirname(__FILE__) + '/../config/boot'require 'commands/server'
#!/usr/bin/env rubyrequire File.dirname(__FILE__) + '/../config/boot'require 'commands/server' server
4. Ruby on Rails on Oracle
Step 1: Set up the Oracle database– Refer to the “1. Oracle 11g”– Create a user on SQL Plus – ruby/ruby
Step 2: Install Ruby, RubyGems, Rails, and the Ruby/Rails Oracle library– Refer to the “3. Ruby on Rails”
• Use the "One-Click Ruby Installer for Windows 1.8.6-26 Final Release“
• Follow the installation instructions
57
SQL> GRANT CONNECT, RESOURCE TO ruby IDENTIFIED BY ruby;SQL> ALTER USER ruby DEFAULT TABLESPACE users TEMPORARY TABLESPACE temp;SQL> EXIT
4. Ruby on Rails on Oracle
– Update RubyGems to latest version
58
C:\Ruby>gem update --systemUpdating RubyGemsUpdating rubygems-updateSuccessfully installed rubygems-update-1.3.3:0:Warning: Gem::SourceIndex#search support for String patterns is deprecatedUpdating RubyGems to 1.3.3Installing RubyGems 1.3.3Installing RubyGemsInstalling gem executableRemoving old source_cache filesRemoving old RubyGems RDoc and riInstalling rubygems-1.3.3 ri into C:/Ruby/lib/ruby/gems/1.8/doc/rubygems-1.3.3/riInstalling rubygems-1.3.3 rdoc into C:/Ruby/lib/ruby/gems/1.8/doc/rubygems-1.3.3/rdoc
------------------------------------------------------------------------------
= Announce: RubyGems Release 1.3.3…
4. Ruby on Rails on Oracle
– Install Rails
– Install Ruby Oracle library(Ruby-oci8)
– Install ActiveRecord Oracle enhanced adapter
59
C:\Ruby>gem install rails -v 2.3.2Successfully installed rails-2.3.21 gem installedInstalling ri documentation for rails-2.3.2...Installing RDoc documentation for rails-2.3.2...
C:\Ruby>gem install ruby-oci8 -v 1.0.4Successfully installed ruby-oci8-1.0.4-x86-mswin321 gem installedInstalling ri documentation for ruby-oci8-1.0.4-x86-mswin32...Installing RDoc documentation for ruby-oci8-1.0.4-x86-mswin32...
C:\Ruby>gem install activerecord-oracle-adapter --source http://gems.rubyonrails.orgSuccessfully installed activerecord-oracle-adapter-1.0.0.92501 gem installedInstalling ri documentation for activerecord-oracle-adapter-1.0.0.9250...Installing RDoc documentation for activerecord-oracle-adapter-1.0.0.9250...
4. Ruby on Rails on Oracle
Step 3: Create the Web Application– Create a new project using the rails command line
application
60
C:\Ruby\temp>rails comics_catalog -d oracle create create app/controllers create app/helpers create app/models create app/views/layouts create config/environments create config/initializers create config/locales create db create doc create lib create lib/tasks create log create public/images create public/javascripts create public/stylesheets create script/performance create test/fixtures create test/functional create test/integration create test/performance create test/unit create vendor create vendor/plugins create tmp/sessions create tmp/sockets create tmp/cache create tmp/pids create Rakefile create README create app/controllers/application_controller.rb create app/helpers/application_helper.rb create config/database.yml create config/routes.rb create config/locales/en.yml create config/initializers/backtrace_silencers.rb create config/initializers/inflections.rb create config/initializers/mime_types.rb create config/initializers/new_rails_defaults.rb create config/initializers/session_store.rb create config/environment.rb create config/boot.rb create config/environments/production.rb create config/environments/development.rb create config/environments/test.rb create script/about create script/console create script/dbconsole create script/destroy create script/generate create script/runner create script/server create script/plugin create script/performance/benchmarker create script/performance/profiler create test/test_helper.rb create test/performance/browsing_test.rb create public/404.html create public/422.html create public/500.html create public/index.html create public/favicon.ico create public/robots.txt create public/images/rails.png create public/javascripts/prototype.js create public/javascripts/effects.js create public/javascripts/dragdrop.js create public/javascripts/controls.js create public/javascripts/application.js create doc/README_FOR_APP create log/server.log create log/production.log create log/development.log create log/test.log
4. Ruby on Rails on Oracle
– Edit database.yml using Oracle database
61
If you use ActiveRecord Oracle enhanced adapter, specify 'oracle_enhanced' instead of 'oracle' as the adapter
4. Ruby on Rails on Oracle
Create a Web application using the Rails scaffold
62
C:\Ruby\temp\comics_catalog>ruby script/generate scaffold comic title:string issue:integer publisher:string exists app/models/ exists app/controllers/ exists app/helpers/ create app/views/comics exists app/views/layouts/ exists test/functional/ exists test/unit/ create test/unit/helpers/ exists public/stylesheets/ create app/views/comics/index.html.erb create app/views/comics/show.html.erb create app/views/comics/new.html.erb create app/views/comics/edit.html.erb create app/views/layouts/comics.html.erb create public/stylesheets/scaffold.css create app/controllers/comics_controller.rb create test/functional/comics_controller_test.rb create app/helpers/comics_helper.rb create test/unit/helpers/comics_helper_test.rb route map.resources :comics dependency model exists app/models/ exists test/unit/ exists test/fixtures/ create app/models/comic.rb create test/unit/comic_test.rb create test/fixtures/comics.yml create db/migrate create db/migrate/20090511153415_create_comics.rb
"title:string issue:integer publisher:string" represents a table column
Rails code generator created model, view, and controller Ruby code to access the COMICS table
If you make any changes to the database tables, you'll need to run the scaffold command again.
4. Ruby on Rails on Oracle
– Create a database
– Start a Web Server
63
C:\Ruby\temp\comics_catalog>rake db:migrate(in C:/Ruby/temp/comics_catalog)== CreateComics: migrating ===================================================-- create_table(:comics) -> 0.1100s -> 0 rows== CreateComics: migrated (0.1100s) ==========================================
C:\Ruby\temp\comics_catalog>ruby script/server=> Booting WEBrick=> Rails 2.3.2 application starting on http://0.0.0.0:3000=> Call with -d to detach=> Ctrl-C to shutdown server[2009-05-12 00:53:22] INFO WEBrick 1.3.1[2009-05-12 00:53:22] INFO ruby 1.8.6 (2008-08-11) [i386-mswin32][2009-05-12 00:53:22] INFO WEBrick::HTTPServer#start: pid=7376 port=3000
can change the Ruby code at anytime without restarting if we change the database configuration file, need to restart
the server
4. Ruby on Rails on Oracle
69
http://github.com/rsim/oracle-enhanced/tree/master
To get a ActiveRecord Oracle Adapter
4. Ruby on Rails on Oracle
Files and Directories– \comics_catalog\app
• models\comic.rb• views\comics or layouts\*.erb• controllers\*.rb• helper\*.rb
– \comics_catalog\config\database.yml– \comics_catalog\db\schema.rb– …
70
Make API DOC – “C:\comics_catalog>rake doc:app”
5. Another way using Oracle
Create a New Project(comics_catalog)
Move to directory(comics_catalog)
Edit a database.yml in config directory– development: adapter: oci username: ruby password: ruby
host: RAILS
Create a Web application using the Rails scaffold
–
Start a Web Server–
Check by Web Browser– http://localhost:3000/comics/list
74
C:\> rails comics_catalog
C:\> cd comics_catalog
C:\comics_catalog> ruby script/generate scaffold Comic
C:\comics_catalog> ruby script/server
6. Reference
Ruby Programming Language– http://www.ruby-lang.org/en/
Ruby on Rails– http://rubyonrails.org/
RubyForge – Project Library– http://rubyforge.org/
Ruby Central– http://www.rubycentral.com/
Ruby on Rails on Oracle: A Simple Tutorial– http://www.oracle.com/technology/pub/articles/haefel-oracle-
ruby.html
Oracle Database Software Downloads– http://www.oracle.com/technology/software/products/
database/index.html
75