ruby rails overview
TRANSCRIPT
Michal PoczwardowskiRuby on Rails [email protected]
#1: puts ‘Yes’ if ‘Work’.starts_with? ‘W’
#2: population = 12_000_000
#3: misterious_number.between?(10, 20)
Like a natural language
1: numbers = []2: for i in [1,2,3,4]3: numbers << i ** 24: end5: numbers # => [1,4,9,16]
Elegant - NON ruby-way solution
:001 > 1.class => Fixnum :002 > (2.2).class => Float :003 > [].class => Array :004 > "Politechnika Gdańska".class => String :005 > nil.class => NilClass :006 > {}.class => Hash
Output from irb
Classes, objects
01: class School02: attr_reader :name03: 04: def initialize(name)05: @name = name06: end07:08: def hello09: puts “Hello #{name}”10: end11: end
school = School.new(‘PG’)school.hello
# => ‘Hello PG’
- high performance / lower level stuff- multi-threading- graphics / data analysis
Avoid ruby in case of
Example with send
01: class Rubyist02: def face(mood)03: send(mood)04: end05: 06: private07: 08: def happy09: ‘:)’10: end11:12: def sad13: ‘:(‘14: end15: end
dev = Rubyist.new
dev.face(:happy)# => ‘:)’
dev.face(:sad)# => ‘:(’
Handle missing methods
1: class Rubyist2: def happy; ‘:)’ end3: def sad; ‘:(‘ end4: 5: def method_missing(name)6: ‘:?’7: end8: end
dev = Rubyist.new
dev.happy# => ‘:)’
dev.sad# => ‘:(’
dev.excited# => ‘:?’
dev.worried# => ‘:?’
Define own methods
01: class Rubyist02: FACES = {03: happy: ‘:)’,04: sad: ‘:(’,05: excited: ‘;D’,06: angry: ‘:[‘07: }08: 09: FACES.each do |key, value|10: define_method(key) { value }11: end12: end
dev = Rubyist.new
dev.happy# => ‘:)’
dev.sad# => ‘:(’
dev.angry# => ‘:[’
dev.excited# => ‘;D’
Everything changes
1: class String2: def with_smile3: self + ‘ :)’4: end5: end
‘Sad string’.with_smile# => ‘Sad string :)’
Example rspec
describe Rubyist do subject { described_class.new }
describe ‘#happy’ do it ‘returns happy face’ expect(subject.happy).to eq ‘:)’ end endend
Gemfile
01: source 'https://rubygems.org'02: 03: gem ‘rails’, ‘4.2.1’04: gem ‘nokogiri’05: gem 'stripe', git: 'https://github.com/stripe/stripe-ruby'06:07: group :test do08: gem ‘rspec-rails’09: end
‘Powerful web applications that formerly might have taken weeks or months to develop can be produced in
a matter of days.’Tim O’Reilly
$ rails generate model Post title:string content:text invoke active_record create db/migrate/20150509232514_create_posts.rb create app/models/post.rb invoke rspec create spec/models/post_spec.rb invoke factory_girl create spec/factories/posts.rb
Magic spells
01: class CreatePosts < ActiveRecord::Migration02: def change03: create_table :posts do |t|04: t.string :title05: t.text :content06: 07: t.timestamps08: end09: end10: end
Migration