Nil vs empty vs blank in Ruby on Rails

In practice, it can be a little difficult to keep track of the differences in nil, empty, and blank in rails. The following explains their differences.


What nil, empty, and blank means in Rails

.nil? can be used on any object and is true if the object is nil.

.empty? can be used on strings, arrays and hashes and returns true if:

  • String length == 0
  • Array length == 0
  • Hash length == 0

Running .empty? on something that is nil will throw a NoMethodError.

That is where .blank? comes in. It is implemented by Rails and will operate on any object as well as work like .empty? on strings, arrays and hashes.

nil.blank? == true
false.blank? == true
[].blank? == true
{}.blank? == true
"".blank? == true
5.blank? == false
0.blank? == false

.blank? also evaluates true on strings which are non-empty but contain only whitespace:

"  ".blank? == true
"  ".empty? == false

Rails also provides .present?, which returns the negation of .blank?.

Array gotcha: blank? will return false even if all elements of an array are blank. To determine blankness in this case, use all? with blank?, for example:

[ nil, '' ].blank? == false
[ nil, '' ].all? &:blank? == true 

Source: StackOverflow

How the Ruby on Rails Authenticity Token Works

How the Authentication Token Works

When the user views a form to create, update, or destroy a resource, the Rails app creates a random authenticity_token, stores this token in the session, and places it in a hidden field in the form. When the user submits the form, Rails looks for the authenticity_token, compares it to the one stored in the session, and if they match the request is allowed to continue.

Continue reading How the Ruby on Rails Authenticity Token Works

Ruby on Rails Get Absolute Current URL

Getting the absolute URL of the current page is simple.

Versions of Ruby on Rails implementations for getting current URL

For Rails 3.2 or Rails 4+

Use request.original_url to get the current URL.

This method is documented at

For Rails 3

You can write "#{request.protocol}#{request.host_with_port}#{request.fullpath}", since request.url is now deprecated.

For Rails 2

You can write request.url instead of request.request_uri. This combines the protocol (usually http://) with the host, and request_uri to give you the full address.

Email Validation with Regular Expressions

Regular expressions for catching valid email addresses is complex and requires a lot of conditions.

Two Approaches to Regex Validation of Email Addresses

Basic Syntax Email Validation Regex


Very Advanced and Thorough Email Validation Regex

(?:(?:\r\n)?[ \t])*(?:(?:(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t]
)+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:
\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(
?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ 
\t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\0
31]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\
](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+
(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:
(?:\r\n)?[ \t])*))*|(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z
|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)
?[ \t])*)*\<(?:(?:\r\n)?[ \t])*(?:@(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\
r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[
 \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)
?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t]
)*))*(?:,@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[
 \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?: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?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>
@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"
(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t]
)*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\
".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?
:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[
\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*|(?:[^()<>@,;:\\".\[\] \000-
\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(
?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)*\<(?:(?:\r\n)?[ \t])*(?:@(?:[^()<>@,;
:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([
^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\"
.\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\
]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*(?:,@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\
[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\
r\\]|\\.)*\](?:(?:\r\n)?[ \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:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t
])*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t
])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?
:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|
\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*|(?:
[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\
]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)*\<(?:(?:\r\n)
?[ \t])*(?:@(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["
()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)
?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>
@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*(?:,@(?:(?:\r\n)?[
 \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,
;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t]
)*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\
".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*)*:(?:(?:\r\n)?[ \t])*)?
(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".
\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:
\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[
"()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])
*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])
+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\
.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z
|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*\>(?:(
?:\r\n)?[ \t])*))*)?;\s*)

How to Prevent SQL injection in PHP

If user input is inserted without modification into an SQL query, then the application becomes vulnerable to SQL injection.

Two ways of preventing SQL injection in PHP websites and forms

Option 1: Validate and sanitize the input data with PHP code

Essentially, you’ll be escaping strings and removing bad characters.


Option 2: Use a prepare statement

Note: this is specifically available in MySQLi

    $mysqli = new mysqli("server", "username", "password", "database_name");

    $unsafe_variable = $_POST["user-input"];
    $statement = $mysqli->prepare("INSERT INTO table (column) VALUES (?)");

    // "s" means the database expects a string
    $statement->bind_param("s", $unsafe_variable);


Other Considerations

More complex cases may require more complex approaches. Examples include:

  • If you want to alter the structure of the SQL based on user input, parameterised queries are not going to help, and the escaping required is not covered by mysql_real_escape_string. In this kind of case you would be better off passing the user’s input through a whitelist to ensure only ‘safe’ values are allowed through.
  • If you use integers from user input in a condition and take the mysql_real_escape_stringapproach, you will suffer from the problem described by Polynomial in the comments below. This case is trickier because integers would not be surrounded by quotes, so you could deal with by validating that the user input contains only digits.
  • There are likely other cases I’m not aware of. You might find a useful resource on some of the more subtle problems you can encounter.

How to Check for an Active Internet Connection on iPhone SDK

There are several ways to check for an active internet connection on an iPhone.

Examples of Checking for an Internet Connection in Objective C

Use a simple (ARC and GCD compatible) class to do it

  1. Add a SystemConfiguration framework to the project.
  2. Get and include the Reachability code (written by Tony Million) at
  3. Update the interface
    #import "Reachability.h"
    // Add this to the interface in the .m file of your view controller
    @interface MyViewController ()
        Reachability *internetReachableFoo;
  4. Implement a testConnection method in your .m file that you can call when needed.
    // Checks if we have an internet connection or not
    - (void)testInternetConnection
        internetReachableFoo = [Reachability reachabilityWithHostname:@""];
        // Internet is reachable
        internetReachableFoo.reachableBlock = ^(Reachability*reach)
            // Update the UI on the main thread
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"Yayyy, we have the interwebs!");
        // Internet is not reachable
        internetReachableFoo.unreachableBlock = ^(Reachability*reach)
            // Update the UI on the main thread
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"Someone broke the internet :(");
        [internetReachableFoo startNotifier];


Or, implement Apple’s reachability class

  1. Add SystemConfiguration framework to the project but don’t worry about including it anywhere
  2. Add Apple’s version of Reachability.h and Reachability.m to the project (you can get those here)
  3. Add @class Reachability; to the .h file of where you are implementing the code.
  4. Create a couple instances to check in the interface section of the .h file:
    Reachability* internetReachable;
    Reachability* hostReachable;
  5. Add a method in the .h for when the network status updates:
    -(void) checkNetworkStatus:(NSNotification *)notice;
  6. Add #import "Reachability.h" to the .m file where you are implementing the check
  7. In the .m file of where you are implementing the check, you can place this in one of the first methods called (init or viewWillAppear or viewDidLoad etc):
    -(void) viewWillAppear:(BOOL)animated
        // check for internet connection
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkNetworkStatus:) name:kReachabilityChangedNotification object:nil];
        internetReachable = [Reachability reachabilityForInternetConnection];
        [internetReachable startNotifier];
        // check if a pathway to a random host exists
        hostReachable = [Reachability reachabilityWithHostName:@""];
        [hostReachable startNotifier];
        // now patiently wait for the notification
  8. Set up the method for when the notification gets sent and set whatever checks or call whatever methods you may have set up (in my case, I just set a BOOL)
    -(void) checkNetworkStatus:(NSNotification *)notice
        // called after network status changes
        NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];
        switch (internetStatus)
            case NotReachable:
                NSLog(@"The internet is down.");
                self.internetActive = NO;
            case ReachableViaWiFi:
                NSLog(@"The internet is working via WIFI.");
                self.internetActive = YES;
            case ReachableViaWWAN:
                NSLog(@"The internet is working via WWAN.");
                self.internetActive = YES;
        NetworkStatus hostStatus = [hostReachable currentReachabilityStatus];
        switch (hostStatus)
            case NotReachable:
                NSLog(@"A gateway to the host server is down.");
                self.hostActive = NO;
            case ReachableViaWiFi:
                NSLog(@"A gateway to the host server is working via WIFI.");
                self.hostActive = YES;
            case ReachableViaWWAN:
                NSLog(@"A gateway to the host server is working via WWAN.");
                self.hostActive = YES;
  9. In your dealloc or viewWillDisappear or similar method, remove yourself as an observer
    -(void) viewWillDisappear:(BOOL)animated
        [[NSNotificationCenter defaultCenter] removeObserver:self];

Objective C difference between atomic and nonatomic attributes

This post will explain the difference between atomic and nonatomic property declarations, and the functional differences between them.

Sample Atomic and Nonatomic properties

@property(nonatomic, retain) UITextField *userName;
@property(atomic, retain) UITextField *userName;
@property(retain) UITextField *userName;

The difference between “atomic, retain” and “retain”

@property(atomic, retain) UITextField *userName;
@property(retain) UITextField *userName;

The two lines above are identical in meaning.

What Atomic Properties Are

Assuming that you are @synthesizing the method implementations, atomic vs. non-atomic changes the code that is generated. If you are writing your own setter/getters, atomic/nonatomic/retain/assign/copy are merely advisory.

Note: @synthesize is now the default behavior in recent versions of LLVM. There is also no need to declare instance variables; they will be synthesized automatically, too, and will have an _ prepended to their name to prevent accidental direct access.

With “atomic”, the synthesized setter/getter will ensure that a whole value is always returned from the getter or set by the setter, regardless of setter activity on any other thread. That is, if thread A is in the middle of the getter while thread B calls the setter, an actual viable value — an autoreleased object, most likely — will be returned to the caller in A.

What Nonatomic Properties Are

n nonatomic, no such guarantees are made. Thus, nonatomic is considerably faster than “atomic”.

What “atomic” does not do is make any guarantees about thread safety. If thread A is calling the getter simultaneously with thread B and C calling the setter with different values, thread A may get any one of the three values returned — the one prior to any setters being called or either of the values passed into the setters in B and C. Likewise, the object may end up with the value from B or C, no way to tell.

Avoiding Errors

Note that there is no “atomic” keyword, if you do not specify “nonatomic” then the property is atomic, but specifying “atomic” explicitly will result in an error.

How to Rename a Database Column with a Migration

If you’ve misnamed a column and would like to change it, do the following to fix it in migrations.

It is very easy to change it using rails migrations, so don’t try to do anything complicated or hacky. Just use the built-in tools. :)

Simple Database Column Rename

rename_column :table, :old_column, :new_column

Advanced Database Column Rename with New Migration

rails g migration FixColumnName

class FixColumnName < ActiveRecord::Migration
  def change
    rename_column :table_name, :old_column, :new_column

Advanced Database Multiple Column Renames with New Migration

rails g migration FixColumnName

class FixColumnName < ActiveRecord::Migration
  def change
    rename_column :table_name, :old_column, :new_column
    rename_column :table_name, :old_column2, :new_column2

Source: StackOverflow

Swift 2.0 append() Reference


Using string.append(character) adds a single character to the end of a string.




let str:String = "I'm Ron Burgundy";
var char:Character = "?"; //must be 1 character long

print(str.append(char)) // I'm Ron Burgundy?

Swift 2 isEmpty Reference

The property returns a boolean true if empty, false if not empty.




import Foundation

let myString = "Hello World.";
println(myString.isEmpty) // false
import Foundation

let myString = "";
println(myString.isEmpty) // true