Posts by Michael Murphy

An Introduction to Vue.js Components

Components are great for those of us looking to harness the true power of Vue.js. If used correctly we can have clean, reusable code, which is what every developer really wants, right?

What is A Component:

The concept of components is not unique to Vue.js. You can find them referenced in many other javascript frameworks. In fact there is a term for this style of programming called component-based development, which is described as:

… a branch of software engineering that emphasizes the separation of concerns with respect to the wide-ranging functionality available throughout a given software system. It is a reuse-based approach to defining, implementing and composing loosely coupled independent components into systems.

In it’s simplest terms, you can compare components to Lego blocks. These blocks contain smaller pieces of code that handle specific features. If there’s one thing you can take away from this post, it’s that components make your code Readable, Reusable, and Reliable.

The Vue Component

A Vue component is just a Vue instance that is assigned to a custom tag-name and renders content in the template. For example, let’s create a simple component that displays a username.

The first argument in the component function is the tag-name my-user-greeting. When we want to use this component, we just add <my-user-greeting></my-user-greeting> to the template and it will render the code found in the second argument. It’s good practice to give a unique name to your tag. This prevents any tag conflicts from other components or packages installed on your application.

The second argument is the actual object that represents our component. It may look very similar to the object that we pass into the Vue Instance, but the data option is no longer an object but a function. This is because we want the data represented in the component to be specific to said component. We don’t want data that changes in our component to have side-effects changing data in other components.

This object accepts all options and lifecycle hooks that a normal Vue instance would accept, with the exception of el, which is not needed since our main Vue instance is already mounted to an element.

The Template Option:

In the above example you’ll see the template option. This option only accepts a string value, and is the markup for what you intend to render with the component. In our example, we are rendering a simple user greeting wrapped in <p> tags.

This option is pretty limited as we can only use a string. Sure we can pass data properties using text interpolation, but if we wanted to add nested HTML elements, this approach becomes cumbersome. Vue.js allows for single file components which will work great for medium to large projects, and my personal preference, but since this is just an introduction, I’ll save that concept for a future post.

Global vs Local Components:

Many of the applications you build with Vue will span over multiple directories and files. If you build a component with the intention to use it anywhere and everywhere, then defining it once will keep your code clean and easy to refactor.

In the first example, we define our component using Vue.component(), this makes the component available to be used globally throughout your app. Because this component is global, we can add <my-user_greeting></my-user-greeting> to any template in our app and the greeting will be rendered.

As you might expect, a local component is scoped only to the template it is referenced in. Let’s take a look at just one way to define a local component.

In the example we are working directly in a Vue instance and using another available option; components. This accepts an object which can have many components. The key in the object is the tag-name you wish to assign to your component. Then we pass an object which holds the template and data. In this case we just set the object to a variable outside the Vue instance.

Now <my-cmp></my-cmp> is available to be referenced, but only in the template which it is defined in. We could not use this component in other templates because it is out of scope.

Wrapping Up

Components offers us a a way to take complex code and simplify it down into organized, easy to read code. Hopefully this dumbs-down the concept of components. The first time I heard about them I felt slightly anxious and overwhelmed. But coming from a Rails background, they were easy to relate to partials. With a little practice, Vue components will begin to take form within your Vue applications, and you’ll never look back!

Learning Vue.js?
Want to follow along with my learning path? Check here for more posts about Vue!
(Visited 44 times, 1 visits today)

Interacting with the Vue Instance

So you’ve dabbled a bit with Vue.js, and you keep hearing about the Vue Instance. Sure, it allows us to interact with Vue.js on our page, but how?

Initializing The Vue Instance

Whether you add Vue.js using the CDN or the CLI tool, you still need to initialize the Vue instance in some way. By initializing this instance, you are then able to start interacting with Vue.js’ core library.

Clearly there’s not much going on in our instance at the moment. new Vue({}) is just our starting point. Below you’ll find some basic options that the Vue instance accepts.

Common Vue Instance Options

el:

In order for our Vue instance to be accessible in our view, we need to first mount it to an existing DOM element. For single page applications (SPAs) this will likely be the element id  attribute that directly follows the body tag.

It’s important to note that the value for el is a plain string, and we do not need to attach the HTML id symbol, #, to the string. Vue.js already expects this value to be an id.

Vue.js takes this element and it’s containing HTML and regenerates the DOM into a Vue template. Since the generation of the DOM occurs only once when the page loads, the only time el is needed as an option is when we initialize a new Vue instance.

data:

One of the benefits to using a Javascript framework like Vue.js is the ability to to make the DOM reactive, and one of the simplest ways to dynamically render data on your page, is to add a data object to the Vue instance. Below is an example of how you would set up your data properties:

The above example is a basic javascript object which contains three properties: namelocation, and interests.  These data properties are now available to be used within our Vue template generated by the el option.

Take a look at the template example below, we can now bind these data properties to our page using text interpolation; using the mustache syntax {{ }}.

Useful side notes when using data:

  • Vue will convert data properties into getters and setters. This allows the page to be reactive.
  • Once the instance initializes, you can no longer add reactive data to the instance this way. There are other ways to add new data with Vue.js, but not using this method.
  • Vue.js proxies all properties found in the data object, so you can reference properties within the instance using this.location. This is helpful in the following options.

methods:

Methods are event driven functions. Say we have a button on our page, which when clicked, changes our location property to San Fransisco. Our template may look like this:

@click= may look new to you, but it’s Vue.js’ way of saying: “When this element is clicked, run this method”. So changeLocation is the name of our method, and we can now define it within our instance.

As mentioned in the data section, since Vue.js proxies all our data properties, we have them available to use in other areas of our instance. In this case we can use this within the Vue instance and we can then reference our data property location. We reset the value, which will then bind to our template.

An important note is that Vue.js is not smart enough to know if it needs to re-run a method if the data dependencies do not change. If location is already set to “San Fransisco” and your method’s task is to change location to “San Fransisco”, the method will run every time.

computed:

Computed properties work just like methods, however they are cached and only re-computed when a dependency changes. These functions are smart, unlike methods, when it comes to knowing if it needs to run or not when the DOM updates.

Computed functions also don’t need to include the parentheses when called in the template.

An important note with computed functions is that they can only run synchronously. If you want to make asynchronous calls out to an API, you can use methods or the watch option.

watch:

Just as the name suggests, this option accepts properties that align with data properties. When a data property changes, you can add a callback function to run. This function is independent from a method or computed function. For instance, if name changes, we can run other functions.

As mentioned above, watch functions are GREAT for asynchronous calls!

By default watch functions automatically pass a value argument, which is the current value of the data property. You can reference this within your function like so:

Other Useful Vue.js Instance Options:

Below you’ll find a few more helpful options. You can find a longer list of options on the Vue API docs here.

props:

Since this post does not cover components, I wont go into too much detail about props, but this option is an array or object which contains data from a parent component to be used in the child component. As well as the properties being passed, you can specify the data types, validators, and required options.

 

Lifecycle Hook:

In addition to all the options mentioned so far, there are special options that execute during the life of the Vue instance. These hooks fire just as their names suggest so no need to go into individual details. These lifecycle hooks are:

  • beforeCreate
  • created
  • beforeMount
  • mounted
  • beforeUpdate
  • updated
  • activated
  • deactivated
  • beforeDestroy
  • destroyed
  • errorCaptured

So with those stated, here is just a small example how you might want to use these Vue Instance lifecycle hooks:

Wrapping Up with The Vue Instance:

We’ve only covered the tip of the iceberg when it comes to the Vue instance function and it’s available options. With the introduction of components that list of options grows tenfold! However, Vue.js is such a welcoming framework that you could build simple single page apps with just the options mentioned above!

Learning Vue.js, and want to follow along with my learning path? Check here for more posts about Vue!

(Visited 23 times, 1 visits today)

Partials Should Never Contain Instance Variables

It may seem that the benefits of partials in our Rails application are endless. They help keep our views DRY, organized, and easily reusable. But with great power comes great responsibility.

Due to the flexibility partials give us, controlling the data flow to partials should not be an oversight. Let’s say we’re using one partial in two separate views which will render a message on the page:

Since @message in used in the partial, we must define the variable in both the Dashboard and Photo controllers. If we want to change @message to another name in one of our controller actions, then all other instances of @message must be renamed as well. For this reason, our partial becomes difficult to reuse and manage.

To combat against an issue like this we can use local variables:

You’ll notice just after the file name, we are adding an additional option which is our local variable. We can now set message to whatever we want, and then use the message local variable within our partial.

This method now allows us to use the partial freely across all our views without the worry of having to trace our variables back to multiple controllers.

For situations where you may have more than one local that needs to be passed along to a partial, just use the locals hash locals: { }.

So next time you find yourself working with partials, remember, a good practice when passing data to your partials is to use locals over instance variables.

For more best practices about rendering partials, the Layouts and Rendering section in Rails Guides is a great starting point.

(Visited 9 times, 1 visits today)

How I fixed SQL Server WMI Service Error

Recently I switched my database over to SQL Server, which led me to use Microsoft’s SQL Server Management Studio. During the installation process I ran into a WMI Service Error; something I never faced before. This is how I fixed this error and continued on with the SQL Server setup installation.

So assuming you Google searched your way over to here, I’m guessing you have a Windows Management Instrumentation (WMI) service failed error. If you do great, you may have come to the right place.

(Disclaimer: Try these steps at your own risk. What worked for me, might not work for you. I solved my issue with a series of tutorials that may or may not have contributed to this fix. I’m also not a computer genius, half of the time I had no idea what would happen. All I know is that these steps eventually worked. So proceed with this in mind.)  

WMI Service Error… you suck!

During the ‘Global Rules’ stage of your setup, you notice that your Windows Management Instrumentation (WMI) service has failed and you cannot continue until the the failure is corrected.

Windows Management Instrumentation (WMI) service Failed / WMI Service Error

What does this mean? Well, it can be caused from one or more issues on your local computer (corrupted files, an incomplete install or uninstall of a program, improper deletion of hardware, etc.).

By clicking on the ‘Failed’ link we can see detailed information. This message doesn’t give us any surprising information.

Rule "Windows Management Instrumentation (WMI) service" Failed / WMI Service Error

After a quick Google search, I managed to locate where to find the WMI service on my local computer. Here is the full path starting from the Control Pannel:

Control Pannel > System and Security > Administrative Tools > Services > scroll down to Windows Management Instrumentation

Once I located the WMI service, I noticed that the status was set to Running…

Windows Management Instrumentation (WMI) service / WMI Service Error

I found this to be strange since it appears to be running just fine. So why am I getting a WMI Service Error?

I checked the properties by double clicking (or right-click > properties) and checked the Dependencies tab…

Windows Management Instrumentation (WMI) service Properties Dependencies / WMI Service Error

Well there’s our problem. A propertly working WMI should look like this.
(Note: If your error box says “WMI: Initialization failure” take a look at this quick fix tutorial)

With a quick Google search, I came across a Microsoft blog post about rebuilding the WMI repository.

The first action they recommend to do is “Re-register all of the dlls and recompile the .mofs in the wbem folder and re-registering WMI Service and Provider”. (Whatever that means…sure, I’ll give it a try) To do this we first must create a batch file to run in the admin command prompt.

Copy the following script and paste it into notepad. Then save the file in a familiar location with the name WMI-repo-register.bat . Make sure when you save the file, you select ‘All Files’ in the ‘Save as type’ select dropdown.

@echo off
sc config winmgmt start= disabled
net stop winmgmt /y
%systemdrive%
cd %windir%\system32\wbem
for /f %%s in (‘dir /b *.dll’) do regsvr32 /s %%s
wmiprvse /regserver
winmgmt /regserver
sc config winmgmt start= auto
net start winmgmt
for /f %%s in (‘dir /s /b *.mof *.mfl’) do mofcomp %%s

Now open your command prompt (as admin) and CD to the following path; C:\Windows\System32\Wbem (chances are you’re already there when you start up CMD). Now run the file you just created in the command prompt.

Once the script completes, restart your computer and run winmgmt /verifyrepository in your command prompt. This will check the repository for consistencies.

WMI repository verification failed 0x80041002 WMI Not Found / WMI Service Error

If you get a more successful response than the one above, try running the SQL Server installation/setup again and see if the ‘Global Rules’ step passes. If you got the same response I got, continue on with the tutorial.

Next I tried resetting the WMI repository by running Winmgmt /resetrepository in the command prompt.

WMI repository reset failed 0x8007041B / WMI Service Error

Great another error… Something is blocking me from running the command. Thanks to a blog post by Robin at Fixing Things, there is a way to force a reset repository command.

Open up Windows Powershell as an admin and type the following in the command line…

Stop-Service winmgmt -Force; winmgmt /resetrepository

After the command completes, reboot your computer.

I then ran the SQL Server installation/setup and WMI services finally passed! (Forgot to take a screenshot during my excitement)

If you run into any other issues later on in the installation, (most likely in the Feature Rules) read the error and download whatever you may be missing. In my case, I was missing Microsoft .NET Framework 3.5 Service Pack 1…. so I just downloaded the pack right from Microsoft and was allowed to proceed.

Rule "Microsoft .NET Framework 3.5 Service Pack 1 is required" failed / WMI Service Error

 

I hope this tutorial helps you solve your Windows Management Instrumentation (WMI) service error. If you ran into a similar issue and found a different solution that worked for you, please post a link or suggestion in the comments below.

Thanks for reading!

(Visited 2,105 times, 1 visits today)

Year To Code…2015 Coding Goals

It was just over 6 months ago when I wrote my first functional ruby program. Sure, it was a simple question/response program, but I was exhilarated with what I created. Fast forward to now and I’m proud to be employed as a full-time software developer at a company I love working at.

The journey to reach this point was no cake walk, but by setting short term target specific goals I was able to persevere without being bogged down from the pressure of reaching my main goal; landing a software developer position.

Since this is my first January 1st as a developer, I wanted to set a few goals for myself to accomplish throughout the year. To some, if not most of you, this list may already be part of your routine, if not then you’re welcome you to recycle some of these aspirations as part of your own for 2015.

Attend more networking events

During the first 3 months of coding I was pretty active when it came to showing up to events within the programming community. Then a month after graduating my bootcamp and landing a job, I stopped going to events. To put it simply…I got lazy.

In 2015 I want to attend at least two meet ups a month. Boston has a great Ruby community, The Boston Ruby Group, and using Meetup.com to find an event that fits your schedule makes it that much more convenient.

Participate in a hackathon

Looking back over the past 6 months I can recall multiple instances where impostor syndrome got the best of me. I can now laugh at most of the things that cut my confidence in half, realizing how ridiculous my concerns and doubts once were.

The thought of participating in a hackathon where experienced developers are depending on my rookie code is slightly intimidating. Being a competitive person myself, I can understand why a more senior hack team would *sigh* to have me on their team. However, I’m hoping to surprise myself along with my future teams and rise to the occasion.

Work on more passion projects

The last three weeks of my bootcamp I dedicated 8 hours a day on my passion project. The same feeling of accomplishment from the simple Ruby program came back those last few weeks. To me, taking an idea and turning it into a functional program still seems like magic, but now I’m the magician.

Right now, I have two passion projects I want to work on. I’ve procrastinated far too long on potential projects that those past ideas have faded into nothing. This year my goal is to start working on a project as soon an idea comes to mind and devote more of my free time to progress them.

Take a codecation

One of my mentors; Ben Orenstein wrote a post about why a developer should consider taking a codecation. For the lazy… A codecation is a time where you travel with a couple code buddies and spend a majority of time coding on a collective passion project.

This concept of working on vacation seemed a little weird to me at first, but after some consideration, I realized it’s a great opportunity to learn and work collectively with familiar faces.

puala


 

Wrapping Up…

If you have a couple goals you wish to accomplish over the course of the year I encourage you to try writing them down or creating a similar blog post. For those of you like me who make a bunch of new years resolutions at the start of the year, only to last a month before falling back on to old habits, let your blog post be your training partner who is there to motivate you when you feel like giving up.

To all of you who read this far down… Happy New Year and make 2015 your best year yet!

(Visited 8 times, 1 visits today)

Magical Values

When writing code ALWAYS be aware of magic numbers.

You attend a magic show and for the magician’s last trick he performs the old ‘rabbit out of hat’ stunt. As you sit in your seat, you witness the magician actually pull a live rabbit out of the hat he’s been wearing all night! You are stunned, but more so confused where that furry little creature came from in the first place.

Reading poorly written code can often time’s feel like you’re trying to figure out a magic trick. In this post we will cover a strategy that will combat against magical values.

So let’s talk about what magic values are. In its simplest term, a magic value is a value that is directly used within your code that has no context of where it came from.

Take a look at the example below. Can you spot a line that could possibly raise a red flag?

The area we are concerned about is within the conditional. More specifically the integer 5 is our example of a magic value.

Although this chunk of code will work, it’s not the way experienced developers write code.

The developer who wrote the lines in the example will understand it perfectly today and maybe even tomorrow, but what if he/she comes back a year from now to refactor their code? Will he/she be able to remember what 5 means? Better yet, let’s think about other developers who may be working on this chunk of code today. They may have no idea what this integer 5 is trying to perform.

Now I understand that this example is very basic, but we want to get in the habit of writing code in a way that it can speak for itself. That way everyone including yourself stays informed and happy.

Let’s take a moment and refactor our conditional in a way that we can eliminate our magic number.

As you can see in the example above, we extracted the integer 5, and set it to a constant variable outside of the method. Now we can use this constant multiple times within the class, just by calling the constant variable’s name. This is great practice because if we wanted to change the minimum username length to 6, we only have to change one bit of code instead of multiple bits in multiple locations.

The naming of the constant variable is key. A properly named variable will give us information about what the value is trying to accomplish. After all, what’s the point of extracting the magic value if our variable is poorly named?

Here is another example of a magic values, but this time we see both integers and strings:

What does (1..12) and (“a”..”z”) mean? In the example above we do not have the slightest clue. But when we refactor our class, and get rid of the magic values the code instantly becomes more clear:


Take away points:

  • Never write code with non-descriptive values
  • When defining what a value is, set it to a constant variable
  • Make sure your constant variables are properly named
  • Always look for ways to improve readability for yourself and others

 

(Visited 5 times, 1 visits today)