Travis Emmett's blog

A coder in training's thoughts

A Spot of Tea, Anyone?

I was recently in a meeting with a web development team in New York and they mentioned they relied on a template language called Tea, which all their corporate online content is translated into before it goes live. I had never heard of it before so I thought it would be a good chance to investigate further.

Tea was created in 1997 and is a strongly typed, compiled programming language made to work within a Java-based hosting environment and is still used by several large websites today. While the original version of Tea is no longer maintained, many users now utilize TeaTrove, a maintained fork of the Tea source code. According to TeaTrove’s GitHub page, Tea’s main goal is “to provide an enforced separation between data processing and presentation, without sacrificing basic programming constructs.” It’s basically designed to be simple and ensure that all programming and business logic reside in a separate place.

Tea utilizes templates for simple textual output and HTML. It relies on a Java hosting environment for all data and cannot directly acquire or modify data itself (it can however pass return values back to its Java host). Data must be passed from the hosting environment to the Tea template, either via objects sent through a template’s parameters or through a custom context that supplies various functions. Here’s an example of a simple Tea template:

1
2
3
4
5
6
7
<% template MyTemplate(PageInfo page) %>
<html><head><title><% page.title %></title></head>
<body>
<h1><% page.heading %></h1>
<p><% page.body %></p>
</body>
</html>

Tea’s code regions are delimited by “<%” and “%>”. Any code inside these regions is evaluated by Tea and then inserted into the surrounding html when rendered. Here, a Tea template called “MyTemplate” is being declared and passed in a “PageInfo” object called “page” as a parameter. The passed in object can then be accessed in order to output its various properties (i.e. using page.name). This reminds me of the Embedded Ruby syntax used when rendering Rails views with HTML as well as the same general principle Rails has of passing in a local variable to the view (although it should be noted that Tea explicitly forbids accessing objects not passed into the view as opposed to Rails which doesn’t).

It is interesting to note that while explicitly declared variables are required in a template’s declaration, a characteristic common in a strongly typed language, a local variable’s type created inside a Tea template is inferred based on assignment where the below variable “message” is inferred to be a string:

1
message = Hello

After reading Tea’s documentation, it’s interesting to me that the authors state that it was intentionally designed to be a language of limited functionality. They seem to be walking a fine line of providing just enough functionality to be useful, but not enough to be able build a fully functional application:

“When introducing programming constructs into a template, the challenge is to come up with something that is powerful enough, yet at the same time be simple and safe. If it’s too powerful, then complete applications could be developed in templates. If it is too weak, then HTML formatting ends up in the application. If it isn’t simple or safe, then application developers end up writing and maintaining templates.”

I can definitely appreciate this as I have experienced the temptation to place parts of an application in the view (or presentation) which belong in the core of the application. I can imagine this temptation would lead you increasingly astray if the content you are producing exists in many different formats, something Tea was created specifically for.

In practice, I also wonder if there are any drawbacks to its intended limited functionality and if any inefficiencies exist in maintaining a separate template system as opposed to a single framework uniting front and back end content. I am definitely intrigued though by its enforcement of programming best practices and the fact that several major companies continue to rely on it today. I definitely look forward to reconnecting with the developers I met in New York to pick their brains further about it!

Sandi Metz and Object-Oriented Design in Ruby

If you talk to most Rubyists, a book almost universally held in high esteem is Sandi Metz’s Practical Object-Oriented Design in Ruby. Before my time at The Flatiron School, I had some experience in programming but mainly from the procedural side, so when Objects or Classes started coming into the fold, I would usually end up running for the hills. After the program, I felt like I had finally acquired a solid foundation in Object Orientation, but I still wanted to get a better understanding of some of its nuances. So I thought it was high time to pick up Sandi’s tome and see what all the fuss was about. And, about a quarter of the way in, I get it.

It’s very cool having a seasoned developer like Sandi describe, in fluid prose, her best practices over the last 30 years of her career. It’s like having a good friend available at all times to answer your nagging questions “Ok sure, but why?” It’s also great to see, rather than just teaching from the best code first, her progression through various refactorings starting with the newbie antipattern. So without further adieu, here are some interesting points from her from the first few chapters:

Classes and methods should have a single responsibility and do the smallest possible thing

Most people have heard this before but it’s important because one of the major advantages of Object Oriented code is that if written correctly it should serve as a set of interchangeable parts to be used by future programmers. Implemented well it usually means features can be changed, removed, or added without changes cascading down through your application’s codebase in a programming nightmare. D.R.Y. (Do not Repeat Yourself) ties in nicely here because achieving DRY code often forces you to break your program into small, unique parts.

Deciding on how to divide up your classes and what responsibilities can be intimidating but Sandi provides a few rules of thumb: 1. Try to define the purpose of your class in one sentence not using AND or OR. If it doesn’t fit, probably rethink it 2. As for what behaviors belong in your class, try asking your class its various methods in the form of a question to see if it makes sense. Like “Hi Appointment, what is your time?” sounds pretty good. But “Hi Appointment, what is your square footage?” sounds suspect and belongs in another class.

Avoid dependencies

Avoiding dependencies is a large topic (too large to be covered fully here) and is one of the central theme’s of Sandi’s book but I think this statement of hers sums it up nicely:

“Every dependency is like a little dot of glue that causes your class to stick to the things it touches. A few dots are necessary, but apply too much glue and your application will harden into a solid block.” -Sandi Metz

So very true and I couldn’t have said it better. Minimizing dependencies between classes ensures that when one class needs to change that it will be pliable and won’t set off a cascade of expensive changes in other classes. One small way to do this that I enjoyed reading a little more about was why it can be advantageous to use a singular hash argument when instantiating an object instead of relying on several argument order ones:

1
2
3
4
5
6
7
8
9
10
11
Class Person
  attr_accessor :name, :height, :hair_color

  def initialize(args)
    @name = args[:name]
    @height = args[:height]
    @hair_color = args[:hair_color]
  end
end

Person.new(name: Travis,  hair_color: brown, height: 6.25)

Using a hash has several advantages including 1. As an initialization argument’s order and number can sometimes change in the future this helps prevent it from breaking when other classes instatiate a new object of that class 2. The keys are instructive of their purpose and what their values represent. 3. Why, removes unnecessary dependencies across your code of course!

Heed the Law of Demeter (LoD) aka Avoid Trainwrecks

The Law of Demeter broadly maintains that it is bad practice to send messages to distant objects when relying an intermediate object to get there. Every Demeter infringement isn’t necessarily wrong but always be wary of the possibility especially if you are altering an attribute of a distant object and not just accessing it. Following this advice results in loosely coupled objects, a hallmark of good OO code.

Take for example if you have a class called “Order” and it has a method within it called “place_order” and within that method the following call is made: customer.cart.items.update_stock. This would likely be a violation of Demeter because you are accessing the customer object to get to the cart object to get to the item objects to implement the update_stock method to change each item’s quantity attributes. Whew, I’m outta breath. Sometimes this is simply referred to as “avoiding trainwrecks” due to a violation’s long method chain’s resemblance to train cars and their propensity to crash your program, which I think is much more memorable than remembering the Greek harvest goddess (sorry Dem).

Access instance variables via methods

Yes, I am guilty sometimes of referring to instance variables directly when I should use a reader or writer method instead. But I never fully understood why it was important not to. Sandi makes a good argument for always using a reader method instead because if you decide that your instance variable requires an interim calculation after you have peppered the instances throughout your codebase, it will take some time to fix when using a method would require a code change in only one spot.

Actively categorize your methods as public or private

How you classify your methods within a class tells a story about your code and communicates your intentions to other programmers. A public method generally carries along the following assumptions with it: 1. Other objects are free to utilize it 2. That it is stable and will not likely change 3. Communicates the responsibilities and purpose of your class. 4. That it should be tested. Private methods on the other hand generally indicate that your code is not meant to be relied on by other objects (it actually cannot in Ruby without a workaround) and may change and generally is not part of the core testing framework of an application.

Well, these are just a few of the many things I have learned thus far from Sandi and look forward to finishing the rest. It really is a fascinating book because it delves so deeply into the philosophy of programming and object orientation. Perhaps I will go through some other lessons of hers when I have the chance. Thanks for reading!

A Few of My Favorite Gems...

Along my journey of learning Rails, I thought it would be helpful for beginners if I listed a few of the indispensable gems I have come across. Before I started developing in Ruby, I would always hear people talking about 'gems' but not really have a firm grasp on what a gem actually was. A gem is basically a library or plug-in that provides some additional functionality that you can require your application to load every time it is run. They are incredibly helpful because they allow the developer to focus on building out the unique parts of an application, rather than reinventing the wheel each time. Rubygems.org is the main repository of Ruby gems (there are over 6,650 gems listed currently) but Ruby Toolbox is also a great resource because it breaks gems down by category. So, in no specific order, here are just a few of my favorites:

Rails ERD

I love Rails ERD. I think there's a tendency when coding to discount visual representations of data and logic for the text editor. While parsing code and relational data mentally is great, I think drawing it out is very important because it allows you to get a more complete understanding of how your data is really interacting with each other. Rails ERD utilizes Graphviz, an open source visualization library, to visualize your Active Record database schema and their relationships (which is probably an over fancy way of saying it let you visualize your database). It renders a nice pdf of your database schema and here is an example below:

Note that Rails ERD requires Graphviz to be installed on your system and detailed instructions can be found here. Once installed, you can type simply "erd" in your console and find the rendered file in your project's main directory under erd.pdf. I actually like to display foreign keys in my tables so to have ERD do this you would type "rake erd attributes=foreign_key,content" into your console instead.

Faker

Faker is a really fun gem to play with. Sooner or later, your applications will get to the size where your databases need a bunch of realistic data to test with. Faker will supply a huge variety of data with which to construct example seed data. So, for instance, in place of making up a street address yourself, you could specify Faker::Address.street_address and it would provide you an example address like “282 Kevin Brook”. It has tons of different kinds of sample data available. Some of the more interesting ones: Avatar images, company slogans, and of course sample bitcoin addresses for all you Internet currency junkies. Here’s a quick example of creating a new Person entry in your database with Faker:

1
2
3
4
5
person = Person.create(
  :first_name   => Faker::Name.first_name,
  :last_name    => Faker::Name.last_name,
  :email        => Faker::Internet.email
)

Figaro

Figaro is an extremely helpful gem when you begin utilizing API’s in your applications. If you are using a public GitHub account in the development of your project, once you supply your API key inside of your application, you want to make sure GitHub does not remember this file, lest it be found by a malicious user. This is where Figaro comes in handy and makes the process very easy. As the steps were a little confusing online when I began using it, assuming you are building a Rails application, here is an example implementation that worked for me:

1. Add “gem ‘figaro’” to your gemfile in your Rails application

2. Type “bundle install” in your console

3. Then type “figaro install” in your console. This will create a file in your config folder called application.yml where we will save the API key. This will also add an entry for application.yml in your .gitignore file so git will not push it to GitHub (be aware when working with any team members they will also have to perform these steps in order to use the API)

4. Go into your config/application.yml file created by Figaro in the previous step and enter your api key. There are different ways to do this but in the recent project I worked on, we chose to enter our key like this:
weather_api: “f0403B7e04110UI15c”

5. Then, find the place in your application (usually within your API’s model class) where you are making the request to the api for data, and save the api key to a variable:
api_key = ENV[“weather_api”]

Voila, you now have access to your api key from the variable api_key without it ever appearing on GitHub!

What's a Form_for, or for That Matter, a Form_tag? Some Examples...

Last week I was introduced to the magic that are the various form builder methods in Rails. It was a little intimidating to me because I am sort of a control freak with my code and Rails makes a number of assumptions behind the scenes as to what you are trying to do. But it's also amazing because with that automation, you can say goodbye to writing out html forms manually and these methods can be very smart. There is a ton of documentation online which is a great resource, but I was a little frustrated that it was hard to find an example all in one spot of a form's ruby code, the html output, what the form looked like on a web page, and the corresponding params hash sent on submission of the form.

So, in case you are looking for a quick reference to these tags, here are a few briefly explained:

form_tag

The form_tag is an ActionView helper method that follows the url provided to it and defaults to the POST method unless you specify otherwise. Here we are specifying a PATCH action in order to update a record:

views/concretes/edit.html.erb:

1
2
3
4
5
<%= form_tag("/concretes/#{@concrete.id}", :method => 'patch') do %>
<%= label_tag ("mix type") %>
<%= text_field_tag('concrete[mix_type]', @concrete.mix_type) %>
<%= submit_tag "Update Concrete" %>
<% end %>

The second argument in text_field_tag is responsible for pre filling in the value of the existing record (which you’ll notice is filled in below) in order to submit an update.

Outputted HTML:

1
2
3
4
5
6
7
<form action="/concretes/1" accept-charset="UTF-8" method="post">
<input name="utf8" type="hidden" value="✓"><input type="hidden"
name="_method" value="patch"><input type="hidden" name="authenticity_token" value="aBUUH4T65nmHGLS/uATo5yNttcsWRW8gpyrV4MvPEDbfOKWuqmC498fV8r9WAYHBBvHQOBNctaeeLqcuk27iRQ==">
<label for="mix_type">Mix type</label>
<input type="text" name="concrete[mix_type]" id="concrete_mix_type" value="stone" >
<input type="submit" name="commit" value="Update Concrete">
</form>

Example form (non functioning):

Params content:

And here is the content of the params hash after submission of the form:

1
2
3
4
5
6
7
8
9
10
{"utf8"=>"✓",
 "_method"=>"patch",
 "authenticity_token"=>
  "aBUUH4T65nmHGLS/uATo5yNttcsWRW8gpyrV4MvPEDbfOKWuqmC498fV8r9WAYHBBvHQOBNctaeeLqcuk27iRQ==",
 "concrete"=>
  {"mix_type"=>"stone"},
 "commit"=>"Update Concrete",
 "controller"=>"concretes",
 "action"=>"update",
 "id"=>"1"}

This params hash could then be intercepted in the concretes controller's update method where you would save the changes to the existing record.

form_for

The form_for method is another ActionView helper that offers an additional level of abstraction (and ease) over it's lower level form_tag counterpart. This is a good approach to take if you are practicing the Rails convention of RESTful routing and you are using a standard active record object, in this case an instance of the Baby class. Because Rails makes so many assumptions about your form, it is good practice to still double check your data is being routed correctly. Below is a basic illustration of entering a new baby name in a database:

views/babies/new.html.erb:

1
2
3
4
5
6
7
8
9
<%= form_for (@baby) do |f| %>
<%= f.label :first_name %>
<%= f.text_field :first_name %>

<%= f.label :birth_date %>
<%= f.date_field :birth_date %>

<%= f.submit %>
<% end %>

Note the amazing number of assumptions Rails has made about your form! Based on the view type that the form_for is added to (in this case our new Baby view), Rails guesses correctly the method (post), the name of the submit button (Create Baby), the desired nesting of data in the params hash for mass assignment ease -- baby[first_name] and baby[birth_date], among other things.

Outputted HTML:

1
2
3
4
5
6
7
8
9
10
<form class="new_baby" id="new_baby" action="/babies" accept-charset="UTF-8" method="post"
_lpchecked="1"><input name="utf8" type="hidden" value="✓"><input type="hidden"
name="authenticity_token" value="6/3miTvGAxS4pv3D2/
zQU8iLYnwDB1wDaYC6e7qDknNc0Fc4FVxdmvhru8M1+bl17RcHjwYehoRQhMi14iJgAA==">
<label for="baby_first_name">First name</label>
<input type="text" name="baby[first_name]" id="baby_first_name" >
<label for="baby_birth_date">Birth date</label>
<input type="date" name="baby[birth_date]" id="baby_birth_date">
<input type="submit" name="commit" value="Create Baby">
</form>

Example form (non functioning):

Params content:

{"utf8"=>"✓",
 "authenticity_token"=>
  "6/3miTvGAxS4pv3D2/zQU8iLYnwDB1wDaYC6e7qDknNc0Fc4FVxdmvhru8M1+bl17RcHjwYehoRQhMi14iJgAA==",
 "baby"=>
  {"first_name"=>"Brandnew",
   "birth_date"=>"2015-07-13"},
 "commit"=>"Create Baby",
 "controller"=>"babies",
 "action"=>"create"}

This params hash could then be intercepted in the babies controller's create method where you would add the data from the params hash to the database.

Dude, Where's My Object?

I love things that expose a little bit of what Ruby is doing under the hood. And I’m new to object orientation so you will just have to humor me here. Let’s say you’re in IRB and you just created a shiny new Car class with the following Ruby code:

1
2
3
4
5
6
7
8
9
10
11
class Car
attr_accessor :make, :model, :year
  def initialize(make, model, year)
    @make = make
    @model = model
    @year= year
  end
  def drive
    puts "Vrooom!"
  end
end

And now you decide you’re ready to create a new car so you can get ready to take it for a spin with the following code:

1
Car.new("Renault", "LeCar",  1979)

Renault LeCar? Nice choice! Now, let’s ride. But wait, you forgot to assign your new car to a variable. Dude, where’s your car?

Well, as it turns out, it’s not actually gone. It just requires a little snooping around to get it back. Ruby comes packaged with a module called ObjectSpace which contains a useful method #each_object to aid in the search. ObjectSpace interacts with Ruby’s garbage collection facility which helps manage Ruby’s memory. Calling #each_object and passing in your class in question will allow you to find all living objects of that particular class (assigned to a variable or not):

1
2
3
4
ObjectSpace.each_object(Car){|car| puts car.object_id}
#IRB output
  #70206505370260
  #=> 1

Ruby returns to you the number of objects in the Car class ‘1’ and your missing car’s object id, provided you #puts it (70206505370260). If you had a bunch of objects in that class instead of just one like we do, you could pass in the value of a particular instance variable of your object in question into the block through an if statement to narrow down your search.

But I digress. Now that you are armed with this information, you can use another method in ObjectSpace called #_id2ref which converts an object id into a direct reference to the object to finally track down your car and save it:

1
2
3
4
5
6
lecar = ObjectSpace._id2ref(70206505370260)
#IRB output
=> #<Car:0x007fb473a08528 @make="Renault", 
#@model="LeCar", @year=1979>

lecar.drive ==> "Vroom!"

Way to go! You even remembered to store your car to a variable this time so this will not happen again. Jesse and Chester would be proud.

Now, if you want to have some more fun, ever wonder what other objects Ruby has hidden under the rug? Try this line of code in IRB sometime to see what strings Ruby currently has in memory. It yielded an array of 23,157 strings I did not know about!

1
2
3
strings_array = [ ]
ObjectSpace.each_object(String){|string| strings_array << (ObjectSpace._id2ref(string.object_id))}
strings_array

What’s yours say? SWEET!

A (New) Programmer’s Musings

A (new) Programmer’s Musings

Week two has just wrapped up on my wild and crazy journey that is The Flatiron School. I feel really lucky to be here and to be surrounded by such smart folks, and even more lucky that in a few months time I might be able to work somewhere as a full time web developer.

As a relative newcomer to the programming field, I’ve found myself wondering about various aspects of the field that I’ve either taken for granted or never thought that much about before. To the veteran CS professional or developer, these may likely seem like unoriginal questions coupled with perhaps misguided musings, but hey, it’s my blog so I get to do what I want! ;)

And, since I’ve always had more fun asking questions than answering them, here are some of the things I’ve been thinking in no specific order:

Why are there so many languages?

It seems like the number of programming languages is increasing more rapidly as time goes on as opposed to human language which went from many to present day where it seems to be converging towards one. Is this an indication that we are still very early in the computer revolution? Or perhaps an indication that the two things are very different from each other? Maybe this isn’t an apt comparison, but it’s something that piques my interest.

Ruby as a language for people, instead of computers.

I really dig this concept. When I was trying to figure out what programming language to learn, I remember trying one that required like 5 lines to add 2 + 2. While I can understand various loyalties people have towards one language or another (I also think there can be a natural tendency towards this the more difficult something is), it seems to me there is something very powerful in a flexible language that makes it easy to express yourself simply–something Ruby is known for. The easier something is to express, implement, and understand, the more opportunity there is for trial and error and experimentation, something I think crucial to invention and making anything better. After all, as our instructor Avi Flombaum has mentioned, the human brain can only process a limited amount of data (around 60 bits per second) when making a decision, so why not leave as much of this power as possible to devise better ways to perform the task at hand than to comprehend the instructions in the first place?

Is language the most efficient way?

I also wonder where this takes you if you follow the premise of this argument further. Are there inefficiencies of the spoken and written word that perhaps could allow for even more powerful languages to emerge? Perhaps there’s a sort of programming equivalent that allows for comprehension on multiple levels at once, like Charles Joseph Minard’s famous info graphic charting Napoleon’s disastrous march through Russia in 1812. I don’t know enough about CS to answer this question yet, but it’s something I’ve been thinking about and look forward to exploring further someday!