Object Oriented
class Person
def initialize(name)
@name = name
end
def speak()
puts("Hi, I am #{@name}")
end
end
peter = Person.new("Peter")
peter.speak() # Hi, I am Peter
| space, → | next slide |
| ← | previous slide |
| d | debug mode |
| ## <ret> | go to slide # |
| c | table of contents (vi) |
| f | toggle footer |
| r | reload slides |
| z | toggle help (this) |
irbfxri$irb(main):001:0> "Hello World"
=> "Hello World"
$irb(main):001:0> 1+1
=> 2
$irb(main):001:0> puts("Hello World")
"Hello World"
=> nil
CamelCasedALL_CAPS_WITH_UNDERSCORES*under_scored* Not entirely true
class Person
def initialize(name)
@name = name
end
def speak()
puts("Hi, I am #{@name}")
end
end
peter = Person.new("Peter")
peter.speak() # Hi, I am Peter
class Employee < Person
def initialize(name, salary)
super(name)
@salary = salary
end
end
michael = Employee.new("Michael", 10000)
michael.speak() # Hi, I am Michael
sam = Employee.new("Sam", 30000)
sam.speak()
# same result:
sam = Employee.new "Sam", 30000
sam.speak
1.next # 2
-15.abs # 15
"hello".length # 5
# Lots of stuff built-in:
1.methods.count # 130
"".methods.count # 160
nil and falseif(0), if("") => truthyif x < 0
puts "negative"
elsif x == 0 # <- not "elseif"!
puts "zero"
else
puts "positive"
end
true or false17.even? # false
"".empty? # true
obj.nil? # true if obj == nil
str = "Hello"
other = str.upcase # doesn't modify str
puts(str) # Hello
puts(other) # HELLO
str.upcase! # modifies str
puts(str) # HELLO
array = [ 1, 2, 3, "catorce" ]
array[4] # returns "catorce"
array[4] = 4
array[4] # returns 4
each
[ 1, 2, 3, 4 ].each do |n|
puts(n)
end
# or
[ 1, 2, 3, 4 ].each{ |n| puts(n) }
String vs Symbolstring = "hello"
symbol = :hello
string != symbol # not equal
string == symbol.to_s # unless converted
String vs Symbol (II)String: text that changes, ex. db text fields.Symbol: text that identifes, ex. "enums"
properties = {
:name => "number_of_dwarves",
:value => 7
}
properties[:name] # "number_of_dwarves"
properties[:value] # 7
properties[:value] = 6 # a dwarf died
properties[:value] # returns 6
hash = { :a => 1, :b => 2 }
hash.each do |k, val|
puts("#{k} => #{val}")
end
# or
hash.each{ |k, val| puts("#{k} => #{val}") }
class Foo
def my_method(x,y, options = {})
...
end
end
foo = Foo.new
# equivalent:
foo.my_method(1, 2, {:color => :white})
foo.my_method 1, 2, {:color => :white}
foo.my_method(1, 2, :color => :white)
foo.my_method 1, 2, :color => :white
gem command$ gem install gem_name
app/modelsapp/viewsparams variable => hashed parametersapp/controllersrake db:xxx commandsdb/migratedb/config/routes.rb$ gem install rails
$ gem install sqlite3
$ <ubuntu> sudo apt-get install sqlite3
$ rails new to_do
create README
create Rakefile
...
create vendor/plugins/
create vendor/plugins/.gitkeep
$ cd to_do
$ rails s
.
├── app
│ ├── models
│ ├── views
│ ├── controllers
│ └── ...
├── config
├── db
│ └── migrate
├── public
│ ├── images
│ ├── javascripts
│ └── stylesheets
└── ...
$ rails g scaffold Project name:string
create db/migrate/20110627160358_create_projects.rb
create app/models/project.rb
...
route resources :projects
...
create app/controllers/projects_controller.rb
...
create app/views/projects
create app/views/projects/index.html.erb
create app/views/projects/edit.html.erb
create app/views/projects/show.html.erb
create app/views/projects/new.html.erb
create app/views/projects/_form.html.erb
...
create public/stylesheets/scaffold.css
...
$ rake db:migrate
== CreateProjects: migrating =================================================
-- create_table(:projects)
-> 0.0026s
== CreateProjects: migrated (0.0027s) ========================================
Creates a table with 4 fields: id, name, created_at & updated_at
rails s$ rails c
Loading development environment (Rails 3.0.7)
$ ruby-1.9.2-p0 > p1 = Project.new
=> #<Project id: nil, name: nil, created_at: nil, updated_at: nil>
$ ruby-1.9.2-p0 > p1.name = "New project"
=> "hello"
$ ruby-1.9.2-p0 > p1.save
=> true
$ ruby-1.9.2-p0 > p2 = Project.new(:name => "Initialized project")
=> #<Project id: nil, name: "Thank you", created_at: nil, updated_at: nil>
$ ruby-1.9.2-p0 > p2.save
=> true
$ ruby-1.9.2-p0 > p3 = Project.create(:name => "Saved project")
=> #<Project id: 2, name: "Saved project", created_at: "2011-06-28 12:55:40", updated_at: "2011-06-28 12:55:40">
# db/migrate/...create_projects.rb
class CreateProjects < ActiveRecord::Migration
def self.up
create_table :projects do |t|
t.string :name
t.timestamps
end
end
def self.down
drop_table :projects
end
end
# app/controllers/projects_controller.rb
class ProjectsController < ApplicationController
# index, show, new, create
# edit, update, & destroy
end
.
├── edit.html.erb
├── _form.html.erb
├── index.html.erb
├── new.html.erb
└── show.html.erb
# config/routes.rb
Todo::Application.routes.draw do
resources :projects
...
end
# app/models/project.rb
class Project < ActiveRecord::Base
end
$rm public/index.html
# config/routes.rb
...
# root :to => "welcome#index"
...
root :to => "projects#index"
class Project < ActiveRecord::Base
# add these two lines
validates_presence_of :name
validates_uniqueness_of :name
end
$ rails g scaffold Task name:string project_id:integer done:boolean
...
$ rake db:migrate
has_many & belongs_to# app/models/project.rb
class Project < ActiveRecord::Base
...
# add this line:
has_many :tasks
end
# app/models/task.rb
class Task < ActiveRecord::Base
# add this line:
belongs_to :project
end
has_many$ rails c
Loading development environment (Rails 3.0.7)
$ ruby-1.9.2-p0 > p = Project.first
=> #<Project id: 1, name: 'foo', created_at: nil, updated_at: nil>
$ ruby-1.9.2-p0 > p.tasks
=> []
$ ruby-1.9.2-p0 > p.tasks.create(:name => "Clean dishes")
=> #<Task id: 1, name: "Clean dishes", project_id: 1, done: false, ...
$ ruby-1.9.2-p0 > p.tasks.create(:name => "Take dog out")
=> #<Task id: 2, name: "Take dog out", project_id: 1, done: false, ...
$ ruby-1.9.2-p0 > p.tasks.count
=> 2
belongs_to$ ruby-1.9.2-p0 > t = Tasks.find(2)
=> #<Task id: 2, name: "Take dog out", project_id: 1, done: false, ...
$ ruby-1.9.2-p0 > t.project_id
=> 1
$ ruby-1.9.2-p0 > t.project
=> #<Project id: 1, name: 'foo', created_at: nil, updated_at: nil>
$ ruby-1.9.2-p0 > t.project_id = 2
=> 2
$ ruby-1.9.2-p0 > t.save
=> true
$ ruby-1.9.2-p0 > t.project
=> #<Project id: 2, name: 'bar', created_at: nil, updated_at: nil>
# app/controllers/tasks_controller.rb
class TasksController < ApplicationController
before_filter :calculate_projects
...
private
def calculate_projects
@projects = Project.all
end
end
# app/controllers/tasks_controller.rb
class TasksController < ApplicationController
before_filter :calculate_projects,
:only => [:new, :create, :edit, :update]
...
private
def calculate_projects
@projects = Project.all
end
end
<%= f.text_field :project_id %>
# change that to this VVVVVV
<%= f.collection_select :project_id, @projects,
:id, :name, :include_blank => true
%>
# app/models/task.rb
class Task < ActiveRecord::Base
...
def status
if self.done
return "done"
else
return "not done"
end
end
end
# app/models/task.rb
class Task < ActiveRecord::Base
...
def status
return self.done ? "done" : "not done"
end
end
# app/models/task.rb
class Task < ActiveRecord::Base
...
def status
return done ? "done" : "not done"
end
end
# app/models/task.rb
class Task < ActiveRecord::Base
...
def status
done ? "done" : "not done"
end
end
# app/views/projects/show.html.erb
<p>
<b>Name:</b>
<%= @project.name %>
</p>
<!-- add this: -->
<ul>
<% @project.tasks.each do |task| %>
<li><%= task.name %>: <%= task.status %></li>
<% end %>
</ul>
...