Ruby Argentina Asociación Civil
25 de Septiembre de 2012
Ruby is designed for programmer happiness

value = 42
puts value # => 42
value = "Hola UNLaM!"
puts value # => Hola UNLaM!
puts "hola".capitalize # => "Hola"
>> "fnoCybuR".reverse
=> "RubyConf"
a = ""
4.times { |i| a+= i.to_s }
# => 0123
4.8.round
# => 5
nil.nil?
# => true
nil.class
# => NilClass
class Person attr_accessor :name end inkel = Person.new inkel.name = "Leandro" puts inkel.name # => "Leandro"
module Say
def self.say
"I'm a module!"
end
end
Say.new # => NoMethodError
puts Say.say # => "I'm a module!"
class Animal
attr_accessor :kind
end
class Human < Animal
def initialize
@kind = "Human"
end
end
module Extend
def de_clase
"class method"
end
end
module Include
def de_instancia
"instance method"
end
end
class EI
extend Extend
include Include
end
EI.de_clase # => class method EI.new.de_instancia # => instance method
Es una buena manera de extender funcionalidades en las clases.
En cierto sentido, similar a las interfaces de Java o a los templates de C++.
nums = [1, 2, 3, 4, 5]
names = [ "ceneon", "inkel" ]
meses = %w{ enero febrero marzo abril mayo ... }
meses = { :enero => 31, :febrero => 28 }
meses[:enero] # => 31
counter = Hash.new { |h, k| h[k] = 0 }
counter[:a] # => 0
counter[:b] += 1 # => 1
Curso.find(:conditions => {:dia => Date.today }, :order => "id asc" )
def splats(*args) p [ args.length, args ] end splats "ceneon" # => [1, ["ceneon"]] splats "ceneon", "inkel" # => [2, ["ceneon", "inkel"]]
Código fuente de Ruby: https://github.com/ruby/ruby
class String
def greet
"Hola #{self}!"
end
end
>> "UNLaM".greet
=> "Hola UNLaM!"
class Person
attr_accessor :name, :age
end
Person.instance_methods
# => "[:instance_eval, :pretty_inspect, :enum_for, :public_methods..."
Person.instance_methods.grep(/^to_/).sort.reverse
# => "[:to_yaml_properties, :to_yaml, :to_s, :to_enum]"
Person.instance_methods false
# => [:name, :name=, :age, :age=]
10.times do
puts "u "
end
puts "Hoy es la charla!" if Time.now.tuesday?
Person.delete_all!
(1..5).each do |i|
puts "El cuadrado de #{i} es #{i * i}"
end
1_000_000.times do
# Algo que se hará muchas veces
end
user = "Foo Bar"
10.times do
puts user
end
# Donde *user* es una variable que fue creada
# fuera del bloque y el bloque puede acceder a ella
vec = []
(0..7).each do |n|
vec << n
end
# vec => [0, 1, 2, 3, 4, 5, 6, 7]
reverse_string_order = lambda { |x, y| y.to_s <=> x.to_s }
[1, 20, 3].sort &reverse_string_order
# => [20, 3, 1]
square = lambda { |n| n * n }
[1, 2, 3, 4, 5].map &square
# => [1, 4, 9, 16, 25]
conf$ ruby -v
=> ruby 1.9.....
conf$ irb
"hola mundo".split
=> ["hola", "mundo"]
# Rakefile
task :default => [:test]
desc "Run unit tests"
task :test do
ruby "test/unittest.rb"
end
# Bash
rake test
Librerías, o "gemas" de todo tipo
Sistema de repositorios símil Debian/Ubuntu
# Bash
gem install 'twitter'
# irb
> require 'twitter'
=> true
> Twitter.user_timeline("inkel").first.text
=> "cerrando detalles de la charla de #Ruby para la UNLaM"
SCM (Como SVN, CVS pero mejor!)
Proyectos en Git: Linux, Debian, Eclipse
Social Coding (Open Source Fun!)
Proyectos en GitHub: jQuery, Symfony, DJAngo, Linux Kernel
"git y GitHub, primeros pasos" por Ruby Argentina, el 21/8
Objetivo principal: Más productividad
Minimalista. Simple.
require 'sinatra'
get '/hi' do
"Hello World!"
end
Paso 1: Crear la aplicación
$ rails new app1
Paso 2: Configurar base de datos
/config/database.yml
/Gemfile # => 'mysql2'
Paso 3: Crear un "Scaffold" (andamios)
$ rails generate scaffold alumno nombre:string dni:integer email:string
Paso 4: Actualizar base de datos
$ rake db:migrate
(Ver resultado en la BD)
Paso 5: Iniciar el servidor
$ rails server
(Ver model, controller y views)
Validaciones del modelo
/app/models/alumno.rb
# validates_presence_of :nombre
# validates_numericality_of :dni
Localizar mensajes
/config/environment.rb
/config/locales/es.yml
rails server
Layouts
/app/views/layouts/application.html.erb
Form Helpers
/app/views/alumnos/_form.html.erb
Bonus: Poner una foto a los alumnos
/Gemfile # => gem 'paperclip'
$ bundle install
$ rails g migration agregarFotoDeAlumnos
add_column :alumnos, :foto_file_name, :string
add_column :alumnos, :foto_content_type, :string
add_column :alumnos, :foto_file_size, :integer
add_column :alumnos, :foto_updated_at, :datetime
$ rake db:migrate
/app/models/alumno.rb
has_attached_file :foto, :styles => { :medium => "300x300>", :thumb => "128x128>" }
validates_attachment_content_type :foto, :content_type=>['image/jpeg', 'image/png', 'image/gif']
Bonus: Poner una foto a los alumnos
/app/views/alumnos/_form.html.erb
form_for .... , :html => { :multipart => true }
f.file_field :foto
/app/views/alumnos/index.html.erb
image_tag alumno.foto.url(:thumb)
15 y 16 de Junio