You can make a Chrome extension!

Inspired by this post by Lindsay Grizzard on how to make a simple Chrome extension, I decided to try my own.

According to the docs over at developer.chrome.com an extension should be a small program with a single, narrow purpose. Extensions are used to customize the browsing experience.

I started by following the beginning of Lindsay’s walkthrough to make an extension that renders a custom HTML page each time you open a new tab.

I made a directory with an index.html file and a manifest.json file.

Screen Shot 2018-10-17 at 10.38.29 PM.png

Every extension needs to have a manifest. It needs a name, description, version and manifest version. Manifest version should be set to ‘2.’ That’s the supported version right now. The other version is your project version number.

chrome_url_overrides is what’s going to let us start customizing. For the basic walkthrough we just told each new tab to load our simple index.html.

Screen Shot 2018-10-17 at 10.44.47 PM.png

To test it, we go to chrome://extensions and use the toggle in the upper right corner to switch to developer mode. Click “load unpacked” and select the extension directory. Now when I open a new tab ….

Screen Shot 2018-10-17 at 10.47.28 PM.png

That’s exciting, but I wanted to try something a little more fun.

With just one more file and a few more lines of code I made my extension trigger an alert on Twitter when you click the retweet button!

First, I made a very simple index.js file:

console.log('Hello Twitter')

Then I made an addition to manifest.json.Screen Shot 2018-10-17 at 10.55.13 PM.png

The content scripts run on certain websites. Matches sets a match pattern. This one will match any URL with twitter.com in it. Then I specify the path to my new index.js file. After the updates were made and saved, I had return to Chrome developer mode and tell the extension to refresh so it would get those changes.

Then, when I navigated to Twitter and checked the console to make sure index.js was connected. Screen Shot 2018-10-17 at 11.02.18 PM.png

It was! Next I spent some time poking around in the console. I practiced using querySelectorAll and getElementsByClassName to figure out how I was going to grab what I wanted to change.

I ended up selecting the retweet buttons by class name. Then I turned them into an array so I could map over them and add event listeners that would trigger my alert on click.

Screen Shot 2018-10-17 at 11.08.00 PM.png

Back at the Chrome developer mode I refreshed again and headed back to Twitter and started trying to retweet things.

Screen Shot 2018-10-17 at 11.09.41 PM.png

It works. It’s not ready for the Chrome Extension Store, but it’s fun to practice on!

Hiding secret credentials in Rails

I’ve tried to learn how to keep my API keys secret at some point during every Flatiron project I’ve done so far and failed and gave up. This time my partner and I got it to work and I wanted to save the whole process in one place for the next time I do this.

giphy

Rails 5.2 introduced the credentials file. You’ll find it in config/credentials.yml.env and it will look something like this.

Screen Shot 2018-10-03 at 7.58.37 PM.png

You can hide your API keys and any other credentials that need to remain secret herebut as you can see, it’s encrypted, so you can’t edit it directly. You can run this command in your terminal:

$ EDITOR=atom --wait rails credentials:edit

You can replace atom above with the name of your editor. This will open up a readable version of the file that you can edit. The file has a helpful commented out guide you can follow for formatting your secrets, but they should look something like this.

api: 
  id: 1234
  key: 3456789

It’s easy to draw on these secrets later when you’re ready to use them.

Screen Shot 2018-10-03 at 8.15.39 PM.png

Your Rails app will also have a config/master.key file, which you should add to your .gitignore. This master key is used to encrypt and decrypt the credentials.

Screen Shot 2018-10-03 at 8.03.45 PM.png

One wrinkle with this came up when my project partner cloned the project and tried to seed the database using our API keys. Since master.key was in the .gitignore file, she didn’t have that to decrypt the credentials file. So if a collaborator clones your project and needs to use your app’s credentials, they will need to create a master.key file that matches yours.

Bonus: Heroku

Hiding our API credentials this way caused us problems when we later deployed the app on Heroku (How to do that here). Since master.key was in our .gitignore, Heroku couldn’t get to the unencrypted version of our keys.

To fix it we saved our master.key to an environment variable. You can set Heroku a environment variable from the Heroku CLI by running:

heroku config:set RAILS_MASTER_KEY=YOUR APP'S MASTER KEY

I discovered later that you can also set up environment variables right on the Heroku dashboard for your application. Navigate to your application’s settings page and click the button that says Reveal Config Vars. You can add and edit your config variables here.

And now you have an app that doesn’t reveal your API secrets!

 

 

Javascript Dates

For my most recent pairing project, my partner and I built a habit tracking app. After selecting a user profile, the user could view a dashboard-type page that listed habits and days of the week in a table.

Javascript has a built in Date object that helped us achieve some of the functionality we were going for.

date

This week I spent some more time exploring Javascript Date methods and figuring out how to use them

Creating a new Date object with no parameters will give back a full date object for the current date and time, like the one below.

Screen Shot 2018-09-19 at 11.08.45 PM.png

If I just wanted to know the current year, I could use the .getFullYear() method on my currentDate variable. This will return just the four digit year.

Screen Shot 2018-09-19 at 11.13.40 PM.png

The .getDate() method works the same way.

currentYear.getDate()
// => 19

It’s a little bit more complicated to get the current month or day of the week.

Screen Shot 2018-09-19 at 11.19.25 PM.png

To get the name of the current day of the week you could make an array of the days of the week and use the number returned from .getDay() as the index, to grab the right day.

Screen Shot 2018-09-19 at 11.23.39 PM.png

The same process would work for finding the current month using .getMonth() method! I would make an array of the names of the months and use the value of currentDate.getMonth() as the index to find the month I’m looking for.

These are just a few of the built-in getter methods for Javascript’s Date object.

If I don’t want to work with the current date I can use the new Date() constructor with year, month, and date arguments to create the date object that I want. If I wanted to be really specific, I could also include arguments for hours, minutes, seconds and milliseconds.

Screen Shot 2018-09-19 at 11.48.34 PM.png

The Date constructor always returns a Date object. But what if I needed my date as a string? The Javascript Date object also has built-in conversion methods!

Screen Shot 2018-09-19 at 11.49.37 PM.png

These are just a few of the methods that come with Dates and seemed the most useful. Here’s a full cheat sheet. There are also a bunch of Javascript libraries for date and time manipulation.

Next week I’ll try out one or two of those to see if they can make it a little bit easier to make a full calendar in React.

Pig Latinizer using Regex

A few weeks ago I spent half a day working on a lab on Sinatra and the MVC. I needed to build a form to take user input, build a method to receive the user input, build a PigLatinizer model to convert a string to pig latin, convert the user input to pig latin and display the translated text.

I spent the majority of my time on this lab struggling to get the logic of the Pig Latinizer working and teamed up with a classmate. Eventually we got it working by adjusting a few methods we found online to work for the tests in this lab.

I wondered if I could simplify our translation method using regex and hoped to begin to understand regex through my refactoring.

The Basics

Regex looks for patterns inside strings. In Ruby, regular expressions are defined between two forward slashes. To find the first occurrence of a word or letter from a given string, put the string between two forward slashes. This is a literal character regular expression.

Simple regex code snippet

Using .match to see if there’s a match in my_string to the pattern between the forward slashes.

Non-comprehensive Cheat Sheet

(Seriously, there are too many modifiers and special character classes for one blog post.)

I recommend Rubular to build and verify that your regular expressions are finding what you think they are!

Character Classes and Ranges

/[aeiouAEIOU]/ => will match any one vowel, uppercase or lowercase.
/[a-z]/ => matches any lowercase letter
/[0-9]/ => matches any numeral

Adding a caret ^ to the beginning of a character class will match any character EXCEPT those in the character class.

/[^aeiou]/ => matches any character except a lowercase vowel

Special Character Classes

/\s/ => matches white space
/\d/ => matches any numeral. It's shorthand for /[0-9]/
/\D/ => is the opposite of /\d/.

Use a caret at the very beginning of your expression to indicate that you’re trying to match something at the start of a line.

/^[0-9]/ => matches a numeral only at the beginning of a line
/./ => matches everything except newlines

If you’re trying to match an actual period in your string, you’ll have to escape it.

/\./ => matches the . character

Check out this full cheat sheet from TutorialSprint if you’re looking for something that I didn’t cover!

Back to Pig Latin

To make my translator work I had two rules to follow.

  1. For words beginning with consonants, move all the letters that come before the initial vowel to the end of the word and add “ay” to the end.
  2. For words beginning with vowels, add “way” to the end.

Let’s break the method for translating an individual word into two parts corresponding to those rules. First I want to see if the first letter in the string passed into my method is a vowel.

Screen Shot 2018-08-22 at 11.47.08 PM.png

I’m using the caret at the front of the expression to indicated that I’m only interested in the first letter and the character class of [aeiou] to match vowels. The i at the end of the expression says we’re ignoring case so the expression will match any vowel, uppercase or lowercase.

If it finds a match, it will add “way” to the end of the given word.

The else, to handle words not beginning with vowels was the really tricky part.

Screen Shot 2018-08-22 at 11.57.57 PM.png

We recognize the character class. [aeiou] is looking for vowels. The . matches any single character and the * tells whatever comes before it to match zero or more of it.

In other words, we’re finding the first vowel with zero or more characters coming after it. If we left it at that, the expression would match and give us only the first vowel, but for my method I still need the rest of the word. That’s what the parentheses do.

So this snippet takes my text and splits it at the first vowel and gives me an array of everything before the first vowel and everything after the first vowel.

Let’s say we called it on the word “stream.”

"stream".split(/([aeiou].*)/) => ['str', 'eam']

Now I can access those pieces of the word using their array indexes, rearrange them and add “ay.

Great! Now that I can translate a single word to pig latin I can use it in another method that accepts a larger chunk of text.

Screen Shot 2018-08-23 at 12.13.16 AM

I can split my user input on spaces and get an array of words. Then I can map through my words array and run my translation method on each one and join them back up at the end.

Implementing regular expressions really simplified my methods for this lab. You can compare here.

Taking the time to refactor my translator in this lab helped me feel slightly more comfortable with regular expressions, but I’m still going to be turning to one of these many regex testers the next time I need to write one.

MVC and RESTful Routing

This week the Flatiron School curriculum introduced me to the MVC pattern. MVC is a straightforward way of structuring applications and I love it. Often when I’m working on labs or building something new I feel like a need a map to keep track of all the parts and how they work together. The MVC pattern is a simple map of an application.

An example of MVC file structure

The app folder from one of my labs, divided neatly into controllers, models and views.

M is for Models. A model is like an instruction manual for how to create and save your data.

V is for Views. This is what the user of the application will get to see!

C is for Controllers. The controller sits right in the middle of the application. It takes requests from the browser, tells models and views what to do with them and responds to the browser request.

I like being able to see and understand the different parts of my application in Atom’s tree view while I’m working.

The most difficult part of this concept for me to really internalize this week has been how the routes in my controllers are actually interacting with the rest of my application.

This is where RESTful routes come in. At the most basic level, RESTful routing is a naming pattern that allows an application to take HTTP requests, find them in the controller, and execute the Ruby code inside.

In practice

The most difficult part of my labs this week has been figuring out how to start. I fork and clone the repository take a look at the README and click around the file tree. Which route should I write first? Should I write out the code that needs to happen in the view first?

This seems simple, but I’ve found during the past few weeks that the best way for me to learn is to draw myself a map or a chart.

In the lab I used to map the RESTful routes for myself I was building an application to store recipes.

Here’s the guide I made that helped me more easily understand what was happening between my views and my controller when a user was interacting with the application.

Screen Shot 2018-08-08 at 10.26.05 PM.png

There are a lot of cheat sheets structured like that one out on the internet, but writing one specific to my code helped me really wrap my mind around how to write routes and how they interact with my models, views and controllers.

The next time I find myself not knowing where to start building an application, I’m going to start by turning it into a chart like this one and adding the my results as comments in my controllers.

I’m hoping this will be especially helpful when I’m dealing with more complex applications with more than one model and controller and many more views.