code_jen

a blogging platform for hackers

Senior Status: Goal Oriented Design

It’s week one of my senior year of college and I’m sitting here wondering, what was I doing those other three years here at Michigan?

Tonight I met fifteen people I’ve never even seen on campus before who utterly amazed me. It was a feeling I knew all too well for I recently experienced it at The Flatiron School – where I realized what incredible people the students/instructors are: motivated, generous, fascinated by life, determined and above all else, passionate. The people I met tonight were driven, they were students getting shit done — whether they were programmers, designers, aspiring VCs, interaction researchers, iOS devs or simply interested in entrepreneurship, it didn’t matter – they all had wrong thing in common; they were getting shit done and changing the world.

I can tell this year is going to be different. It already is.

To that end, here are some of my goals and inspirations for the last eight months I have here in Ann Arbor doing nothing except learning and taking in as many experiences as possible. It’s written as a letter to myself.

  • Surround yourself with people smarter than yourself in whatever field that may be. Art history, bioengineering, music studies, computer science, just be around people who can teach you about their field. Not only will this inspire your creative mindflow, but you’ll be introduced to new perspectives leading to a more well rounded character.

  • On the same spectrum, get really good at your field. Yes, you are totally a newbie to the tech field. You’re a linguistics and Spanish major for pete’s sake, but that’s not stopping you. Code, code, code. This is the last time in your life (likely) that you’ll ever have this much free time. Read all the books, go to all the meetups, audit all the CS classes.

  • Complacency is the ultimate enemy. There is never a time where you legitimately have nothing to do considering there are seventeen books in your dropbox (Thanks Avi and Flatiron team), treehouse lessons to be completed and commits to be made. Besides coding, just keep learning. Strum your ukulele often. Play with illustrator for a few hours. Run a few extra miles. Challenge yourself. There is no risk right now, you thankfully don’t need to be making money for another few months. Take the risk not presented to you, seek it out and be productive.

  • Explore deeper connections. After the next eight months, you have no idea where you’ll be located let alone where all your friends will be. But even with distance, if you have an amazing relationship with someone, neither of you will let it fall astray. Be an amazing friend, help each other, learn from one another, explore new aspects of Ann Arbor and of yourselves. Friends can be forever.

  • Lastly, be in the moment. Life is too fricken short to be living anywhere else. Whether you are at MHacks programming away in the executive suites of the big house (blog post to come next weekend about this hackathon), at an MPowered Sunday meeting, apple picking at the cider mill, or doing the dishes, be in the moment. Accept the gifts and obstacles life throws at you.

So here’s to my final year as a college student. Have fun, make it count. Be the person you’ve dreamed of becoming. You now have the resources and the power to do so and it’s up to you to make shit happen.

This Is Not the End

“This is my summer of learning” I so naively told a fellow pair programmer on the first day of Flatiron School. I told him, “I can’t go out tonight. I need to learn.”

Oh how skewed my perception was. If there is anything I can take away from my summer, it’s that learning is forever. If I continued with that initial sentiment I would learn for what, 3 months? Then what? Never learn again? With that mindset I’d be on a track to being a terribly uninformed, uninteresting, unchallenged person.

Over the past three months I’ve been surrounded by the most inspiring and motivated people I’ve ever met. It’ll certainly be a change of pace going back to college. (Yes, despite Avi’s efforts, I’m returning to college).

Even though the official dates for The Flatiron School have terminated and graduation has been completed, that in no way indicates the learning process is over. Avi, Blake, Ashley, Jeff and Jon have awarded me the gift of knowing how to learn. Before Flatiron, I was quite literally stuck in the console (and stuck in Python). Any escape seemed impossible. But thankfully with the help of the incredible instructors, students, and overall environment, not only have I deployed code, I feel ready to teach myself the next steps equipped with new methods, languages, and frameworks.

Although I’m heading back to college today, life won’t change too drastically. Sure I’ll be free to code from the comfort of Michigan Stadium (re Michigan Hacks — yup I’m hacking in the Big House in 25 days and I’m pretty stoked about it) but besides the freedom of space, I hope my life won’t be too different from the daily schedule at Flatiron School. I have plans to read “Rails Recipes”, plans to learn node.js, plans to finally get around to creating my personal website and yes, to blog way more frequently. This is the just the beginning.

Revealing Mass Assignment

This past weekend I dove head first into Rails. I quite literally created over seven applications just to familiarize myself with the commands and the generated file system with a clear goal of debunking some of the magic of Rails.I frequently came across the same error regarding “mass assignment.” The simple hassle-free fix was to add the attribute to attr_accessible and poof no more error. Although that temporarily fixed my error, this mass assignment concept was still fuzzy. Even the ruby guides surprisingly appeared to be unhelpful to a mere beginner — as most of the issues surrounding mass assignment have to do with security breaches, a topic I will go into at a later date.

The definition Mass Assignment is the convention Rails assigns the act of constructing your object with a parameters hash while you are assigning many values to attributes with one single assignment operator. Lacking mass assignment would mean a lot of manual labor drawing assignment statements for each and every attribute.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Movie < ActiveRecord::Base

end

#What mass assignment lets us do
attributes = {:name => "The Emperor's Club", :star => "Kevin Kline", :year => 2002}
movie = Movie.new(attributes)
Movie.create(:name => "The Emperor's Club", :star => "Kevin Kline", :year => 2002)
Movie.update(:name => "The Emperor's Club", :star => "Kevin Kline", :year => 2002)
#for any of the above code to work, mass assignment must be allowed for for each attribute assigned in hash.
movie.name
movie.star
movie.year
1
2
3
4
5
6
7
8
9
#Without mass assignment
attributes = {:name => "The Emperor's Club", :star => "Kevin Kline", :year => 2002}
movie = Movie.new(attributes)
movie.name = attributes[:name]
movie.star = attributes[:star]
movie.year = attributes[:year]
movie.name
movie.star
movie.year etc.

Attr_accessible The keyword attr_accessible allows developers to assign specific attributes open to mass assignment.

Under the hood of the attr_accessible we have a method that looks like

1
2
3
4
5
6
  def initialize(attributes_hash)
    attributes_hash.each do |k,v|
      self.send(("#{k}="), v)
    end
  end
end

This code takes in an arbitrary amount of key value pairs. Mass assignment permits us to set a bunch of attributes at once. For each k/v pair sent in above, the name of the key becomes the name of an attribute setter method and the value associated with the key is the name of the value you want to pass to that method. The ruby send method then permits you to call the method name that is the key’s name as well as call the associated value as a param in the key’s method. This is a solid underlying method because we can easily alter the number of attributes in the class and need not worry about editing the initialize method.

Thus without attr_accessible, all attribute fields would be open to mass assignment leading to a potentially perilous situation.

Security Issue Not going to go super indepth here yet, but essentially because rails conventions are so, well – conventional – it’s not too tough to merely guess attribute names like :user or worse, :admin. Funny story, actually in order for a developer named Egor Homakov to prove his point that mass assignment is insecure and dangerous, he actually gave himself access to commmit to the rails repo on github. (read more about his awesome hack or lapse in judgement or what he calls “The commit that changed my life” here. Anyway there are two main ways to get around this.

Whitelisting This is what’s safe and we assume everything else is dangerous. Thus we can assume this is super secure because we are being explicit in what we give access. You tell your application what is allowed. Similarly, attr_accessible makes the attributes accessible while the others are protected aka we are being explicit in what we give global access.

1
2
3
class Student < ActiveRecord::Base
attr_accessible :name, :tagline, :twitter, :github
end

These attributes are unprotected and can be mass assigned and if we add more we need to add them to this list assuming we want them to be accessible.

Blacklisting Just the opposite. Consider all attributes “good” unless they come from explicit source x. Similarly, the attr_protected method says that the written attributes are protected while everything else IS accessible.

1
2
3
class Student < ActiveRecord::Base
attr_protected :is_admin
end

Above we are protecting the is_admin attribute and all other attributes added at a later time will not be automatically protected like :is_admin.

There ya have it! mass-assignment.

What the Foo?

Questions on Questions

Learning without questioning. That’s a problem. While learning to program over the past two weeks, I’ve come to realize something: I need to learn to love questions as much as the answers in order to grow.

Before I so fortunately arrived here @FlatironSchool and discovered that vital piece of info, I dabbled with the world of self-teaching. Some of the resources I attempted to utilize included Codecademy, w3schools, Khan Academy, & even auditing CS classes at UMich. Since the code was never recited aloud to me, the names of variables and methods didn’t cross my mind. One of my goals for this week was to question anything and everything. Quiz yourself until there is no longer a grain left in the argument, I’d say to myself at night.

To that end, this past week Avi demonstrated examples regarding ruby classes and objects.

1
2
3
4
5
6
class Dog
  def initialize()
  end
end

fido = Dog.new

Fido. That name again. Why do I learn about this dumb dog named Fido every few months. Who is Fido and why don’t I know him? Is he brown? Is he friends with Foo? What about bar? or baz?

Now that the questions were out of the way, it’s time to dig deeper for an answer. Between every programming resource I’ve come across, there appears to be defined terms to name entities such as methods, variables, data, and commands to help demonstrate an abstract system. These aliases for variables in code examples (like foo and baz listed above) are formally known as metasyntactic variables.

Background

To reiterate, within the computing sector, there are definite syntactic and semantic conventions in order to help display an abstraction. Metasyntactic variables define the specific words themselves used by programmers universally to assign a non-semantic yet consistent alias to a command or function to indicate that the word must to be replaced by the programmer him or herself, and exist solely to demonstrate a concept. So, these words are mere logical representations or arbitrary objects, like x and y in mathematics.

Foo who?

There seems to be no precise lineage dating the instance of Foo to programming but naturally, many theories have been surmised. Sometime within the 1930s, the word foo was cited in a comic called Smokey Stover by Bill Holman to mean essentially nothing – or a nonsense word. For example, according to RFC Archives in the cartoon many license plates read “FOO” and nonsense expressions could be discovered in backgrounds echoing “He who foods last foos best” and “Where there’s foo, there’s fire.“ When asked for this choice, Holman stated that he took advantage of the three letters because he saw it in a fortune figure meaning “good luck” or sometimes “happiness” in Chinese depending on the pronunciation. Apparently, the word foo was actually quite popular in the thirties — appearing in many other comics and cartoons like The Daffy Duck.

Then, the term took a major turn, specifically towards the military in the 1940s, where it merged with the common metasyntactic variable known as FUBAR. FUBAR, as you probably guessed, stands for “F**ked up beyond all repair.” Even during WWII the term “foo fighters” was coined — referring to people searching for UFOS aka some mysterious/unknown unidentified flying object.

Technically, the term foo was probably first maintained in a coding manner by the Tech Model Railroad Club in the 1960s. The term was adopted by MIT and in their “train room” there are two buttons labelled foo and bar. Legend has it that these miscellaneous buttons were re-evaluated for any and all random ideas the MIT hackers were working on at the time, further supporting the notion that foo and bar refer to mere var names. Foobar even appeared in a systems manual by Digital Equipment Corporation in the late 60s.

Conclusion

OK this is starting to make sense now. Programming languages take advantage of arbitrary words in the basic structure of a function so we can be left with “good luck” to get through the actual difficult process of making the function work within the scope of our task at hand even though we may have f**ked up the function beyond all repair. Noted. As we say here at Flatiron, failure is learning. Celebrate failure. Celebrate your FUBAR function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#foo examples
# Declare var foo and set equal to 5
foo = 5

# Declare var bar and set equal to 12
bar = 12

# Declare method named baz, which prints the text 'Hello world'
def baz
   puts 'Hello world'
end

#common metasyntactic variables in ruby
foo, bar, baz, quux, gorp, fred, barney 

bar = foo + baz
#wait, is that really better than 
value = var_1 + var_2

Thanks to all these handy resources for the helpful info regarding possible foo citations: Wikipedia Foobar, Wikipedia Metasyntactic variable, RFC Archives.

A Beginner’s Thoughts on “Practical Metaprogramming”

An intro to metaprogramming in Ruby

Pre thoughts

The term “meta” often gets used in reflection, but as a newcomer to the dev world, I’ve heard this word even more. I have a vague notion that it refers to code that writes code. Meta pretty much means referring to self. Like discussing a discussion. Joking about a joke. Emoting from an emotion. The abstraction referring to the concept itself. As a linguistics concentrator, I’ve been dealing with meta abstraction and analysis in a non technical way. Now that I’m diving into developing, it’s time to get meta with programming.

I took a look at Steven Harm’s deck on speakerdeck.com which is partially aimed at beginner/intermediate level Rubyists like myself.My interpretation of his analysis will focus on the first half of the presentation because honestly, that means more to mean right now than the more complex aspects. I’ll come back in a few weeks to share my deeper progression with MP.

Application

Especially with Ruby, it makes sense that essentially all basic libraries are built off of the concept of metaprogramming. Libraries of ruby code are packaged and installed cross computers to serve up code that builds other code. This written code passes messages to another piece of the structure at the time of running the program. Although the definition of “metaprogramming” is disputed, the practical application is that metaprogramming really is just programming code that acts on other code, such as classes and modules, at runtime.

In order to pass a method to an instance of a class we put defs in the class.

1
2
3
4
5
6
7
8
9
var s = "Ruby syntax highlighting";
class Dog
  def self.dognicate
    puts "doggy"
  end
end

Dog.dognicate
puts Dog.ancestors

Dog.dognicate returns “doggy” as expected. The method ancestors returns Dog Object Kernel BasicObject

We can also put defs in a module instead of a class or defs in the module into the class. (sounding meta already, I know).

Thus with all these ways of to pass code from various structures, re-routing, and interpreting based on various conditions exists. And that’s the concept of metaprogramming. Programming code to be passed to into another element and in turn be interpreted by the original code above and then it returns to the second element and runs.

This is a very basic level using methods and classes and hinting at modules.

MP and Classes

Let’s take a look at another example. Thus far in my programming life, I’ve been using the #attr_accessor module to define setter and getter methods in Ruby using a single line of code. However, according to MP principles, even this is still not ideal if I have more than one attribute per feature.

1
2
3
4
var s = "Ruby syntax highlighting";
class ComputerParts
  attr_accessor: :hardrive_info, :hardrive_price, :memory_info, :memory_price, :model_info, :model price
end 

With a little further reading from rubylearning blog I can go more in depth regarding this Ruby Object Model that is starting to be defined above. Everything in Ruby is an object. When you call a method on a object, the interpreter literally searches for the method to see if it exists. If it does, the method will be called and the appropriate reaction will be executed. However, if not, it looks beyond the scope of the method and looks at the object’s class or parent class or it’s parent class etc. until it reaches the original class.

method_missing()

So now that we’ve talked a bit more about the structure of Ruby objects we can talk about an important method in metaprogramming called method_missing(). One should define this method within a class and if a method cannot be determined or found in the object’s class, it will go back to the called object and call method_missing() method which thus returns NoMethodError error. You can even edit the metaprogram so it takes two parameters as in method_missing(sym,args).

Ghosts Methods

Another way MP is utilized in by calling a method to affect the interpretation of passed messages, using something called a ghost method. In these methods you can write code that actually takes a method, interprets and responds without actually reciting the name in advance.

Complexity

Harms provided an in depth example to see the value of MP in a complex set. He was looking to way to easily conjugate latin verbs as they are passed into methods to determine whether they are first person, second person, third person and singular number or plural number.

Had he not used MP, it would have been vital to define 6 methods per tense (6 tenses), voice (2 voices) and mood (4). That results in a heck of a lot of unique paths..potentially thousands. This is definitely not something anyone would want to program due to inefficiency, poor elimination of ambiguity and pure sanity.

Merits of metaprogramming (MP)

Code that programs other code == insta time saver! No need to type out the body of a method for each piece of code you want that function to run. Metaprograms build from basic ruby. Not only is your code more scalable, but it becomes DRYer too — meaning “do not repeat yourself” as your code becomes more defined with purpose. It quickly becomes apparent that debugging is a much simpler when the ambiguity is only in one instance.

Questions

What is the key difference between programming and metaprogramming? In my book, there a difference doesn’t seem to exist. Were we not just programming normally in the above code. When diving into much more complex method definitions, I can clearly see the win involved with MP.

Looking forward to returning to this topic in the coming weeks.