Max Miller

Month

June 2013

1 post

GA Apprenticeship: Week Four

This week was a bit slow starting — I blame Reunions — but once I got going, it was really productive. I spent most of the first day thinking about the architecture for a new project that I will be working on together with Rob Gleeson, a remote dev (Irish, but living in Amsterdam). Should be interesting to build something with someone thousands of miles away. The gist of the project is this: the Sales team wants to be able to separate leads from people who are interested in a course and those who have actually applied, which will also include migrating the whole application process from Wufoo to our own website. 

There are two distinct chunks to this project. The first, and easier of the two, is to automatically send emails to people who request more information about a course, thereby freeing up the sales team’s time to pursue more important leads. As far as I can tell, this will require simply creating a new “request info” mailer and updated the Lead Observer to generate this mailer anytime a lead is created from this particular source.

The more complicated piece of this project will be to create a course application flow on Core rather than just linking to Wufoo. Some initial thoughts: (1) beginning an application will generate a new lead, so we need to figure out whether to create duplicate leads if a user already exists as a lead or whether to override the existing; (2) perhaps there should be a single-page summary for completed forms for GA producers to access; (3) we’ll need to create an Application model (or maybe something with a less confusing name) with fields for user, course, completed, instance (maybe), url (maybe), as well as a serialized field for all other data from the forms; (4) how do we deal with the views, which will be different for every application?; (5) do we save the input from each page of the form, and if so, how do change the “completed” attribute to true? I’m sure we’ll start to address these issues when we get started on this project. 

Also, from talking with Derek and Dave, I’ve realized that there is a real need for devs with Javascript skills here at GA, so I’ve decided to focus on that over the next two months to make myself a compelling hire at the end of this apprenticeship. Backbone, Jasmine, and jQuery are on the top of my list of things to master. 

Jun 7, 2013
#GA #apprenticeship

May 2013

4 posts

GA Apprenticeship: Week Three

The lesson of the week is this: things usually take longer than expected. Last Thursday I thought I was almost done with building the program index  pages for GA’s core site, pages that will display all the programs for a given topic and metro as well as upcoming instances of those programs if they exist and featured classes/workshops. Now, exactly a week later, the pages are finally completed—my first shippable feature!

The reasons for the delay were varied. First, I ran into some problems when I merged back in the develop branch, because I initially branched off a while ago and didn’t realize I needed to continually update my local develop branch. The QA process also took a while, as several times my PM Katie requested changes to the functionality—the takeaway here being that it’s better to ask questions up front rather than later. One of the requested features, in particular, looked innocuous (simply adding a link to the bottom of a page), but it ended up taking about 5 hours because it required me to learn Backbone and pair with my mentor Derek. But in the end, I completed the feature, with a not insignificant amount of help from my other team members. Booya. Next monday I will start on a new project, probably something JS heavy, this time in tandem with another engineer.

Speaking of Backbone, that’s my next big project. I’ve started going through Code School’s “Anatomy of Backbone.js” course, and I’m planning on diving deeper next week after I get back from my 5th (!) Princeton reunion on Sunday. Go tigers!

May 31, 2013
#backbone.js #GA #apprenticeship
GA Apprenticeship: Week Two

Aside from some minor PostgresQL issues mid-week, Week 2 has been great. I (mostly) completed my first solo project—building an index page for GA programs per each topic.

1. ActiveRecord: Based in part on my recent database horror stories, I’ve decided to dive a bit more into how databases work and how Postgres in particular works, and how ActiveRecord allows you to easily interact with the database from a Rails app. Aside from the most common ones like first, last, all, etc., below are some of the most common ActiveRecord methods.

  • Find — the most basic method of retrieving an object based on its primary key. You can also use an array of primary keys to find multiple objects. Even more awesome, you can use a dynamic finder to search items by attributes other than their primary key. For instance: Person.find_by_first_name(“John”) OR Person.find_by_first_name_and_last_name(“John”, “Doe”) OR Person.find_all_by_first_name_and_last_name(“John”, “Doe”) OR Person.find_or_create_by_first_name “Lindsey”
  • Where — allows you to specify conditions that will limit which records are returned, without querying the whole database. There are several syntaxes you can use: Array: Client.where(“orders_count = ?”, params[:orders]) OR Client.where(“orders_count = ? AND locked = ?”, params[:orders], false) OR Client.where(“created_at >= :start_date AND created_at <= :end_date”, {start_date: params[:start_date], end_date: params[:end_date] } ). Range: Client.where( created_at: (params[:start_date].to_date) . . (params[:end_date].to_date) ). Hash: Client.where( locked: true) OR Client.where( ‘locked’ => true) OR Client.where( orders_count: [1,3,5] )
  • Order — pretty self explanatory, this method defaults to ascending. Client.order(“created_at”) is the same as Client.order(“created_at ASC”). You can also order by multiple fields: Client.order(“orders_count ASC, created_at DESC”)
  • Select — Unlike the above methods which return the entire item object, the select method returns only the attributes you specify: Person.select(:first_name).first OR Person.select(“last_name, age”).find_by_first_name(“Max”). You can use this method to select only unique values: Client.select(:name).uniq
  • Limit — Returns a specified number of items. Client.limit(5) will automatically grab the first 5 from the table. Client.limit(5).offset(30) will grab 5 items starting with the 31st. 
  • Joins — Executes an Inner Join on multiple table that share a common table attribute (i.e. a primary key/foreign key pair; in other words, two table that have an association): Category.joins(:posts). For more on SQL Joins, this article.
  • Explain — Chain this method to the end of any relation query and it will yield a graphic explanation of the SQL query that you are trying to run.
  • Scopes — Allows you to specify commonly used ActiveRecord queries as method calls on your association objects or models. These scopes are defined in a Model class and can be constructed with any of the above methods.Method Chaining — scope :published, where( published: true ).joins(:category). Working with times — scope :last_week, lambda { where(“created_at < ?”, Time.zone.now ) }. Passing in arguments — scope :last_week, lambda { |time| where(“created_at < ?”, time ) }
  • Calcuations: Count, Average, Minimum, Maximum, Sum

N.B. It is important to note that these above methods return an instance of ActiveRecord::Relation. A further method such as .all or .first must be used to execute the relation.

2. New methods:

  • gsub — substitutes a character or characters from a String with other characters: “hello”.gsub( /[aeiou]/, ‘*’ )  OR “hello”.gsub( /[eo]/, ‘e’ => 3, ‘o’ => ‘*’ )
  • collect vs map — these methods are exactly the same: [ “a”, “b”, “c”, “d” ].map { |x| x + “!” } #=> [“a!”, “b!”, “c!”, “d!”]

3. New gems:

  • HTTParty — allows you to make really easy API calls for API’s that don’t have gems available. Read more here.
  • JSON — converts strings into json or parse JSON into a Ruby object
  • Nokogiri — an amazing gem that lets you scrape HTML into your Rails project (God I wish I had this for my bookmarklet!). Read more here.
  • Twilio — allows you to make and receive phone calls and send and receive text message from an application.
May 29, 2013
#postgresql #ga #apprenticeship #rubygems
GA Apprenticeship: Week One

Week one down — eleven more to go! This week has been a bit of a whirlwind, but super exciting. Wrapping my head around all of GA’s existing and upcoming products and code base has been daunting, but I’ve been able to jump into a handful of projects by pair programming with Tim Dussinger and Dustin Coates, two former apprentices. I’ve learned so much already, and I’ve broken it all down into four major areas:

1) Testing: One of my main goals during this apprenticeship was to learn TDD, and I’ve gotten a great start this week writing tests during pair programming. I had previously held off from getting started with tests until this point because I hadn’t known what to test for, but now I’m starting to get the hang of it. Basically a test should do 4 things: (1) Set up the data needed for the test, often from a pre-created “Fixture”; (2) Perform the action that triggers the behavior being tested; (3) Perform one or more “assertions” to prove that the behavior triggered in the previous step had the desired results; (4) Tear down any data structures that need to be removed before the next tests are run (although this is often done for us in Rails). Tests are usually broken into a couple categories: functional, for controllers; unit, for models; integration and performance test, which are evidently not used often; and cukes, for acceptance tests, powered by Cucumber. Speaking of which, Cucumber, Factory Girl, RSpec, and Capybara are all gems for testing that I’m going to learn more about; I’ll write a more in-depth post about them later on.  

2) Git/Deployment: For the past 6 months since I’ve known what Git is, it’s been a bit of a magical, nebulous question mark in my mind. I know what it is and how it’s used, but not really how it works beyond basic commits on a single machine. Also I had no idea how it worked in practice with a team of developers. I read a great article about Git Flow, which is a paradigm for dev teams to manage software development. The basic premise is that a software code is distributed into a handful of different folders that are like separate branches, including master, develop, feature branches, release branches, and hotfixes. The master branch is where live, production code is stored. Changes are never made to this master branch; instead, code is forked off from this branch into the develop branch. Anytime a new feature needs to be created, a new feature branch is forked off of the develop branch. You are then free to work on these feature branches without any worry that your changes will conflict with other changes that might be happening at the same time. Once the feature is complete, you can fetch and merge the develop branch again into this feature branch, in order to resolve any discrepancies before you merge back into the main branch. Then you initiate a pull request, which asks someone in charge of the develop branch to integrate your feature back into the develop branch. This can happen as many times as there are new features for a given release, then the code is pushed to a release branch, where final testing is done. When it’s deemed complete, the release is deployed to the master branch.  

3) Rails Stack Infrastructure: Derek explained to me how a Rails stack (or at least our Rails stack) works. Because we have multiple servers through AWS (Amazon Web Services), there needs to a be a mechanism that spreads out requests among the servers, so that a single server does not get overloaded. Here’s how this works: DNS routes a request to something called a “load balancer,” which is responsible for doing exactly what it says — balancing the load of requests amongst a distributed networks of servers. From here, the request is sent to an Amazon EC2 (Elastic Compute Cloud) box, which is a virtual machine running our software, and intercepted by Nginx, an open source web server/reverse proxy server for HTTP, IMAP, SMTP, and POP3 protocols, (replacing Apache). Nginx determines whether it can render up a static file or whether it needs to send the request to Unicorn (a Ruby gem), which allows a Rails server to run multiple processes (i.e. requests) at the same time. Unicorn allocates space on the CPU, so that the maximum number of processes can be run on a single CPU, determined by how much memory the CPU has. Once the request is handled, it is send back to client. 

4) Coding Tools: One of the great things about working with REAL LIFE DEVS has been observing their native environments — their coding environments, that is. Here are some of the cool tricks I’ve learned in the past week. First, I learned about installing packages for Sublime Text, including Git, GitGutter, SidebarEnhancements, Emmet, Plain Tasks, and others that enhance the text editor experience. You do this by opening the Command Palette (CMD + SHIFT + P) and then Install Packages, and then searching for whatever package you want to install. Pry is another great gem I learned about — it lets you insert “binding.pry” at any point in your code, and when you run that code, it creates a break point, and will automatically open up the console so that you can test what data exists at any point in the execution of your code. This is like what I was doing with RubyMine, but without a clunky IDE. Another thing I want to do is upgrade from Terminal to iTerm because you can customize it with zShell, but I haven’t figured out how to do that just yet.

More to come soon…

May 17, 2013
#GA #apprenticeship #git #tdd
My Life as an Engineer, Day Zero

Today is a very exciting day. Eight months after shutting down LIFTLUXE, six months after blindly diving into the new world of coding, and four months after completing my Rails course at General Assembly, I have my first real coding job as software engineering apprentice at GA. I really couldn’t be more excited. It’s been a crazy ride — from the basement of Starbucks to airy 61 local, from GA classrooms to Hearst hackathons — and I’m so pumped to be able to work with an awesome dev team from here on out, and given its existing dev team and focus on pair programming, I know that GA is the best fit for me right now for developing as an engineer. 

The main thing that I hope to discover during the coming 3 months is this: do I want to be a great engineer, to pursue excellence in building software and do that for the rest of my career, or do I want to spend several years getting to be highly proficient at coding and then leverage these new skills in conjunction with my prior entrepreneurial ambitions. This is honestly a question that I can’t answer at the moment—though my gut is actually pushing me towards the former. Either way, in the short term, as I figure out this question, I will go forward with the goal of becoming a great engineer and devoting myself to this path fully. I’ve been searching for a career that I find fulfilling and can imagine doing for the rest of my life since before I graduated from Princeton, and I truly feel like this is it. 

As far as specifics go, I want to accomplish the following over the next 3 months: strengthen my knowledge of Ruby and Rails, learn Node and Backbone, get more comfortable with Javascript and front-end development, learn to better integrate testing into my development workflow, and most importantly learn what good code is and how to write it.

At the same time I also plan on starting a pet project — an administrative dashboard for tutors to manage and keep track of their clients. This is something I have needed in my own life as a tutor for the past 8 months, and I’m sure others could benefit from it as well. Who knows, maybe I can even sell it to a tutoring company.

May 9, 20131 note

March 2013

2 posts

jQuery Methods: On vs. Bind vs. Live vs. Delegate

I’ve just learned about a handful of different jQuery methods—on( ), bind( ), live( ), and delegate( )—which are a bit confusing, so here’s my attempt to sort them all out:

BIND( )

This is the oldest jQuery method, and it attaches an event directly to a DOM element. For instance, I could write:

$(“#members li a”).bind( ‘click’, function(e) { } );

At the same time, I could also eliminate the bind method in favor of the following shorthand:

$(“#members li a”).click( function(e) { } );

Though easy to implement, there are some performance issues attached to this method:

  1. Method attaches the same event handler to every matched element in the selection
  2. Doesn’t work for elements added dynamically that match the same selector
  3. Performance issues when dealing with large selections
  4. Attachment is done upfront which can lead to problems on page load

LIVE( )

Unlike bind, this method doesn’t attach the event handler to every matched element in the DOM; it attaches one event handler at the root level. This method has been deprecated, in favor of delegate( ). 

DELEGATE( )

This method functions like live( ), but instead of always attaching at the root document, you can specify where you want it to attach. This is very powerful and can work with dynamically added elements since it relies on event delegation. However, there is an even more powerful method in jQuery 1.7…

ON( )

This was the first jQuery method I learned, and it is basically the most robust. It is basically the same as delegate( ), with a minor syntax change: 

$(‘#members’).on( ‘click’, ‘li a’, function( e ){ } );

$(‘#members’).delegate( ‘li a’, ‘click’, function( e ){ } );

At the same time, it also allows for the same functionality as bind ( ):

$(‘#members li a’).on(‘click’, function( e ) { } );

$(‘#members li a’).bind(‘click’, function( e ) { } );

As long as you can keep these different implementations straight, this is a method that can be used to replace all the other three methods.

Mar 12, 2013
Try JQuery

Today I completed the Try jQuery course on CodeSchool. Here are some takeaways:

First, what is jquery? jQuery is a JavaScript framework that makes it easy to find elements in an HTML document, change HTML content, listen to user input and react accordingly, animate content on the page, and talk over the network to fetch new content. All jQuery objects are signified by a $.

jQuery works by interacting with the DOM (document object model), a tree-like structure created by browsers so we can quickly find HTML elements using JavaScript. Inside the DOM, HTML elements and text become “nodes” which have parent-child-sibling relationships with one another. (JavaScript is essentially just a language that allows developers to interact with the DOM.) N.B. Every browser has a slightly different DOM interface, so we use jQuery, which works on all browsers, to interact with the DOM.

jQuery uses CSS selectors to find elements within the DOM.
—Descendant selectors (“#destinations li”) can be used to search all elements that are descendants of another element.
—Child selectors (“#destinations > li”) can be used to search all elements that are direct children of another elements (and not grandchildren, etc).
—Multiple selectors (“.promo, #france”) can be used to select multiple elements at once.
—CSS-like pseudo classes (“#destinations li:even, li:first”) can also be used.

While selecting elements from the DOM works, “traversing” the DOM is faster and therefore a better practice when applicable. Methods of traversal include:
— find( )
— first( )
— last( )
— next( )
— prev( )
— parent( )
— children( )

Best practices:

• Use the “text” method to access an element’s text or to change it.

• Always wrap jquery in a DOM ready wrapper: $(document).ready(function(){})

• The “on” method takes 3 arguments: the mouse/keyboard event, the element to listen to, and the function to execute.

• Other jquery events to listen for include:
-Mouse: dblclick, mouseenter, mouseleave, focusin, focusout, mouseover, mousemove, mousedown, mouseup
-Keyboard: keypress, keydown, keyup
-Form: blur, focus, select, submit, change

Mar 7, 2013

January 2013

2 posts

Writing Great Object-Oriented Code

Now that I’ve learned what object-oriented programming is, it’s time to delve into what makes good object-oriented code. Not that I could cover this in a single post, but we’ll have to start somewhere. Conveniently, there is, of course, an acronym that conveys the characteristics of good, scalable code — TRUE:

  • Transparent: The consequences of change should be obvious in the coe that is changing and in distant code that relies upon it
  • Reasonable: The cost of any change should be proportional to the benefits the change achieves
  • Usable: Existing code should be usable in new and unexpected contexts.
  • Exemplary: The code itself should encourage those who change it to perpetuate these qualities

The first step towards fulfilling these injunctions is to make sure your classes have a single, well-defined responsibility.

(1) Classes should have a single responsibility.

How are you supposed to decide what belongs in a class and what belongs elsewhere? The basic rule is that classes should have a single responsibility and nothing more. Anything extraneous to that goal most likely belongs somewhere else. As silly as it sounds, a good way to determine if a class contains behavior it shouldn’t is to pretend like it’s sentient and interrogate it. Rephrase every one of its methods as a question and that question ought to make sense For instance, “Please Mr. Gear, what is your ratio?” This is a reasonable thing to ask a gear class. However: “Please Mr. Gear, what is your tire (size)?” This is no longer reasonable. 

Action Steps:

  • Hide Instance Variables with Accessors - You should always depend on behavior, not data. Therefore, always wrap instance variables in accessor methods instead of directly referring to variables. (attr_reader / attr_accessor)
  • Hide Data Structures in Structs - Methods should have no knowledge about the arrangement of the data that they rely upon. For instance, a method shouldn’t know that the data it needs is the second number in an array. Just as you can wrap an instance variable in an accessor method, you can use the Struct class to wrap a structure.
  • Extract Extra Responsibilities from Methods - Methods, like classes, should have a single responsibility. The same questioning technique can apply to interrogating methods as well as classes. 
  • Isolate Extra Responsibilities in Classes - Once you have isolated the behavior in a class that questionably belongs in that class, you can decide whether it merits a new class altogether or whether you should use a temporary measure, like creating a Struct to isolate that behavior within a class, without committing to a new class. 

(2) Objects should know as little as possible about the outside world, i.e. have as few dependencies as possible.

Ruby is all about messages, and every message is initiated by some object to invoke some bit of behavior. However, this behavior is dispersed among many objects. For any desired behavior, an object either knows it personally, inherits it, or knows another object who knows it. This last tyoe of knowledge is called a dependency, and code can easily become strangled by poorly-managed dependencies. 

Ways to recognize dependencies:

  • A class knows the name of another class.
  • A class knows the name of a method that it intends to send to someone other than self. 
  • A class knows the arguments that a message requires.
  • A class knows the order of those arguments. 

** An especially odious instance of coupling is message chaining, where an object knows another who knows another who knows something. Beware!

Action steps to writing loosely coupled code:

  1. Inject Dependencies - Referring to another class by name is a no-no, because it assumes that the external class name will never change and that this class will never use the same behavior with another class. This unnecessarily limits the reusability and scalability of your class. In the bicycle example, for instance, Gear shouldn’t depend on Wheel to calculate its gear_inches method. It should merely rely on an object—any object—that has a diameter. 
  2. Isolate Dependencies - It may not always be possible to break all dependencies, and when this is the case, you should at least isolate these dependencies within your class. Metz advises, “Think of every dependency as an alien bacterium that’s trying to infect your class. Give your class a vigorous immune system; quarantine each dependency.” You should do this in two ways (a) by isolating the creation of an external class instance and (b) by isolating messages sent to some class other than self. This first scenario might happen in your initialize method, or in its own method, perhaps using the | |= operator (ex. @wheel | |= Wheel.new( rim, tire )). This does not eliminate your class’s dependency on the external class, but it does at least make clear the dependency. The second scenario, like the call to wheel.diameter, is easy to overlook when it is embedded within a block of complex code. Therefore, it is best to isolate this into a method of its own. For instance, create a diameter method (wheel.diameter) and use that in the gear_inches method, rather than including wheel.diameter on its own.
  3. Remove Argument-Order Dependencies - Sending a message that requires arguments often requires an object to know the specific order of those arguments. That’s more knowledge than the object needs, and the best way to counteract this knowledge is to use a hash to initialize arguments. That way order doesn’t matter. Rather than pass :chainring, :cog, and :wheel to the Gear initialize method, pass a hash “args” instead, and initialize each variable by calling args[:chainring], args[:cogs], and args [:wheel]. This of course assumes that you have control over the method in question. Sometimes you will be forced to depend on a method that requires fixed-order arguments. So what then? In that case, it is best to use a wrapper module or “factory” in order to handle all instantiations of this external class. (N.B. I haven’t totally wrapped my head around this one… see p. 50 for more explanation.)
  4. Only Depend on Classes That Change Less Than You - Every class in your application can be ranked along a scale of how likely it is to undergo a change relative to all other classes. The rule of thumb of determining the direction of dependencies is for a class to rely only on classes that are less likely to change than itself. A good way to accomplish this is to rely on abstractions rather than concretions. “Depending on abstraction is always safer than depending on a concretion because by its very nature, the abstraction is more stable.” More discussion of this on page 53. 
Jan 29, 2013
What Is Object Orientation?

I’m reading an excellent book called “Practical Object-Oriented Design in Ruby” that’s all about the fundamentals of object-oriented design. Rather than explaining how to code, it explains how to arrange your code. It begins with the fundamental assumption that all code will change. In light of this you could build something thats satisfies your current needs and then worry about scaling in the distant future (a tremendous headache down the line, obvi), or you can implement sustainable design patterns in your code that satisfy your current needs and acknowledge that those needs will inevitably change. The book is all about those design patterns. 

But first, what is object-orientation anyways? The author Sandi Metz explains it like this:

Object-oriented applications are made up of parts that interact to produce the behavior of the whole. The parts are objects; interactions are embodied in the messages that pass between them. Getting the right message to the correct target object requires that the sender of the message know things about the receiver. This knowledge creates dependencies between the two and these dependencies stand in the way of change.

Because of this, object-oriented design is all about managing dependencies. The fewer dependencies, the more flexible your code. Metz talks about objects as “knowing” things about the other objects with which they interact, for instance how many arguments another object takes or the order of those arguments. The general rule is the less knowledge about the outside world, the better. Objects should be myopic: they should see/know only themselves and nothing outside.  

When objects know too much they have many expectations about the world in which they reside. They’re picky; they need things to be “just so”. These expectations constrain them. They objects resist being used in different contexts.

Another important thing to understand about Object-Oriented Languages, as opposed to Procedural ones, is that they combine data and behavior into a single thing, an object. The operations that work with a single instance of a string are built into the very nature of the string object (itself instantiated from a String class). Each string object differs in that each contains its own personal string of data, but are similar in that each behaves like the others. 

Now, because programmers love acronyms, they’ve come up with a couple acronyms to represent the prevailing design standards that good software engineers follow in designing their code:

SOLID - Single Responsibility, Open-Closed, Liskov Substitution, Interface Segregation, and Dependency Inversion

DRY - Don’t Repeat Yourself

LoD - Law of Demeter

These following acronyms will be explored at greater length in following chapters.

Jan 25, 2013
#Ruby #Object-Oriented Design

December 2012

7 posts

Rails 101

Action Controller: One convention of Rails is the url structure of your application will correspond to the controllers and instance methods of those controllers. For instance, if a user goes to /clients/new in your application, they will by convention be routed to your ClientsController, which has an instance method “new”. That “new” method might create an instance of the class Client (which I think is defined in your Models — because I think each Controller should have a corresponding Model). 

HTTP Requests: Though HTTP has 4 verbs (GET, POST, PUT, and DELETE), only two are commonly send to the application via the user’s browser — GET and POST, with GET being by far the most common. GET requests are usually transfered to the application as query string parameters (everything after the “?” in a URL). The params will be defined within that query string. POST requests are usually transfered to the application via an HTML form the user has submitted. **N.B. HTML can be used to define the HTTP verb, using a “method” tag. This is how you can include PUT and DELETE requests.**

Default Routing: Once a controller has received a request and determined what it should do next (either access data in a model and/or output data to the user), it must determine which view to generate. The rule is that if you don’t explicitly render something at the end of your a controller’s action (instance method), then Rails will search for and render a view that is titled action_name.html.erb. In other words, if you access an index method within BooksController, Rails will default route to the file “app/views/books/index.html.erb”. If that index method is defined as @books = Book.all, then the @books instance method will be passed to the view generated at index.html.erb. (**QUESTION: Is the Book object from the model “book.rb”? If so, how does it have access to it? Is this a convention of Rails?)

Rendering: There are three ways for a Controller to pass information back to the user: (1) by rendering a view — from its own controller, another controller, or a default file or even JSON or XML; (2) by redirecting to another action or view; the difference here is that the second action will not be called, unlike when using render; (3) by using head to build header-only responses. I don’t fully understand the importance of this, but think it is used with AJAX. 

Routing: In Rails, a resourceful route provides a mapping between HTTP verbs and URLs to controller actions. The code “resources :photos" automatically creates 7 different routes in your application all mapping to the Photos Controller:

HTTP VerbPathactionused forGET/photosindexdisplay a list of all photosGET/photos/newnewreturn an HTML form for creating a new photoPOST/photoscreatecreate a new photoGET/photos/:idshowdisplay a specific photoGET/photos/:id/editeditreturn an HTML form for editing a photoPUT/photos/:idupdateupdate a specific photoDELETE/photos/:iddestroydelete a specific photo

Therefore, Rails would know to process a DELETE request to /photos/17 and send it to the correct destroy action within the Photos Controller. 

Dec 11, 2012
#Rails #MVC
Running - Jessie Ware (Disclosure Remix)
Dec 10, 2012
Dec 7, 20121,182 notes
Dec 5, 2012239 notes
MVC Architecture

Monday morning — back to my coding den in the basement of the Cobble Hill Starbucks! It must be a sign that I’m onto something when I spend much of the weekend wishing I were back here, rather than out socializing. Today, I’m spending some time reviewing the architecture of Rails apps, namely the MVC design pattern, and playing around with my simple demo app. 

I first was introduced to MVC (Model-View-Controller) architecture several months ago in my Product Management class. The gist, of course, is this: separate your code into groupings based on the function they perform vis-a-vis the browser and the database. Controllers receive user input from the browser and interact with Models, which are linked to the Database. After receiving data from the Database via the Models, the Controller invokes the appropriate View, usually generating ERB (embedded Ruby) HTML templates and rendering them in the browser. (N.B. This is a helpful way to think about how MVC interacts with a database: The controller tells the database what to do, and the model know how to do it.) A well-structured Rails app does not deviate from this convention; code governing display is only found in the Views, code interacting with the database only exists in Models, and code linking these two belongs in the Controllers. Sticking to this design pattern will make your code modular and much easier to maintain as you inevitably make changes in the future. When Rails creates “scaffolding,” it means that it is creating an MVC skeleton, to which you must then add the logic.

Rails functions slightly differently than a regular MVC framework in a couple ways: (1) Incoming requests are sent first to a Router, which determines where in the application that request should be sent, and ultimately activates an “action” somewhere in the controller code; (2) Rails relies on Active Record as the pre-configured ORM (Object-Relational Mapping) level, which maps the applications objects onto a relational database like SQL; (3) Views and Controllers in Rails are bundled together into one component called the Action Pack. This doesn’t mean they are jumbled together; Rails provides the separation necessary to demarcate between control and presentation logic. 

MODELS: libraries map database tables to classes. Each table in our database requires an analogous class in our program. Each row in that table represents an instance/object of that Class, and each column represents an attribute of that object. Class methods perform table-level operations, and instance methods perform operations on the individual rows.  

VIEWS: There are three ways to generate HTML templates in Views with Rails. (1) The first is ERB (embedded Ruby), which embeds snippets of Ruby into your view documents, which is a flexible approach, but someone breaks with the spirit of MVC. i.e. separating display and business logic. (2) You can also use ERB to construct JavaScript fragments on the server that are then executed on the browser, which is great for creating dynamic Ajax interfaces. (3) Rails also allows you to create XML documents using Ruby code. Not really sure when this comes in handy…

CONTROLLERS: Because so much of the interaction between user and database is taken care of automatically by Rails, the Controllers are actually quite simple and easy to develop/maintain. Controllers are also responsible for the following services: (1) routing external requests to internal actions; (2) managing caching; (3) managing helper modules, which extend the capabilities of the view templates without bulking up their code; (4) managing sessions, giving the users the impression of ongoing interaction with our applications. 

Dec 3, 2012
#rails
Jamie Lidell - "What A Shame"
Dec 2, 2012
Frank Ocean - Thinkin Bout You (Ryan Hemsworth Rmx)
Dec 2, 2012

November 2012

26 posts

Installing Rails / First Demo App!

After several weeks of learning the basics of Ruby, I feel like I’m finally ready to ride some Rails. I actually installed Rails a while back while I was going through the official Rails Tutorial, but I had less than a clue as to what I was doing then. So I’m forcing myself to go through the steps again and try to understand all the pieces in play. 

  1. Ruby Interpreter - also known as the Ruby MRI or CRuby, this is the software that interprets Ruby code. When you “download Ruby,” this is what you’re downloading. 
  2. RubyGems - the package manager that allows you to download gems (modular bits of pre-written code/programs that you can add to your own software, saving you time and effort. From the RubyGems site: “Ruby developers create and publish awesome gems which address specific requirements, solve specific problems or add specific functionality. Anyone who comes across similar requirements or problems can use them and eventually improve them.”)
  3. Ruby on Rails - a framework for quick and easy software development, relying heavily on convention over configuration. Imposes an MVC structure on your code, and allows for the creation of scaffolds upon which you build your business logic. 
  4. Database - The place where data is stored. Could be relational database (SQL) or non-relational (NoSQL), like MongoDB. 
  5. Production Web Server - Don’t understand all of the parts to this yet, but this is what deploys and hosts your program so that others can access it. Heroku is one option, I believe. I think this is where the term LAMP stack comes into play as well…
  6. Xcode - Apple’s suite of developer tools (IDE - integrated development environment). Not sure why I need this yet, or what it does.
  7. Version Control - namely Git, which allows you to store and keep track of any changes to your code as well as collaborate with others via GitHub. 

And voila: Rails is installed, and I’m ready to build my first application!

After a couple of minutes playing around with my first demo app, I’m realizing how easy Rails makes life. By generating a new controller, Rails automatically creates that controller, any views that you indicate as parameters, routes from the controller to those views, assets including coffeescript and scss, and tests and helpers for this controller. (Granted, I don’t know what tests and helpers do yet, but I’m sure they’re important!) All of this is done just by typing in “rails generate controller Say hello goodbye” at the command line, where “Say” is the controller and “hello” and “goodbye” are, I think, different methods for the SayController class. 

Okay, I just figured out a little of what helpers do: helpers allow you to use the link_to() method, which lets you link your pages together based on paths defined within your app, rather than absolute or relative paths that may change as you develop you app. The link_to() method takes two parameters: the first is the text that will be displayed and linked, and the second is the path that you want to link to. It looks something like this: <%= link_to “Hello”, say_hello_path %>.

Well that’s it for today. Tomorrow I’ll be exploring more of the Architecture of Rails Apps, and coming to grips with the MVC structure. That is if I don’t spend all day eating soup dumplings and singing karaoke with Fisher…

Nov 29, 2012
#rails #coding
Listen Solange
Nov 29, 2012
#music
Nov 29, 2012
Nov 29, 2012162 notes
Next page →
2012 2013
  • January 2
  • February
  • March 2
  • April
  • May 4
  • June 1
  • July
  • August
  • September
  • October
  • November
  • December
2012 2013
  • January
  • February
  • March
  • April
  • May
  • June 16
  • July
  • August 5
  • September 2
  • October 1
  • November 26
  • December 7