Welcome! ❤️
In this workshop:
- Why Rails?
- Some Ruby you probably haven't seen yet
- Writing production code
What makes Rails the best choice?
1. Ruby + Rails = ❤️
2. Convention over configuration
3. Fantastic communities
Rails isn't perfect!
Any questions? 🤔
Enough Rails, let's talk Rubyisms
Good
'Hello, Sean!'
"Hello, #{name}!"
trees = ['chestnut', 'mahogany', 'pine']
trees = %w[chestnut mahogany pine]
old_hash = { :apple => 'fruit', :banana => 'vegetable' }
new_hash = { apple: 'fruit', banana: 'vegetable' }
[[:apple, 'fruit'], [:banana, 'vegetable']].to_h
=> { :apple => 'fruit', :banana => 'vegetable' }
Identical!
{ :a => 'b' }
{ a: 'b' }
[[:a, 'b']].to_h
players = [...]
players.each do |player|
player.delete
end
players.each { |player| player.delete }
Remember that function calls in Ruby
do not have to have parentheses
players.each &:delete
But you should
always use parentheses when chaining
Player.find_by(name: 'Sean').delete
if
and unless
- Guard statements
- Bang and question mark methods
- Hashes as parameters
- Symbols
- DSLs
- Different kinds of loops
Some common Ruby pitfalls...
Can you spot what's wrong?
a = 0
loop do
a++
break if a == 10
end
=> undefined method '+@' for nil:NilClass (NoMethodError)
Can you spot what's wrong?
a = false
b = true
if a
puts a
else if b
puts b
end
=> syntax error, unexpected end-of-input
a = false
b = true
if a
puts a
elsif b
puts b
end
=> true
Why is the output unexpected?
[0..2].each do |i|
puts "i = #{i}"
end
=> "i = 0..2"
(0..2).each do |i|
puts "i = #{i}"
end
=> "i = 0"
=> "i = 1"
=> "i = 2"
Any questions? 🤔
Writing production level code
Production is scary!
How can we mitigate the badness?
Observe! The 6 production commandments
1. Write tests and run them before committing
test "username should be present" do
blank_username = Player.new(username: '')
assert_not blank_username.valid?
end
2. Use branches, and keep their contents atomic
3. Run Rubocop as much as possible
4. Don't fight the CI (continuous integration)
5. Never push changes directly to production
6. Review pull requests
In summary:
- Write tests
- Use branches
- Run Rubocop
- Listen to CI
- Never push to production (directly)
- Peer reviews
Any closing questions? 🤔