Ruby Midwest 2011 Confident Code by Avdi Grimm

Confreaks · 29K views · 2012 · 31:24

Open on YouTube

Python, Ruby & scripting languagesSoftware architecture & designSoftware practice, open source & careerstalk

Why Stack Overflow recommends it

Stack Overflow users link it when answering questions about avoiding repetitive nil checks in Ruby and Rails code.

Recommended by 2 people across 2 different months, 2012 to 2018.

What it is

A 2011 Ruby Midwest conference talk by Avdi Grimm, recorded by Confreaks, about writing Ruby methods in a confident, straightforward style. It covers coercion, the Decorator pattern, Null Object and Special Case patterns, and other ways to remove nil checks and defensive clutter.

What people said

Recommends 0xSina · 2012-12 · Stack Overflow · on “How do I avoid many 'nil' checks?”

I found a way to do this in one statement using to_f to coerce nil: ar_show.lat = event['location']['lat'].to_f.round(4) to_f on a nil will make it 0.0 handling the nil case, avoiding an extra variable or statement. Got the answer from this [this video] video.

Recommends sergelerator · 2013-03 · Stack Overflow · on “How do I get around a nil object being created in my controller?”

Try the "confident code" approach. In this particular case, abuse the methods such as to_s and to_i . Examples work better: @daily_entries.each do |daily_entry| # If it's a String, nothing happens, if it's nil, empty string will be returned. string_val = daily_entry.breakfast.to_s # If it's a Fixnum, nothing happens, if it's nil, 0 will be returned. int_val = daily_entry.id.to_i end Watch this video with Avdi Grimm [this video] , it explains this stuff about confident code really well. Hope it helps :)

Cites Kache · 2018-12 · Stack Overflow · on “hashWithIndifferentAccess is preventing update of a single hash value from a form”

what you're looking for is probably: elem = DynamicElement.joins(:dynamic_page_elements).find_by!( dynamic_page_elements: params.slice(:dynamic_page_id), description: "SectionOne", ) new_section_text = elem.section_text.merge(dynamic_element_params) elem.update(section_text: new_section_text) Some tips: make use of db joins to avoid nil s -- they're a common source of bugs and causes your code to be "timid" [this video] avoid mutating ( merge! ) by default, keeps changes discrete and easier to track use good naming to keep track of the concepts you're handling e.g. not clear what element.update(derp) was doing