Thursday, October 20, 2016

Blank? in Ruby On Rails

The blank? method (a clever Rails extension for those of us too lazy to figure out what type of object we are testing is) is some very smart code:

[7] pry(#<#>)> nil.blank?
=> true
[8] pry(#<#>)> "".blank?
=> true
[9] pry(#<#>)> [].blank?
=> true
[10] pry(#<#>)> {}.blank?
=> true
[11] pry(#<#>)> find-method blank?
Object
Object#blank?
[12] pry(#<#>)> show-source blank?

From: /home/saracarl/.rvm/gems/ruby-2.2.0-preview2/gems/activesupport-4.1.2/lib/active_support/core_ext/object/blank.rb @ line 16:
Owner: Object
Visibility: public
Number of lines: 3

def blank?
  respond_to?(:empty?) ? !!empty? : !self
end


Let's break it down
respond_to?(:empty?) ?
  if the object has a method called empty?
 !!empty?
  return the results of empty?, "not"-ed twice.  This means if the response to emtpy? is "true" it will return true (!(!true)).  If the response is false it will return false (!(!false))  If the response is "nil" it will return false (!(!nil)).  It covers the case where empty? returns nil instead of true or false -- if the object.empty? is nil, then the object.blank? is false
: !self
Else return !self -- if self is nil, return true, otherwise return false.

Sunday, January 10, 2016

The Theory of Four Things

When you get to a certain tenure in the high tech industry, you've probably worked in a number of programming languages.  My education started with hobbyist BASIC, continued with high school Pascal, and finished with Scheme and C in college.  My professional life until this year included Java, perl, and bash, and I picked up Ruby for fun side projects.  Those transitions and additions happened over years.  In the last 4 months, however, I've done projects in both javascript (node.js) and Python.  That's  a lot to learn in a short period of time, and I'm by no means an expert yet.  However, I've seen enough patterns in modern web programming languages to state the following -- we'll call it The Theory of Four Things:

To be productive in a new web programming language, you only need to understand four things.

Libraries.  


How do to find, install and load the languages libraries; how to reference the library’s methods.

String Manipulation.


How do you print an output message?  How do you take a substring?  (related:  master regular expressions because most modern programming languages use them for string matching.)

Accessing and creating JSON documents.  


Most server-to-server communication is done with JSON documents these days.  Make sure you know how to put things into JSON format and get things out of a JSON object (or as Stack Overflow will probably tell you “a string that just happens to be a JSON object”).

HTTP requests.  


Those aforementioned JSON documents flow via REST API requests, all bundled up into HTTP requests.  Know how to create them, and how to troubleshoot them (this is where knowledge of networks and security comes in useful).