List of sublime text shortcuts, tips and tricks

I started using sublime text over the past couple months (RIP textmate) and it’s been awesome so far. I wanted to create a short list of the shortcuts, tips and tricks that I’ve found most useful:

Files
cmd+p — Go to Anything
cmd+ctrl+p — Switch Project

Codes
cmd+shift+d — Duplicate Line
ctrl+enter — Insert line after
ctrl+shift+enter — Insert line before
cmd+l — Expand Selection to Line
ctrl+shift+w — Wrap Selection with Tag
ctrl+r — Go to symbols (finding methods)

Multi Edits
ctrl+d — Select the current word and the next same word
ctrl+click — Every place you click will create a cursor to edit
ctrl+shift+f AND alt+enter — Find a word in your files and then select them all
ctrl+] — Indent
ctrl+[ — Unindent
Ctrl+Shift+UP — Move lines up
Ctrl+Shift+Down — Move lines down

Multi Selection
To enable multi-selection, you have several options:

Alt or Command — then click in each region where you require a cursor.
Select a block of lines, and then press Shift + Command + L.
Place the cursor over a particular word, and press Control/Command + D repeatedly to select additional occurrences of that word.
Alternatively, add an additional cursor at all occurrences of a word by typing Alt+F3 on Windows, or Ctrl+Command+G on the Mac. Amazing!! <span 				data-mce-type="bookmark" 				id="mce_SELREST_start" 				data-mce-style="overflow:hidden;line-height:0" 				style="overflow:hidden;line-height:0" 			></span>

Refactoring your code

There was once a time when I had a deep affection for mathematics. I think we fell apart sometime during college but my quest to learn programming has renewed this relationship.

A major concept in computer science that I’m still getting a hang of is refactoring. It’s very similar to factorization in mathematics where you have an expression that you want to reduce to “basic building blocks”. E.g. if “x = a + b + c” and “y = a + b” then you can factor “x = y + c”.

This same concept lends itself to computer programming by the name of refactoring. Similarly this process involves rearranging a program to facilitate code re-use and improve the readability of your code.

Here’s an example from today. I’m working on a procedure “addpageto_index” that takes three inputs and updates the index to include all of the words found in the page content by adding the url to the associated word’s url list. If that’s a little confusing (or worded terribly) this problem set is one of many on the way to building a search engine. In this example I am looking for some content (word) and want to find all the url links associated with that word:

index = []

def add_to_index(index,keyword,url):
    for entry in index:
        if entry[0] == keyword:
            entry[1].append(url)
            return
    index.append([keyword,[url]])

def add_page_to_index(index,url,content):
    a = content.split()
    #print a
    for word in a:
        for entry in index:
            if entry[0] == word:
                entry[1].append(url)
                return
        index.append([word,[url]])

add_page_to_index(index,'fake.text',"This is a test")
print index

The previous problem was already used to find a procedure that adds keywords to an index with their associated urls, “addtoindex” (which is the first part of the above code). I initially started this problem by rewriting the first part to include the “content” or words in the second part.

After some initial trial and error the second part of my code looked like this:

def add_page_to_index(index,url,content):
    a = content.split()
    #print a
    for word in a:
        add_to_index(index,word,url)<span 				data-mce-type="bookmark" 				id="mce_SELREST_start" 				data-mce-style="overflow:hidden;line-height:0" 				style="overflow:hidden;line-height:0" 			></span>

Unbeknownst to me I should have just used refactoring the whole time as I already had written what was needed previously. Eventually I saw that I could refactor the code and was able to solve the problem. I still feel very new to this but it gets me excited every time I notice small things like that. I think I’m slowly getting there.

Building a Rails 4 app using the Twilio API

This weekend I wanted to challenge myself by building a functional web application using the rails framework. My goal for this project was to use an API that I was unfamiliar with and that could be used from my iPhone.

I settled on the Twilio API. Twilio is a company who services voice calling and SMS messaging integration into your app. On the messaging side the service works by essentially turning all text messages into a RESTful architecture. By utilizing a RESTful architecture for your incoming/outgoing SMS requests, you are able to map those requests to the routes in your rails application.

Behind the scenes Twilio figures out how to handle your app requests by using a construct known as webhooks. This is done for you on Twilio’s side. When someone makes a request to your twilio number, either by phone or SMS message. The webhook which is simply an URL will handle that request and follow the directions you give it to make a follow up call or text message.

The entire process of putting this app together was a very frustrating but tremendous learning experience. From a technical standpoint the actual code was not that difficult. The most challenging part was configuring my rails app to talk with Twilio.

You have to very, very RESTful minded when integrating Twilio into Rails. As I’ve gone through this journey I wanted to put together a step-by-step tutorial to make it easier for the wider developer community:

1 Create a Twilio account

First sign up for a Twilio developer account. The account is free and you will be given a certain amount of credit ($$$) to use on your account.

Remember that Twilio actually sends out SMS messages and/or voice calls which does cost money. (A simple google search will help you to find coupons that you can use to add more credit to your account, especially if you’re a student!)

2 Configure your account

During sign up Twilio will either send you a text message or a quick phone call to make sure you are not a spambot. We all hate those now don’t we?
Input the verification code and then proceed to getting your phone number.

3 Choose a phone number

Next get your Twilio number. This is a unique phone number given to you by Twilio which will allow you access to their voice calling and SMS messaging capabilities for the API.

Twilio will assign you a random phone number but you can choose your own based on your location.

4 Add Twilio to your new Rails 4 app

Start up your rails new app

rails new twilio-messages

Add the twilio gem to your Gemfile

gem 'twilio-ruby'

5 Add your aunthentication keys

You can find your authentication keys on your Twilio dev account. You will need both the accountsid and authtoken. For example let’s say you wanted to show all incoming text messages on your rails view.

# messages_controller.rb

class MessagesController &amp;amp;amp;lt; ApplicationController
 def index
  client
 end

 private

 def client
  twilio_phone_number = "9734594512"
  account_sid = 'FDlkje3553l;kj6ljfsafdasf'
  auth_token = 'SFDFAF78987FdfE889'

  # set up a client to talk to the Twilio REST API
  @client = Twilio::REST::Client.new account_sid, auth_token
 end
end

Then in your view:

<h1>Lauryn</h1>
<% @client.account.messages.list({}).each do |message| %>
<ul>
 <li><%= message.body %></li>
</ul>
<% end %> 

6 Test your app locally with ngrok

Since Twilio is looking for a live GET/POST request from your app you will not be able to integrate Twilio on localhost:3000 alone. You can use the ngrok gem which essentially creates a live webserver on the internet for your gem so that you can test it locally.

Gem here

7 configure your incoming/outgoing routes

This is how your app will retrieve data from Twilio and then process the incoming or outgoing requests. You MUST make sure that your controller#action matches what you have on your Twilio dev account.

Rails.application.routes.draw do
 resources :messages
 get '/incoming', to: 'incoming#send_message'

 root 'messages#index'

8 Handle incoming SMS and replying

Twilio allows you to handle incoming SMS messages and then reply to them based on their given body. Twilio uses a special XML format called TwiML that turns the SMS message into a hash containing a lot of data. You can use params[:Body] to respond to a given SMS through your matching controller#action.

# incoming_controller.rb

class IncomingController &amp;amp;lt; ApplicationController 
 def send_message
  body = params[:Body]

  @twiml = Twilio::TwiML::Response.new do |r|
   if body == "Lauryn, what is my current location?"
    r.Message "Ready Or Not, Here I Come, You Can't Hide.
Gonna Find You and Take it Slowly" 
   else
    r.Message "You might win some but you just lost one"
   end
   # r.Message "What up bruh."
  end

  render 'send_message.xml.erb', :content_type =&amp;amp;gt; 'text/xml'
 end

end

Then make your relevant route using an XML view:

#send_message.xml.erb

<Response>
 <Sms><%= @twiml.text %></Sms>
</Response>

9 Change url to your server

Make sure your SMS url is set to GET and that it matches the same URL in your route.

10 Getting puma/postgres/heroku up and running

You will probably want to have your app go live on the internet. Heroku is a good server that you can use. For your first time: YOU WILL GET FRUSTRATED. Make sure you read the docs.

heroku logs tells you nothing heroku run rails console is okay heroku logs is your best friend

11 Finally here are some final pointers in deploying:

Remember to always be pushing to heroku, some of your app updates might not get reflected in Twilio.

rails c = app.class

Do not name your methods reserve words like send

Twilio methods are case sensitive
Twilio::Twiml != Twilio::TwiML
Twilio::Rest::Client != Twilio::REST::Client

12 rails is convention over configuration

= goes out the window when using APIs

Object feels and introspection

One of the most interesting concepts I’ve learned so far about the Ruby programming language is the idea of introspection. In computing, type introspection is the idea that an object or program knows about it’s own properties at runtime.

Specifically in regards to Ruby this means that an object is self-aware and knows what it is, what values it contains and what’s going on around it at a given moment in time. In short, Ruby objects can have feels.

Similar to our good friend Keanu, a Ruby object can have a moment of reflection at a given moment in time. Let us make code:


x = "hello world"
x.class #=> String

x = :hello_world
x.class #=> Symbol

This is a relatively straightforward example that shows how Ruby is able to reflect on itself at two separate moments in life. We can ask Ruby what type of object it is, what type of methods we can call it and then infer more information about it’s scope given that information.

 

The importance of introspection

At this moment you’re probably asking yourself a number of questions.
What’s the big deal? Who cares if “Hello World”.is_a?(String) knows that it’s a string. It doesn’t seem all that complex or exciting.

WRONG.

Although by nature it’s a relatively simple concept, the building blocks that introspection provides come together to form the Voltron that is object orientation. The building blocks of introspection form complexities which allow us to create objects that can interact with each other.

Furthermore, introspection is crucial in our use of mixins, modules and class methods. At the most fundamental level introspection allows us to do all things Ruby and for that we must be forever grateful.


based_god = Class.new
young_based_god = Class.new(based_god)

lil_b = based_god.new
brandon = young_based_god.new

lil_b.instance_of?(based_god) #=> true
brandon.instance_of?(based_god) #=> false
brandon.kind_of?(based_god) #=> true

In our example we create two distinct classes, based_god and young_based_god with based_god being a superclass of young_based_god. We next create two instances of each of these two classes.

Ruby has a method called instanceof? that allows us to check the class of an instance. When comparing both instances we find that only lilb is an instance of the Class based_god.

However, when we use the Ruby method kindof? it is clear that Ruby knows that brandon is a subclass of *basedgod. Through introspection the language implicitly knows that *based_god is a superclass of young_based_god.

The idea of introspection is helpful to us as programmers because we do not have to guess the type of an object. If we want to know what an object is or what methods are available to us to use on that objects we can just ask.

Introspection means that we can make two different objects interact with each other in very unique ways and still be confident that their behavior will do what we expect. It is key to the beauty of Ruby and part of the reason it flows like a natural human language.

Thank you Matz and thank you based god.

The layman’s guide to regex: what is regex exactly?

RegEx stands for regular expression and it is a common tool used by programmers to match patterns of string data. “WAIT, I thought this was the layman’s explanation?!” Let us continue.

A good way to think about regular expressions is a sifter for string data. Let’s say you have a recipe for an amazing cake but your string flour is too lumpy and stuck together. The regular expression sifter will allow you to collect the string flour of your choosing so that you can finish the recipe. And you can keep adding filters to the sifter to make your flour even more fine.

At the most fundamental level, a regular expression allows us to find, manipulate and collect data within strings. A string is one of the most common data types in computer science and it is usually just a sequence of characters between a pair of quotes.


This is a string

With regular expressions we can take a string like the one above and match certain patterns that we are looking to find. Say for instance we wanted to change every ‘s’ character to the number ‘5’.

We could use regular expression to do that instead of re-typing every single time the letter ‘s’ appears. This might seem like a trivial task for the above example but imagine doing this for a research paper you have been working on or maybe even your first novel.

Regular expressions make that process of matching certain data within strings much easier and that is why it so useful. You probably use regular expressions everyday without know it. Everytime you open up a Google Doc or Microsoft Word to use the “Find and Replace” feature you are using a regular expression!

 

Using regular expressions

When I first started learning about regular expressions I was very intimidated because the syntax looked very complicated. You might see a regular expression that looks like this:

​/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.[\W]).{8,}$/

The above is a regular expression for a password that satisfies a strict set of conditions. These are the types of regular expressions that I first saw and it boggled my mind. Let’s start with something a little more straightforward.

Here we have a string of some sample song lyrics. Let’s switch up the words a little bit:


lyrics_test = File.read('lyrics')
replacements = [ [/club/, "pull request"], [/girl/, "labs"], [/the cut/, "my repo"], [/she/, "they"] ]

replacements.each {|replacement| lyrics_test.gsub!(replacement[0], replacement[1])}

puts lyrics_test

In this very simple example we can use one of the most popular tools for regular expressions called gsub.

The method gsub takes two arguments, the first being the data you want to replace and the second being the data you want to replace it with. In our example we have an array of values we want to replace along with the values we want to replace them with.

​replacements = [ [/club/, "pull request"]...

RegEx uses the syntax of two forward slashes and anything you place inside of those slashes becomes your regular expression /-ANYTHING-/. In the first iteration we have our regular expression of /club/ and we replace it with the string ‘pull request’.

Let’s take a look at another example:

lyrics_test = File.read('lyrics')
replacements = [ [/ [t][A-Za-z]{3} /, " code "] ]

replacements.each {|replacement| lyrics_test.gsub!(replacement[0], replacement[1])}

puts lyrics_test

In this example we want to replace every four letter word that begins with the letter ‘t’, with the word ‘code’.

Looking more closely at our regular expression inside of /-ANYTHING-/ we can see that it starts with an empty space. This will be the start of any new word. Now we want to specify only words that begin with the letter ‘t’. Using [t] we are able to pinpoint only the first words that start with the letter ‘t’.

Next we use a handy regular expression trick to specify any alphabetical letter. [A-Za-z] means ANY character from capital A-Z or lower case a-z. Finally we specify that we want exactly three of the characters using {3} to complete a four letter word.

RegEx has a treasure chest of pattern matchers which allow you to match the different sequences across your strings. I would highly recommend playing around with Rubular and RegExr to get more familiar. Once you get the syntax and matchers down I promise you will it will begin to click!

Ruby Class Shortcuts

class Person
 attr_accessor :name, :age
end

# same as:

class Person
 def name
 @name
 end

def name=(name)
 @name = name
 end

def age
 @age
 end

def age=(age)
 @age = age
 end
end

Ruby is awesome. I think it has to do with the ease and beauty of Textmate but I really look forward to typing out code using the language. Additionally I’ve been introduced to many shortcuts which make writing code a lot easier.

One recent shortcut which I’ve been trying to wrap my head around is attraccessor. In the above code you will see the one line “attraccessor :name, :age” re-writes everything below.

It basically performs the read and write methods on a function. This allows you to call x.name and return whatever x is and also allows you to assign x.name = “Jahde”.

I’m sure I’ll be seeing other shortcuts that make writing code easier but this one stood out to me. I think I’m just shocked that 1 line can replace 12 but I’ve come to find this is one of the key attributes of programming itself. Ruby wants to make herself easy to love.