Tag Archives: Coding

Code: Data structure

In my understanding there are different types of data. Each is unique in purpose, mutability, and scope. Clearly identifying the role of an attribute and grouping it with related ones creates a cleaner interface to work with.

Raw Attributes

The raw data that is persisted to the server.

This data should be treated as if immutable, unless planning to persist a change of one of the values to the database. This is the once source of ‘truth’ that is trustworthy. If it is reformatted, or changed it looses its trustworthiness.

user: {
 firstName: 'Phil',
 lastName: 'McCool',
 username: 'pmccool'
}

Computed Values

Take in Raw Data, and reformat it for later use.

More often than not these are a convince to remove the need to repeat logic throughout the app.

If there is an urge to create a value here to describe the model’s content ‘isAdmin’, ‘fullName’, there is a good chance these ought to be part of the data schema to start with.

They can come at a cost of being computed but not always needed everywhere throughout the app. Alternately getter functions could be used to allow a more ‘on-demand’ approach (add result caching and get the both of both worlds).

computed: {
 fullName: 'Phil McCool',
 shortName: 'Phil M.',
 numberVowels: 3
}

State

Describing the state status, of either the data or of the component/view.

State data describes progress or what things are doing currently – [changing, updating, modified]. While these are similar to configuration items, they mutable are more closely tied to the model data describing what is happening to it. If their were multiple components/views that display the same model, they may all want to know the current state of the data. It’s meta data to the data.

These values should update frequently.

state: {
 isLoading: false,
 isModified: true,
 page: 4
}

Configuration

How something should be displayed or behave.

These ought be on the component/view that is rendering the item. It describes the preferences of how something should behave or be displayed. Think of them as options, ways to deviate from the norm, an API for this component/view.

A component/view should have a set of defaults for these values to fall back upon.

Config attributes can make it tempting to overload abstraction. Draw a line of making a new component/view when the core functionality has config options that cause different logic paths.

config: {
 size: 'large',
 template: 'card',
 color: 'blue'
}

 


Take Aways

It can be very tempting to merge or stuff configuration and state data right into the model data. It’s convenient, but lazy. It taints the raw data. If put an ‘isLoading’: true value into our data model then persist it to the server, we ought to feel like we did something wrong.

Ideally we would be able to group data in our actual data structures, but at minimum, we can always just keep in mind the role of an attribute and group mentally.

TL;DR

  • Not all data is alike.
  • Don’t mutate / override original data
  • Computed, State, and Config data shouldn’t be mixed in with raw data.

Code: jquery.otherdropdown.js

Today I published my first node npm package and bower package – jquery.otherdropdown! For quite a while I’ve been reusing a simple code snippet that made it possible for a user to add their own custom response to a select dropdown. I never thought I would publish it.

The principle is simple, in a list of options when the ‘other’ response is selected, prompt the user to specify what they mean. Try out the demo.

jquery.otherdropdown

I’ve seen forms that add an additional input, but it’s effective – but feels choppy to the user. Processing the data can also be slightly more complex when you have to check for a value that may or may not exist.

A long while ago I wrote a script (before jQuery was prevelent) that manipulated the DOM to give the effect I was after. Since then it’s been modified and switched to use jQuery and made it into a plugin.

The functionality is all self contained and pretty simple to use.  Use jQuery to get the select dropdown and runn the plugin on it:

$('.myDropdown').otherdropdown();

Publishing it to Bower I realized could be helpful not only to me but to everyone. Why not give it a go? Many things needed to be done, make it flexible with options for customization, create documentation and demos, and sharpen up the code. After several hours it was ready to go!

It’s been fun to work on. More complex idea are cooking.

Tips: My Favorite Sublime 3 Packages

I primarily use Sublime as my code editor of choice; a bunch of us at Sprout Social do. It’s simple, clean, lightweight on system resources, and it has some pretty sweet packages. I’ve found a number of packages that increase my efficiency developing. Thought I’d share several of these personal favorite Sublime 3 packages.

If you’re on Sublime 2, upgrade to Sublime 3, it’s totally stable.

To get started you’ll need to install Sublime Package Control into Sublime. It’s fairly simple, and the you’re read to go. The “Package Control: Install Package” command will now be available in your command pallet via Cmd+Shift+P or Ctrl+Shift+P.

SublimeLinter

SublimeLinterBase package for all linters. Syntax error highlighting can greatly reduce the save-run-revise cycle time. Most IDEs already have syntax error highlighting, why not add it to Sublime?

There are many SublimeLinter packages. Browse through them find what fits your workflow. Be sure to follow each packages setup instructions, each will be a bit different.

My personal must have’s are:

  1. SublimeLinter-phplint
  2. SublimeLinter-jshint
  3. SublimeLinter-jsxhint
  4. SublimeLinter-csslint
  5. SublimeLinter-contrib-scss-lint

BracketHighlighter

BracketHighlighterAn even better bracket highlighting than what comes with Sublime. It also shows starting and ending brackets in the gutter, and can matching for [ ], ( ), { }, ” “, ‘ ‘, <tag> </tag>.

SideBarEnhancments

Give the context menu more options when right clicking on files in a project. Duplicate files, move, rename, etc.

DocBlockr

DocBlockrEasier creation of document blocks for functions, classes, methods. It’s intelligent and looks ahead to see what you’re documenting to pre-fill the base info (such as input parameters and what is returned). Documenting is now convenient.

Pro tip: use the Tab key to navigate through the generated documented block, no need to click or use arrow keys.

Shell-Turtlestein

Launch the terminal/command line right in the context of your project directly from Sublime.  Either as a new window or as its own panel within sublime.

GitGutter

Visually shows the diff since the last commit in the gutter.  At a glance you can see what lines are additions, modifications, or deletions.

Origami

Split Sublime into multiple horizontal and vertical panes for side-by-side work. Remove the need to switch between tabs or windows as frequently when comparing files.

TrailingSpaces

Highlights and helps cleanup end of line trailing spaces. Nobody likes them right? Or maybe we just don’t notice them.

 

There are many other great packages out there for Sublime : code snippets, theme,  and syntax highlighting. But these are just some of my favorites.

Code: Laravel Scope Query on a Model

Let’s talk a bit about scoped queries in Laravel. First here is a basic Book Eloquent Model with two handy scopes for type and fewerPagesThan.

//Book Model
class Book extends Eloquent {
public function scopeType( $query, $type ) {
return $query->where( 'books.type', '=', $type );
}

public function scopeFewerPagesThan( $query, $pages ) {
return $query->where( 'books.pages', '<=', $pages ); } }

Using scoping

I often see confusion when we try to use scoping. Some would expect the following to give them back all 'autobiography' books:


Book::type('autobiography'); // This works right? Nope!

But it doesn't. Scoping functions will only refine your query. For instance all the following are great examples of using scoping:


Book::type('autobiography')->get();
Book::with('author')->type('autobiography')->get();
Book::fewerPagesThan(500)->type('autobiography')->get();

Building up scopes

When using scopes to refine and filter down which Models to retrieve, you will always need to add a ->get() at the end. This allows you can chain multiple "scopes" onto each other as in the 3rd example. Basically it needs to know when you are done filtering down and when to actually hit the database.

So the 3rd example could be broken down like this to really drive home the point:


$maxPages = 500;

$books = new Book();
$books->type('autobiography');
if( $maxPages )
$books->fewerPagesThan($maxPages);
$opportunities->get();

In every case before the ->get() call $books var is a Eloquent/Builder that is being built up.

After the ->get() call $books var gets overwritten with an Eloquent/Collection that has been filled with our data from the database.

This is a very powerful and flexible to way to scope and filter down models that are in your database. It is better to filter them down with scopes in the DB query than filter down a collection that has already been loaded into memory. Make the your DB do some weight lifting for you. 😉

Code: Backbone.js Selecting Elements with jQuery

Found a very simple way to get a jQuery rapped DOM element that is within a subView in Backbone. using `this.$( )`. This is pretty handy because it traverses only DOM elements within the current view instead of the entire DOM tree.

Inside a backbone view:

this.$('.myElement')

Inside an event

this.$('.myElement') or $(argument1.currentEvent).find('.myElement')

Inside a Model / Collection:

You shouldn’t, that’s the View’s responsibility

Code: Getting multiple specific Laravel models

I had a case where I had an array of model ids, and I wanted to return a collection of these models. That is I had a list of model ids, but it appeared no nice way to get all of them at once. However from the 4.2 API docs you can see that the find() should be able to return either a Model, or a Collection of models.

Find()

Naturally to get one model just use:
User::find( $id );
You could loop over the ::find() to pull each one manually, but that will result in multiple unnecessary queries to the database right? Who wants that?

Find() with Array

Here is a quite simple approach that Eloquent supports that seems quite obvious after you see it. You can just pass an array of model ids right to the find() function!

$arr = array($id1, $id2, $id3);
User::find( $arr );

This will return a collection of models just as you would expect, no fussing around with loops.  A simple way to get Multiple Specific Laravel Models by Id.

Utility: FTP Automation and Sync

I write code. I often find my self manually uploading every change to an ftp server using wither FileZilla or Windows Explorer native ftp browsing.  Keep the FTP in sync is tedious as you may know. Save file – Switch to ftp – upload – refresh browser. In the past I have searched for a simple answer for ftp automation but found nothing. Perhaps I didn’t search long enough, however I have an answer at long last!

Enter WinSCP

WinSCP FTP Automation

WinSCP has a built in “Keep remote directory up to date” function. It is brilliant let me tell you. You select the local folder and remote folder, tinker with settings (like if it should monitor subdirectories in addition), and away you go! Instantly as soon as you save the file it will upload any changes. FTP automation. What a time saver and frustration eliminator!

FTP Automation – It’s like magic!

There is very little latency for WinSCP to detect a changed file, perhaps a fraction of  a second at most! It is important to note, this automation is upload only, it doesn’t appear to support download sync as it doesn’t monitor the server side for changes. However, it does have a directory comparison tool and manual two way folder synchronization options in the main toolbar. But both of these are manual operations.

I recommending give it a try to see if WinSCP can help your workflow and save you time by eliminating the pains of manually uploading to an FTP server.

SyncFTP_Options

Overall I’m very pleased with this application, I think I may say farewell to FileZilla.

Download

Head over to WinSCP’s site for the latest downloads.

In addition WinSCP has some great scripting options with WinSCP.com. I have used it for automation / scheduled FTP transfers.  I will write more on that in the future.

Script: Unhide Network Drive Folders

There is an infection going around that hides all folders on a network drive and sets them as system folders. Here is a script I wrote that will remove the hidden and system attributes all folders/files in a directory you specify.
It uses the “attrib -h -s” and is not recursive into subdirectories.

For complete removal of the infection, naturally scan all machines. Remove any rouge autorun.ini files and rouge .exe files on the network drive.

Download: UnhideNetworkDriveFolders.v1.zip

I haven’t tested on all system setups and naturally comes with no warranty.

Update 3/22/2013

This script can only be run against a folder ( C:/Production/Shared ) not against an actual mapped drive ( S:/ ) at this time.

Update 3/27/2013

Here is a quick list of things to check regarding cleaning up the infection/worm.

  • Scan all PCs with Malwarebytes
    • Cleanup the the startup items
    • Cleanup and rouge exe files located
      • C:\User\%Username%
      • C:\User\%Username%\AppData
      • C:\User\%Username%\AppData\Roaming
    • Find proccess the infection is running under. Example:  jjhhgg.exe
  • Network drives, Flashdrives, External Harddrives
    • Delete all *.exe that mimic a folder and have a folders name
    • Delete autorun.inf
    • Delete x.mpg
    • Deltee anything else odd, rouge .exe files, photos files with .exe extentions
    • CMD Prompt, browse to the folder and run
      • attrib -h -s
      • Note this only unhides files, not folders.
    • CMD Prompt, browse to the folder and run
      • FOR /F "tokens=*" %i IN ('DIR /A:D /b') do attrib -h -s "%i"
      • Note this only unhides folders, make sure to have the quotation marks

 

Case Study: Unique Serial

I did some work repairing a gift certificate for NowStudio.co that a previous coder had created. The certificate is quite fantastic and keeps track of purchased certificates in a database. However, much of the code was written for PHP4 and had logic bugs that needed to cleaned up. A nice fun side project to work on.

The Problem.

The original coder used PHP’s rand() function to generate a number between 10,000,000 and 99,999,999 for the serial + the purchaser’s full name.

Not Unique. The obvious reasoning being that they didn’t want someone to be able to guess a certificate number and redeem a previously payed for certificate. Makes sense. However, there is a key flaw with creating serials this way. Random != Unique. There is the off chance, given time, that two certificates will be created with the same serial!

Using Names. The original coder recognized there was a chance a duplicate serial could be picked. They decided to use both the serial and the the buyer’s first and last name as the unique entries. Excellent idea and certainly seems to solve the problem. However, names tend to be unpredictable and unreliable. For instance, some last names are multi-part (Elfriede Von Kosh), have punctuation (Patrick O’Conner), or contain diacritic marks (Soňa Novak) among other things. This can cause unreliability with the app.

The question.

How can I create a better method of serializing the certificates?

Here are some requirements I came up with:

  • It has to be unique
  • Cannot be re-used
  • Non-continuous
  • Not guessable
  • Shouldn’t need to query the database to verify the serial hasn’t been used
  • Meaningful
  • Manageable in length

The Solution.

I decided simple solution is to use the full date/time + 4 random digits. For example this moment would be 2013-02-17 at 17:11:32 + 8345  or in string format  201302171711328345.

The Date. This serial has the benefit of telling us the exact moment it was generated. I use a 24-hour clock keep the length of the string always the same as well as to avoid the accidental repeated digit twice a day (9am and 9pm), that would be quite awkward. It would only increases the odds of getting a duplicated serial.

The +4 Digits. Using just the date and time down to the second I was still bugged that in theory two users could land on the page at the same moment and be served up the same serial. That’s why I felt the necessity to add the +4 random digits to the end of the string. While in theory it may be possible to still to generate duplicate serials, this makes it rather unlikely. During the save to the database we can always do a double check if we feel it is needed.

The Code.

For the landlubbers that want to use use this method of creating a serial, but don’t want to write it themselves – Here is what it looks like in PHP:

$serial=date("YmjGis").rand(1000,9999);

Too simple? Know a better solution? This only would work for small-medium sites.