Updated document.txt

rhgraysonii authored
revision 9f76e0a4d6405a7b60e2e580a0047d7bae122dd5
#A Fun Introduction to Meteor

Hey guys, just so you know I'm working on a rewrite of all the content you see here as we speak (sunday evening). If you start now, it will still be compatible. No worries. I'll cover it :) Happy Hacking


###UPDATE: Its definitely becoming and undertaking. I've decided to make this an entire "mini-book" and still plan on finishing it promptly, but covering setting up and adding routes, more models, and a basic way to share books will require some more heavy lifting. I really want to show off all the faces of Meteor's wonderful features. Hopefully no one is frustrated that has been reading this so far, I know I sent it out early with a promise of finishing quickly, but I don't want to put out something subpar or that will not inspire others. So, hopefully you aren't too upset with me :)

#A Fun Introduction to Meteor

*Shameless Plug: I'm currently looking for work as a developer anywhere in the US after finishing Epicodus, and working freelance with some great people in a small studio. If you would like to chat about anything (even just your strange fetish for Lisp), feel free to shoot me an email (bobbygrayson@gmail.com) or reach me on [Twitter](http://www.twitter.com/graysonrhii).*

#About Me, This, and Whatever:
My name is Bobby. I'm a hacker-type who recently attended the [Epicodus](http://www.epicodus.com) programming bootcamp, and have been programming in one way or another for the last 9 years. I'm a Rubyist by trade, but a generalist by hobby. I have found myself having far too much fun with Meteor; but also felt there was a lack in material on the "free content" level to get someone who intermediate programming skills from "beginner" to "understanding how to produce a real application" between what is available free online and the book [Discover Meteor](http://www.discovermeteor.com) (which might I say, is an amazing resource and worth every penny). You should also check the authors [Sasha](https://twitter.com/tmeasday) and [Matt's](https://twitter.com/tmeasday) respective Twitters. I am not affiliated with them in any way, but they made a truly great product and if this tutorial is of interest and you enjoy it, it would be a great step to take next. I have also shamelessly followed their methods of file structure, and am using what is essentially their design for the main UI of this app. Though this is 'lazy' I am more than willing to give those awesome guys credit, and since this is a tutorial about technical expertise and not design it seemed irrelevent to the larger picture to worry about hacking together my own.

The free tutorials found online now mostly go through semi-boring, obvious, or trivial applications of Meteor to show its base features. Chatrooms, live updating simple data, etc. are all the norm. I thought a virtual speed reading library of content one can save on their own is not a huge or crazy concept, but at least one that contains some interesting problems to approach and would be serviced well by a framework that can allow a very rapid prototype that is deployable, which Meteor is perfect for in this case.

#Notes for reading:
All command line input is considering your default location to be at "../yourAppName/". It will only properly create files and directories if you do this properly, obviously.

The Code May all be copy-pasted. This is supposed to be a handheld guide into realizing the possibilities of Meteor, and addressing many of the most important features in a fun way. If you are a programmer of at least low to minimum skill, this is a great starting point to jump in and get into building more complex applications quickly, and for a production environment.

In the first drafts I am concentrating on just getting the app done, and going into specifics later. Edits are welcome to integrate this concurrently in the text. Otherwise, I will do it later myself.

I plan on adding testing features later. Right now it is a dimension of Meteor I have not explored as much as I want.

#What is Meteor?
Meteor is a new(er) web framework. If one must put it simply, Meteor offers live data, all the time. Without digging into pull-and-diff, database theory, and other jargon, we can easily discern this: Meteor makes making live-data web applications simple. A chatroom can be implemented in fifteen minutes with a total of 3 files that are all very readable being used. For some ideas of examples, check out [Meteor's official examples](http://www.meteor.com/examples). At the time of writing Meteor is at 0.7.1 and I will update this to be compatible with all future releases, making a separate branch for each in case someone needs documentation referencing the project from an older state and has not upgraded.

#Why Meteor?
Meteor is a quick to pick up, simple to operate framework to rapidly build a simple prototype. It allows you to experiment, and is production capable! If you are interested in seeing this, check out these:




And even more at [Made With Meteor](http://madewith2.meteor.com/)

#What are we doing?
We are going to build a simple web application. It is nontrivial, but it shouldn't take more than an hour or so after some basic introduction if you know your JS. As mentioned before, we will be building our very own Speed Reader that allows us to copy and paste in content and save it as "books" to read at whatever speed we please. We will build it to be completely mobile and tablet compatible, that way we can even use it on the go, or in real life! A tutorial application with application in day to day life!? JIMMINY CRICKETS BATMAN THIS IS GREAT!

#Getting Started

###Launching the base application

If you have not installed Meteor yet, begin by going to the [Meteor Quick Start Guide](http://docs.meteor.com/#quickstart). If you run windows, I'm sorry. But, thankfully folks nicer than me have put together a getting started guide for you [here](http://www.addthelink.com). For reference, we will NOT be using meteorite for this outside of styling with bootstrap (which can be worked around easily without using the smart-package), so you can still do the rest of this tutorial though many others may not work if you need Meteorite integration.

Start with:

meteor create yourAppName
>command line input

if you are on Windows. However, from this point onward know that when you see use of "mrt" you should instead use "meteor". We are using Meteorite on the OSX/Linux side of things just to simplify adding bootstrap and going over package management and integration later. These will be asides you can ignore, due to the fact it will be later addressed.

If you are a user of an OS more pure, you should instead put in:

npm install meteorite
mrt create yourAppName
>command line input

Now that we have a directory, lets navigate to it and take a look at what we've gotten ourselves:

cd yourAppName
>yourAppName.html yourAppName.css yourAppName.js smart.json
>command line input

Did you get the appropriate output? WOO, we've got hello world. Navigate the browser to localhost:3000 and you will be able to check it out. See Hello World and a button? Great! Now, any sane developer will get some git going up in here, so let us do that.

*A note to Windows users: you will not have smart.json listed as referenced above. There will be no further differences until otherwise mentioned from this point onwards; so long as you remember our agreement about the use of meteor over mrt prior.*

git init
git add . -A
git commit -m "first commit"
>command line input

#Making A Plan

As said prior, we are going to be implementing a simple speed reader, similar to what is offered by [Spreeder](http://www.spreeder.com/). What do we need to do this? Well, let us consider the situation from an object-oriented perspective:

If we are going to display text rapidly, we probably don't want to just use a giant string. If we ever want to tie it to a user, and allow them to save the passages they have pasted in to read, we would then default to some kind of object. This object would also have to be able to iterate through all of its words, and somehow split them apart after the user gives their input. I have my own implementation I did with this, but the general idea is that I wanted to create a "Book" that could be saved, and a User can obviously then save as many books as they please. With Meteor, since we are using MongoDB, a NoSQL setup, we will not to worry about any relationships to be explicitly defined, such as "A user has many books, and a book belongs to a user".

#Getting to the Code
Here is the code I used for the reader. At this point it is placed in "yourAppName.js". However, later, we will add some structure to this file system as we add complexity and modify this a bit.

var Book = {
setBodyOfText: function(text) {
this.bodyOfText = text;
createWordChunks: function(numWords) {
var ourWords = this.bodyOfText.split(' ');
this.wordChunks = [];
for(var i = 0; i < ourWords.length; i+=numWords) {
this.wordChunks.push(ourWords.slice(i, i+numWords).join(' '));
setInterval: function(wordsPerMinute) {
this.interval = Math.round((60/wordsPerMinute) * 5 * 1000)
nextChunk: function() {
var nextChunk = this.wordChunks.shift();
return nextChunk;

Now, without going into a vast explanation, this combined with the function we are about to define below would allow one to implement this with user-inputted text on any static-page website using only jQuery. You can see an example of this [here](http://roberthgraysonii.site44.com/projects/newspeedread/index.html). Also, please note that though I wrote the code for that myself, the stop button does not work, and the words will display infinitely fast if you do not put in an initial input. These are problems that will obviously be solved in this setup. It is still useable, and even has a book statically loaded (*The Curse of Lono*, by the late and great Dr. Hunter S. Thompson). Anywho, please do not judge me, I would much prefer a [pull request](http://www.github.com/rhgraysonii/speedreaderjs) for this long forgotten project that I've not the time to work on right now.

Also, the main reasoning of this tutorial is to introduce Meteor principles, and not necessarily how to design a speed reader with OO in general. That is a fun topic we can discuss if you guys enjoy this, but not until later.

Here is the next function, however leave it commented out for the time being inside your *yourAppName.js* file:

.... //to designate the content you entered in the same file prior
//function stepThroughWords(reader) {
//window.setInterval(function() {
// $("div#text-display p").empty().append(reader.nextChunk());
//if (stop) {
// window.clearInterval();
//}, reader.interval);

This isn't the best practice, but I felt it to be most understandable from a code-readability standpoint introducing the models and functions here. Now, replace the default .html file with this:

Speed Reader


Lets commit the changes:

git add . -A
git commit -m "added reader and word-stepping javascript, set up formatting for the html document to display text in these ways
>command line input

Now lets take a dive into getting a way to save all that text!

#Meteor Collections
In Meteor, a collection is any entity you are labelling and throwing in the database. With MongoDB's simple syntax and NoSQL setup, it is quite easy. Let us being with them here. We need to create a collection for all of our "book" objects, as well as display them in the frontend UI in some way. Here is the order we will tackle these problems:

1. Implement a simple jQuery display that only works with sample data pre-inserted into the database
2. Add users and allow them to pick from one of multiple versions of these presets
3. Let users paste in their own books and have them saved in a collection
4. (Our bonus exercise): Load each book live without going to a different route

Now, since we have outlined this plan, let's start by preparing to display items for a collection before we make one! Meteor's templating engine is known as [Handlebars](http://www.handlebarsjs.com/). Here is what we will define in *booksList.html*, the file you will now create:

touch booksList.html

And now, open her up and put in this code:


This gives us a nice little list of each of our books. In this case, we still haven't defined a book. But, all we have to do is create this over on the JS side. First, however, lets define our books in another template.

touch bookTitle.html

And here is our next template-buddy!


This templating may be very self-explanatory if you are familiar with programming in general, or have played with similar libraries. However, if it does not make sense check out the link above to their main page for further guidance. They are a great resource.

Now, our file structure is just getting messy here. We need a solid architecture. Currently, this is what we have jarbled together:








Meteor contains a nifty feature in which if you have the architecture of:







You get to reap some benefit if you follow this pattern. Files in lib are loaded before anything else. Files in server will only run on the server. Files in client will only run on the side of the client. Your static content will go in public.

Now, lets restructure our application to follow this pattern:

mkdir lib
mkdir server
mkdir client
mkdir public
mkdir collections
>command line input

Now, either using the command line or your file navigation program of choice, move the *bookTitle.html* and *booksList.html* files into client. Right now, we don't have explicitly mapped enough of JS to distribute it until we implement into collections soon. So, this will do us fine for now. Our next step is going to be restructuring the three files we began with when generating the project and spreading them out a bit.

*A note on this: I am shamelessly stealing the structure used in [Discover Meteor](http://www.discovermeteor.com). I did not come up with this setup, but I find it to work quite wonderfully and to be of production quality, so I figured it was the way to go*

Heres how we start!

Since we have changed our file structure in a reasonably large way, but have not radically changed too much functionality, lets do another commit.

git add . -A
git commit -m "re-arrange file structure and add templates to display books"
>command line input

*A note on the use of -A in this commit: It is normally not necessary, because it tracks all file deletions, but in this case it would be integral to our new structure. One must not always use it, but I choose to. *

Now, to get into how to manage all of these templates. Lets begin by just throwing in one filler 'book' for any user to access if they feel the need to try out this application quickly and not have to copy-paste anything.

// //you can name this file whatever you please, but as the convention
// //was utilized in Discover Meteor, I will name managers after their
// //respective templates

// var booksList = [
// {
// title: 'A Tale of Two Cities',
// text: 'This is a story about a guy named al, and he lived in the sewer with his hamster pal. Though he worked in the city he worked in a tree and worked in a basal ganglia factory and played for the companies bowling dreams and every single night ate pennies and sour cream, but thats really not important to the story. He one day packed up his keys and got on his knees to go kill some bees that lived in trees'
// },
// ];

// Template.booksList.helpers({
// books: bookFiller
// });

This is a bit of a workaround, as mentioned prior. It will automatically give this bit of filler, but we still want to actually save our own. So, lets move on to defining the collection we have been lauding oh-so-long. Don't worry about everything being commented out. No big deal. We just will be doing some more different things in a moment and for now it allows the app to run without crashing.

cd collections
touch books.js
>command line input

Defining a collection is quite simple:

books = new Meteor.Collection('books');

*A note on the lack of use of the 'var' keyword here: if var is used, the scope of this object will be purely local. Since we want it in our whole application, we do not use the var keyword here*

And, another commit.

git add . -A
git commit -m "Add books collection and filler data to display on default"
>command line input

Now, we have a collection, but we need to add a way to throw some data into it!

#Getting Some Users Up In Your Shindig

We need users to have data. We don't just want anyone to come along and decide that they should mass-insert a ton of data into our setup. So, if we create a User we can make one have to register before they can do this, and limit their submissions later in another way if volume were to get too heavy. Meteor makes this the most painless process imagineable.

####An Aside to Save Us Some Time
We will be using Meteorite packages for our user setup. In regards to this, one of the packages we use (for viewing a user) has a version with Bootstrap stylings already set up. Let's import bootstrap and the related package real quick.

mrt add bootstrap
mrt add accounts-ui-bootstrap-dropdown
>command line input

##Back to the User Party

Now, we have successfully added the packages that allow for the display of the user input, but the puzzle isn't quite complete. We nee password support!

mrt add accounts-password
>command line input

With this, we now need to go back into our HTML and put in the buttons. We have been allotted some wonderful templates to help us with this using handlebars, primarily {{loginButtons}}. With this, lets go back to our HTML and give it some Bootstrap love so we can see this entire system going. We will also add in whatever is needed for us to be able to display our demo book's name, even though we are far from equipped to actually read it yet. Also, lets rename "yourAppName.html" to "main.html" and move it into the /client directory. Things named main.whatever will load first in Meteor.


#Your Subscribed Me to What!?

Publications and Subscriptions are a core functionality of Meteor. After all, what better way to transmit live data? In Meteor these relationships are very easily defined.

By default, in development when you make a project with "meteor create" or "mrt create" you end up with autopublish, a package included with meteor, enabled. This automatically mirrors all data from the server to the client, which is useful for us when using this filler to get our template to display properly. However, we will want to remove it later.

##If you have reached the end and this is still not done, that is because I am working on it actively right now in my own little hackathon. At the current moment (21:20 EST) this is being typed and this is the future plan:

###Displaying a 'Book' with jQuery

###Make 'er Pretty With Bootstrap

###Implement Simple Submission of 'Books'

###Adding Users (Linux/OSX Only)

###Let Users Save 'Books' Only They Can See (Linux/OSX only)

###Advanced Maybe Later Project: add a web scraper to yoink books from place listing them on the public domain (I know this is a grey hat area with many places terms of use. It would be purely educational.)

I hope to have it finished by tomorrow afternoon. I may or may not sleep tonight.