How to Stay Classy With Ruby Variables

Ruby provides a number of options for non-instance-specific variables – class variables (of the form: @@var), constants (in all caps: VAR), and class instance variables (@var).  Which one to use depends on the use case, and to some degree on personal preference.  Let’s explore this a bit.

Constants are meant to be – well, constant.  This is not technically enforced in Ruby; if you redefine a constant during program execution, it will display a warning, but not actually raise an error.  However, the semantic idea of a constant is that it should be defined once and not touched again. Variables, on the other hand, are variable.  They record a particular state that is likely to be redefined at some future point in time.

Now let’s examine some use cases and see where things start to get tricky.  To make things fun, let’s go to the zoo! In this case, I have an Animal class, which will be at the top of the hierarchy and have animal classes that descend from it.  Here are my requirements:

1) Since most of my animals are quadrupeds, I decide it makes sense for the class’s instances to default to 4 legs, and any subclass (let’s say Octopus) with a difference number of legs should change the default.

2) Both the Animal class and the individual animal-type classes should keep track of how many of each type of animal exists, so I can check Animal.all or Octopus.all.

Let’s get to work.  Following Sandi Metz’s recommendation, we’re going to build an Animal parent class with a post-initialization hook.  Hence, the Animal class’s initialize method will append the new item to an animals array, and then call an after_initialize method which will be accessible to the child classes.  We’ll start with just 2 animal types, octopus and llama:


class Animal
@@animals = []
@@legs = 4
def initialize(args={})
@@animals << self
after_initialize(args)
end
def after_initialize(args)
end
def legs
@@legs
end
def self.all
@@animals
end
end
class Octopus < Animal
@@octopi = []
@@legs = 8
def after_initialize(args={})
@@octopi << self
end
def self.all
@@octopi
end
end
class Llama < Animal
@@llamas = []
def after_initialize(args={})
@@llamas << self
end
def self.all
@@llamas
end
end
Llama.new.legs # => 8

view raw

animals.rb

hosted with ❤ by GitHub

Hmmmmmm, not exactly what we wanted.  How did we end up with an 8-legged llama?

8-legged llama

Well, it turns out that Ruby class variables don’t play very nicely with inheritance.  Essentially, they are shared by any class in an inheritance chain.  So when we defined @@legs in Octopus, it changed @@legs in Animal and, by extension, @@legs in Llama.  (Technically, if Animal doesn’t define a class variable, Llama and Octopus won’t share that variable.  But going down that path is just begging for trouble, because you never know when someone down the road will add @@legs to Animal and open up a huge can of worms.)  I have heard this described as “leaky inheritance,” though I have yet to see it in writing.

Class variables, it seems, are really best for situations when you want to have each member of an inheritance hierarchy to be able to access the same variable.  That might be useful for configuration.  For example, let’s say each animal has a speak method which it defines, and it can speak verbosely or concisely (for a Dog, “WOOF!  WOOF WOOF WOOF!” vs “WOOF!”).  Perhaps we want to change one setting in Animal and have that apply to all animals.  In that case, we would do something like this (irrelevant code removed for now):


class Animal
@@config = {}
def self.config
@@config
end
def speak
if self.class.config[:verbose] == true
verbose_speech
else
brief_speech
end
end
def verbose_speech
''
end
def brief_speech
''
end
end
class Dog < Animal
def verbose_speech
"WOOF! WOOF WOOF WOOF!"
end
def brief_speech
"WOOF!"
end
end
Dog.new.speak # => "WOOF!"
Animal.config[:verbose] = true
Dog.new.speak # => "WOOF! WOOF WOOF WOOF!"

So that works great.  But we need to do something about @@legs.  So here’s the next option, which works well.  Let’s change @@legs to a constant, LEGS:


# IRRELEVANT CODE FOR THIS EXAMPLE HAS BEEN REMOVED
class Animal
LEGS = 4
def legs
self.class::LEGS
end
end
class Octopus < Animal
LEGS = 8
end
class Llama < Animal
end
Octopus.new.legs # => 8
Llama.new.legs # => 4

view raw

animals_2.rb

hosted with ❤ by GitHub

Note how we now access LEGS as self.class::LEGS.  This is critical.  If we accessed it as LEGS without adding self.class::, we would be referencing the LEGS variable in the scope where the method was defined, i.e. Animal.  Instead, we tell the method to reference LEGS as it is defined within the scope of the current class.

Alright, we’ve taken care of legs, but let’s consider another issue.  What about our tallying object?  Right now, Animal has an @@animals variable which contains all the animals in our zoo.  This presents 2 problems:

1) What if a later programmer decides to call the container @@animals in the Elephant class?  Suddenly we’ve entered a world of hurt.

2) On a more fundamental level – does it make sense for Octopus to have access to @@animals, even theoretically?  It should be blissfully unaware of the Lions and Tigers and Bears throughout the zoo, and just know about the 8-legged ocean critters.  How can we make this happen?

We can solve problem 1 by simply replacing the array @@animals with a constant, ANIMALS.  Hence, subclasses that define their own array of animals won’t generate a conflict.  However, despite seeing others advocate for it, I don’t like that solution either, for 3 reasons:

1) Now we have a different problem.  If the designer of the Elephant class neglects to define an ANIMALS constant but still adds to the ANIMALS array, the parent class’s array will be affected.  This may be difficult to debug.

2) It’s true that Ruby doesn’t complain about changing the contents of a constant array, because the object hasn’t been fundamentally redefined.  That doesn’t mean it’s the right thing to do.  Others will disagree (and in fact Rails apparently does this all the time), but I maintain that constants should be constant and predictable.

3) Constants are easily accessible from outside the class.  Now, I know that everything in Ruby, even private methods, is accessible, but there’s a semantic point here.  Where in the Ruby core classes do you find constants?  My first thought is in the Math module, which contains the constants PI and E.  In other words, constants are meant to be values which are definitional to the class and/or should never change once defined.  PI and E are not going anywhere.  Similarly, it makes sense to say that Llama::LEGS is 4 and Octopus::LEGS is 8, since those are attributes that should apply in all but the most exceptional cases.  (My apologies to Larry the 3-legged llama.)

The animals array, on the other hand, is not at all fundamental.  It’s a variable that is changed frequently, and should be associated with the class, but not easily accessible from outside, and not shared with subclasses.

So what’s the right answer?  Well, let’s remind ourselves for a moment that everything in Ruby is an object.  It turns out that even classes are objects – instances of the Class class.  (Sidebar: if you want to really warp your brain, enter Class.class into IRB.  Yep, Class is an instance of itself!  Mind blown.)  So if classes are instances, surely they have instance variables, right?  Yes, they do.  And we can use them to implement a safe working version of our animals array!


# IRRELEVANT CODE EXCISED
class Animal
@animals = []
def self.animals
@animals
end
def initialize(args={})
Animal.animals << self
after_initialize(args)
end
def after_initialize(args)
end
def self.all
self.animals
end
end
class Lion < Animal
@animals = []
def after_initialize(args)
self.class.animals << self
end
end
Lion.new
Animal.all # => [#<Lion:0x0000010187de60>]
Animal.all.object_id # => 2160486800
Lion.all # [#<Lion:0x0000010187de60>]
Lion.all.object_id # => 2160342160

view raw

animals_3.rb

hosted with ❤ by GitHub

Note that this was a bit tricky.  We had to define a getter method for the animals array.  If we have a number of such variables, we would probably be best off using attr_accessor, but the call to attr_accessor has to be within the context of a class << self ... end (singleton class) block.

On the other hand, we’ve essentially established the animal-tracking system in the parent class, and we can take advantage of it in children by giving each its own @animals array as a class instance variable.

Alright, dear readers.  The time has come to leave you with the final, comprehensive version of our zoo.  Just don’t feed the animals!


class Animal
@animals = []
LEGS = 4
class << self
attr_reader :animals
alias :all :animals
end
def initialize(args={})
Animal.animals << self
after_initialize(args)
end
def after_initialize(args)
end
def legs
self.class::LEGS
end
end
class Octopus < Animal
@animals = []
LEGS = 8
def after_initialize(args={})
self.class.animals << self
end
end
class Llama < Animal
@animals = []
def after_initialize(args={})
self.class.animals << self
end
end
Octopus.new.legs # => 8
Llama.new.legs # => 4
Animal.all # => [#<Octopus:0x000001010ef220>,#<Llama:0x000001010a6868>]
Octopus.all # => [#<Octopus:0x000001010ef220>]
Llama.all # => [#<Llama:0x000001010a6868>]

As always, comments and thoughts are most welcome.  Stay classy, Rubyists!

CoffeeScript 101

“CoffeeScript, c’mon and/ take a sip, they call it/ CoffeeScript, Coff-”

– oh, sorry, didn’t see you there! I was just humming the jingle from CodeSchool’s CoffeeScript course. Been working on it for a few days. I’ve never been a huge fan of the brown caffeinated stuff, but CoffeeScript? I’m addicted.

CoffeeScript is described by its creator, Jeremy Ashkenas, as “a little language that compiles into JavaScript.” Here’s how I would describe it: “JavaScript is written to give you a brain hemorrhage. CoffeeScript is more like a mild migraine.”

Essentially, CoffeeScript is a language that compiles 1-to-1 to JavaScript, but is more clear and less error-prone. Forget the dreaded var keyword; it has no place in the wonderful world of CoffeeScript, because it’s added automatically.  I like semicolons in English sentences; however, in the world of JavaScript, it’s difficult to remember every semicolon.  Thankfully, Automatic Semicolon Insertion will usually take care of it, but it can lead to unexpected results.  With CoffeeScript, no more semicolons!  And those pesky braces ({}) appearing all over the place?  Gone!

Now, some would say, “Hey, what are you doing with my beautiful JavaScript?  It was so precise, so explicit!”  I would tell them to go try Ruby and understand that extraBoilerplate !== greaterPrecision (I wrote that in JS so they would understand).  Or, as you would write it in CoffeeScript, extraBoilerplate isnt greaterPrecision. (Yes, the ‘ was left out of isnt on purpose – that’s how it’s spelled in CoffeeScript.)

Just to demonstrate how awesome CoffeeScript is, I’m going to write the rest of this post in CoffeeScript to show that it’s really much simpler.


class Reader
  inAttendance: yes
  payAttention: ->
    alert 'Wake up and pay attention!'

you = new Reader
you.payAttention()


class DemoOfCoolThingsAboutCoffeeScript

  functions: ->
    console.log 'As you can see, functions are defined without ' +
    '"function()" or "{}"s. Just a simple "->" - but make sure' +
    ' to keep track of your indentations!'

  classes: ->
    console.log 'It has classes. No more awkward JS inheritance!'

  punctuation: ->
    console.log "Have you noticed that I've been leaving out commas" +
    " and semicolons and braces? Indentation is way more natural..." +
    "\nAlso, see how parentheses are unnecessary on the " +
    "outermost function call?"

  splats: (params...)->
    console.log "I can splat arguments, in both function definitions " +
    "and function calls. In this case, I used #{params.length} params." +
    " Oh, did we mention string interpolation?"

  conditionals: ->
    switchVar = on
    if switchVar
      @showHowThisWorks(yes)
    else
      console.log 'The switch is off!'

  showHowThisWorks: (comingFromSwitch...)->
    if comingFromSwitch[0]
      console.log 'This function was called from switch using "@", ' +
      'which is a handy substitute for "this"'

  makingObjects: ->
    aboutMe =
      name: "Ariel Caplan"
      twitter: "@amcaplan"
      field: "software development"
      enjoysLongWalksOnTheBeach: yes
    if aboutMe.enjoysLongWalksOnTheBeach
      console.log "#{aboutMe.name}, what is this, a personals ad?"
    else
      console.log "#{aboutMe.name}, do you have no heart?"

  implicitReturns: ->
    returningFunction = ->
      "Hey, I never explicitly returned anything! How did you get this string?"
    console.log returningFunction()

  runEverything: ->
    @[propName]() for propName of this when propName isnt 'runEverything'

d = new DemoOfCoolThingsAboutCoffeeScript
d.runEverything()

Still JS-y syntax (it’s just impossible to escape), but isn’t it at least a bit clearer?

Hopefully this has been a pleasant little introduction to CoffeeScript.  You can run the code on CoffeeScript’s website here.  (Click “run” on the top-right, and watch what happens in your console!)  And while you’re there, read up on the language and all its features, try writing some of your own in the “Try CoffeeScript” modal, and maybe even take the CodeSchool course.  You won’t regret it!

P.S. Bonus extra life!!! Check out some real-life jQuery/CoffeeScript action in the code for the Flatiron Showcase website. I have some simple DOM manipulation stuff that I just converted to CoffeeScript yesterday. Check it out on Github!

Using Helper Methods to DRY Up Rails Forms

Helpers are a pretty nifty feature of Rails. And I’m not just talking about the built-in form helpers and the like, though those are awesome. I’m talking about the fact that you can custom-build your own helper methods to clean up repetitive content. Building your own helpers can be a bit tricky, though, so let’s first review a basic Rails rule that is likely to trip you up. Here are some things Rails doesn’t like:

  1. <
  2. >

Yup, Rails isn’t a big fan of HTML markup, unless it’s generated directly from the HTML in a view, or by one of the built-in Rails helper methods.

No, no, don’t get angry at Rails!!!  It’s for your own good, to make sure that you don’t accidentally run some sort of evil, malicious script that a user input into a form or submitted in some other way.

Luckily, Rails has a method called raw which will convert a String into an ActiveSupport::SafeBuffer object (this is the equivalent of typing "string-contents".html_safe).  The object is marked such that Rails knows not to escape its contents.  (See Henning Koch’s explanation for more details.)

So this makes sense so far.  And now we understand how Rails’s built-in helpers don’t have the HTML-escaping problem: they mark their contents as HTML-safe.

Bottom line of Part 1: You can use raw("string") to allow unescaped HTML into your view.  But make sure there’s nothing in the String that’s input by the user.  If there’s a piece that needs sanitizing but the rest needs to be raw to work, first sanitize("user input") and then raw("<HTML-element>sanitized user input</HTML-element>").  Another method that may occasionally come in handy is escape_once("html stuff"), which will recognize sanitized pieces and not sanitize them again, but will sanitize the rest.  Hence, &amp; won’t end up multiplied to &amp;amp; (because, y’know, we’ve all been there).

OK, so now you know how to make sure the right strings, and only the right strings, are sanitized.  But when are custom helpers going to actually be useful in putting together a page?

I recently refactored a project I’ve been working on, to try DRYing up my code using custom helpers.  I found 3 major benefits:

  1. Write less code
  2. Avoid repeating class assignments
  3. Easier standardization of the look of the page

The first is pretty straightforward. More code lumped into a single method call means less code overall. The second is a matter of making it easier for the developer to change the classes of lots of DOM elements just by modifying the helper. The third is the result for the user: a page which, by repeatedly calling on a single helper method, is more likely to have elements that properly resemble each other.

Let’s illustrate with a couple of examples. In the first, we have a form with a bunch of tabs. I wanted to consolidate the code for the tabs, because there’s lots of repeating pieces. Here’s what I did:

<div class="content active" id="guests">
<%= render partial: 'guests_form', locals: {f: f} %>
</div>
<div class="content" id="topic">
<%= render partial: 'topics_form', locals: {f: f} %>
</div>
<div class="content" id="food">
<%= render partial: 'menu_form', locals: {f: f} %>
</div>
<div class="content" id="message">
<%= render partial: 'message_form', locals: {f: f} %>
</div>
<div class="content" id="time">
<%= render partial: 'time_form', locals: {f: f} %>
</div>

became

<%= content_div("guests", "guests_form", "active", f) %>
<%= content_div("topic", "topics_form", f) %>
<%= content_div("food", "menu_form", f) %>
<%= content_div("message", "message_form", f) %>
<%= content_div("time", "time_form", f) %>

using the helper method

module MealsHelper
def content_div(id, partial_name, extra_class = nil, f)
content_tag :div, (render partial: partial_name, locals: {f: f}),
class: "content #{extra_class}", id: id
end
end

Now let’s break it down. I used content_tag, which takes 3 arguments: tag type (div in this case), content (render etc.), and an options hash. It generates a string of HTML that fits the criteria and marks off the contents as HTML-safe. Hence, I don’t have to raw it. I also didn’t have to call raw on the second argument, since render also returns an ActiveSupport::SafeBuffer object.

One could argue that the short form is less semantic than the long form. In truth, I’m inclined to agree. I grew up on HTML, and it looks much cleaner to my eyes than using the helper. However, I have to admit that using the helper makes it less likely for elements to end up differing from each other in ways that could break the layout or cause a JavaScript bug. Ultimately, I’m not sure there’s one right answer. But it’s good to be aware of multiple tools, and actively choose between them.

Here’s another example, from one of the partials of the above form, where the user chooses guests to invite. Here’s the original code:

<% @people.each_with_index do |person, index| %>
<div class="row">
<%= f.fields_for(person) do |ff| %>
<div class="medium-4 small-12 columns">
Name: <%= ff.text_field :name, name: "person[][name]" %>
</div>
<div class="medium-4 small-12 columns">
Email: <%= ff.text_field :email, name: "person[][email]" %>
</div>
<div class="medium-4 small-12 columns">
<% mp = person.meal_people.where(meal: @meal).first %>
Relationship: <%= select_tag(:host_relationship,
options_for_select(['friend','relative','neighbor',
'coworker', 'student','teacher','clergy', 'other'],
[(mp.host_relationship if mp)]),
name: "person[][host_relationship]",
prompt: "Who is s/he to you?") %><br>
</div>
<%= raw("<hr>") unless index == @people.length - 1 %>
<% end %>
</div>
<% end %>

The modified code:

<% @people.each_with_index do |person, index| %>
<div class="row">
<%= f.fields_for(person) do |ff| %>
<%= person_field("Name:#{ff.text_field :name, name: "person[][name]"}") %>
<%= person_field("Email:#{ff.text_field :email, name: "person[][email]"}") %>
<% mp = person.meal_people.where(meal: @meal).first %>
<%= person_field do %>
Relationship:
<%= select_tag(:host_relationship,
options_for_select(['friend','relative','neighbor',
'coworker', 'student','teacher','clergy', 'other'],
[(mp.host_relationship if mp)]),
name: "person[][host_relationship]",
prompt: "Who is s/he to you?") %>
<% end %>
<br>
<%= tag(:hr) unless index == @people.length - 1 %>
<% end %>
</div>
<% end %>

And the helper method, also in MealsHelper:

def person_field(text = nil, &block)
content_tag(:div, raw(text), class: "medium-4 small-12 columns", &block)
end

What’s happening here is a little complicated, so let’s isolate one case:

<div class="medium-4 small-12 columns">
  Name: <%= ff.text_field :name, name: "person[][name]" %>
</div>

turns into

<%= person_field("Name:#{ff.text_field :name, name: "person[][name]"}") %>

So we’ve assumed each person_field will have a bunch of the same classes (for CSS purposes), and just isolate the unique things for each field. The helper method fills in the classes. This way, if I ever want to change the look of the person fields, I have one address to do it from!

Also note that the method takes the block and passes it in as the final parameter to content_tag. This is a built-in feature of content_tag – it will take a string or a block and stick whichever one between the tags it builds. Hence, in the last form element (relationship), the method gets a block rather than a string, and it works just fine.

One final useful note: look at line 17 of the updated version. See tag(:hr)? That’s another helper offered by Rails, and it totally beats the alternative: raw("<hr>"). It’s nice to not have to raw things up. Whether you love or hate view helpers, it’s still important to recognize and know how to use the built-in helper methods, because they will come in handy in plain old views for avoiding the problems caused by Rails’ automatic sanitization.

Exploring Security and Secret Tokens Through Facebook Login

Security is really scary.  How scary?  Well, according to this very pretty infographic, it costs US residents $13.3 billion and 383 million hours per year.  And you don’t want to be the one people are pointing fingers at when there is a data breach.  So it’s really important to understand at least the basics of security – if not all the details, then at least some basic points of entry for hackers.

I’ve been working on a project for my upcoming presentation (next week!) at the Flatiron School, and I decided to use Facebook authentication.  This makes sense because users will generally have Facebook logins already, so the barrier to entry is lowered, and I don’t have the responsibility of taking care of a database of user passwords (or password hashes).  However, I needed to take care of a few things in order to make this happen.

First, I registered a new app with Facebook.  The process was pretty simple – took me about 3 minutes – and I had an app ID and secret key ready to go.  Then I followed the steps on this fantastic blog post to integrate Facebook login with my app using OmniAuth and the Facebook OmniAuth gem.  Et voilà, I can seamlessly bring in Facebook users!

However, there was something that still needed to be taken care of to avoid security vulnerabilities popping up.  My config/initializers folder now included 2 files which would be dangerous to expose in public by posting to Github.  These files are:

omniauth.rb – added for use with OmniAuth, it includes the App ID and Secret Key for Facebook)

secret_token.rb – included in a standard Rails app, used to authenticate the session sent by the user

I checked the initialize directory out of version control, since it’s mostly standard files, and these were the non-standard files and needed to be secret, there was nothing that desperately needed to be pushed to Github.

But this wasn’t ideal either.  Let me explain.

Interestingly, the default code for secret_token.rb includes the following comment: “Make sure your secret_key_base is kept private if you’re sharing your code publicly.”  So they tell you to hide it, but don’t hide it by default.  Why is that?  According to this Google Groups discussion (and it makes sense when you think about it), hiding the file would then break upload to Heroku or any other service that uses Git for deployment.  So the key is to keep it in .gitignore while you’re developing, then add to Git on a deploy.  But then if you continue development, the secret token will be in the commit history, and that will be available on Github!  Major problem.

Well, one solution is to just regenerate the secret key every time you deploy; there is a Rake task for that.  So you could regenerate the secret key, move the master branch ahead by one commit and deploy that, then keep working from the previous commit with the old secret key, so the current secret key doesn’t get to Github.  But this is a pain, and an extra step to remember!

New Zealander David Fone suggests an alternative solution: set the secret key manually in testing and development, and set it on the server in production!  How does this look in practice?  Here’s your secret_token.rb (updated by me for Rails 4):

if Rails.env.development? or Rails.env.test?
  MyApp::Application.config.secret_key_base = ('x' * 30)
else
  MyApp::Application.config.secret_key_base = ENV['SECRET_TOKEN']
end

So whenever you’re working on your own computer, the secret token is just a string of 30 ‘x’es. That seems kinda stupid, but it definitely reminds you, the developer, that whatever secret key you would be using in testing/development just isn’t secure. When you move your application to the production environment, you have to then use the host’s tools to input or produce a secret token. In the case of Heroku, this is done with one command:

heroku config:set SECRET_TOKEN=3eb6db5a9026c54... (fill in a full-length secret token, you get the idea)

So now the production code is secure and unexposed, and you can keep developing with your 30x token.

Finally, one important question. Why is all this secret token stuff so important anyway?  By default, Rails stores sessions on the client’s computer.  This means that the user can access the session’s content, decipher it easily from Base 64 (since it’s not encrypted in any way), and potentially modify it before the next request!  Rails avoids this pitfall by having every session end with a digest that is calculated using the session data and the secret token.  So if the user changes the session data, the digest no longer matches the session data, and Rails knows something is fishy.  It’s highly unlikely that a user will be able to guess the secret token and create a new digest, so your session is ultimately safe, as long as your secret token hasn’t been compromised.  But if someone else finds out the secret token, they can easily modify their sessions and create new digests (though the process to modify a session is still somewhat difficult, but ultimately it’s doable).

Either way, it’s worth noting that the user is able to see the session information; Rails secret tokens just prevent the user from modifying the session information (e.g. changing the user id) and getting away with it.  So don’t store information in the session that you don’t want users to see!  In any situation where you might put sensitive information into a session – don’t!  Keep it in a database with an easy way to access it based on the information contained in the session.

So the ultimate take-aways are:

1) Authenticating with services that use OmniAuth is very straightforward (though see here for a terrifying blog post about how an attacker can use CSRF to take over an account that has internal login plus Facebook login, or any other OmniAuth login)

2) Don’t commit your actual production secret token to Github or anywhere else; there are ways to avoid it without too much hassle.

3) Don’t store information in the session if having a user see it would constitute a security breach.

Struct: Ruby’s Quickie Class

Let’s say you have Player and BasketballTeam classes that are defined and used as follows:

class Player
attr_accessor :name, :number
def initialize(name, number)
@name = name
@number = number
end
end
class BasketballTeam
attr_accessor :player1, :player2, :player3, :player4, :player5
def initialize(player1, player2, player3, player4, player5)
@player1 = player1
@player2 = player2
@player3 = player3
@player4 = player4
@player5 = player5
end
def starting_lineup
str = "Ladies and Gentlemen, here is the starting lineup!\n"
5.times do |num|
player = self.send("player#{num + 1}")
str += "\n##{player.number}, #{player.name}!\n"
end
str
end
end
team = BasketballTeam.new(Player.new("Magic Johnson", 15), Player.new("Michael Jordan", 9),
Player.new("Larry Bird", 7),Player.new("Charles Barkley", 14),Player.new("Patrick Ewing", 6))
puts team.starting_lineup

In this case, since there are always exactly 5 players, I don’t want to pull out an array every time and write team.players[0], and instead I’ve chosen to use 5 similarly named instance variables, so I can do team.player1. This looks nice, but also isn’t ideal. If I want to access player n, this starts to get ugly: team.send("player#{n}").

Well, here’s the good news: as usual, Ruby has a better way for you to do it. Introducing: the Struct class! Structs fall somewhere between full-fledged Ruby classes and arrays/hashes, and are excellent for generating classes which are mostly variable storage containers with a particular number of items, with a small number of methods. Here is how we would refactor our code from before:

Player = Struct.new(:name, :number)
BasketballTeam = Struct.new(:player1, :player2, :player3, :player4, :player5) do
def starting_lineup
"Ladies and Gentlemen, here is the starting lineup!\n" +
self.collect {|player| "\n##{player.number}, #{player.name}!\n"}.join
end
end
team = BasketballTeam.new(Player.new("Magic Johnson", 15), Player.new("Michael Jordan", 9),
Player.new("Larry Bird", 7),Player.new("Charles Barkley", 14),Player.new("Patrick Ewing", 6))
puts team.starting_lineup

Huh? Where did all the code go?

Struct.new is a really cool method that takes symbols as arguments and returns – no, it’s not an object, it’s a class!!! (Well, technically all Ruby classes are objects too, but we’re going to deliberately ignore that for now.) It takes each symbol, makes it an instance variable, gives it setter and getter methods, and adds it to the initialize method in the order specified. So it’s doing a lot of work for you, just for adding the symbol there. The optional block at the end (see how BasketballTeam is created with a block but Player isn’t?) specifies any methods you want to add to the struct. If you have a lot of these, Struct probably isn’t for you. But if it’s just one or two simple methods, then Struct may still be a good idea.

An examination of Struct’s instance methods reveals its similarity to Array and Hash. Here are my favorites:

Method Description and Correlatives
#members like Hash#keys, returns an array containing the instance variable names
#values like Hash#values, returns an array containing the instance variable values
#length, #size like Hash#size or Array#size, the number of instance variables
#each similar to Hash#each, goes through each instance variable’s value
#[member]
(e.g. team["player1"] or team[:player1])
similar to Hash#[], access by instance variable name
#[index]
(e.g. team[0])
similar to Array#[], access by variable index in #members

NOTE: You can also write team[0] = Player.new("Magic Johnson", 15)

Of course, you are also able to get team.player1 because it attr_accessor’ed everything for you.

Because Struct defines an #each method and includes Enumerable, you can use any of the Enumerable methods on its properties. So you can cycle, check if team.any? {|player| player.name == "Michael Jordan"}, inject, or find the team.max_by(&:number), among others. You can also modify all contained values pretty easily: team.each{|player| player.number += 1} (in case you needed to bump up everyone’s number for some reason). And if the IOC is insisting you sort your players by jersey number, just team.sort_by(&:number) and you’re all set! Patrick Ewing, with jersey #6, is now team[0], a.k.a. team.player1.

One downside of Struct as opposed to Arrays is that you can’t push/pop/unshift/shift, because the size is fixed from the beginning.

TL;DR A struct is somewhere between a regular object and a hash/array. It’s an awesome data structure when you

  • know exactly what it needs to hold
  • want to be able to access your data in a variety of useful ways
  • need to define just a small number of custom methods (or none at all)
  • and just don’t want to write much boilerplate code while doing it!

P.S. Check out this post from Steve Klabnik about how incorporating structs into your regular class definitions can make your debugging much easier due to Struct’s handy #to_s method.

P.P.S. Robert Klemme helpfully notes that, unlike hashes, struct[“something”] will raise an error if there is no @something variable. This can be helpful if you want to detect certain types of input problems.

P.P.P.S. Here’s the output from the code above (using structs or regular classes), if you’re desperately interested:

Ladies and Gentlemen, here is the starting lineup!

#15, Magic Johnson!

#9, Michael Jordan!

#7, Larry Bird!

#14, Charles Barkley!

#6, Patrick Ewing!

Lessons from a Failed Successful Gem

One of our mottos at Flatiron is “Celebrate failure.”  We aren’t trying to get it right immediately – it’s all about trying something, making it work, and then improving on it.

I recently published a Ruby Gem called CheckEverything (the source code is here and the gem can be installed by typing ‘gem install check_everything‘ into your Bash console).

Over the course of creating this gem, I’ve made some mistakes, and learned a few lessons:

1. Abstract and Keep it DRY

This one I always knew, but it’s more apparent from working on a larger project.  Make methods for any of three reasons:

a) Don’t Repeat Yourself: don’t unnecessarily write the same code multiple times
b) abstract to keep your code clean and understandable
c) reference values through a method so one change to the method will be reflected in many places in your code

I’ve learned that as methods get longer, they become less understandable and require more comments.  Names of helper methods essentially comment themselves, and add clarity to the method calling the helper method.

Having lots of methods is often helpful in debugging.  When you create a new method, or modify it, it is usually much easier to isolate where something went wrong.  You will often be able to figure out a few options for where the error is creeping in, and it’s pretty easy to check the output of a particular method.  If they’re well-named, you should be able to locate functionality quickly and perform a surgical strike on the problem.

2. Test Early and Test Often

Tests are really important.  I’m going to say it again ten times to emphasize this.

Tests are really important.  Tests are really important.  Tests are really important.  Tests are really important.  Tests are really important.  Tests are really important.  Tests are really important.  Tests are really important.  Tests are really important.  Tests are really important.

Do we get the idea?  The point of testing is clear.  But to a novice programmer, the idea of testing frequently is far from obvious.  Here’s why it makes sense to test ALL. THE. TIME.

Let’s say you write a program that’s 200 lines long, and then you test it.  You get this feedback as soon as you run it:

rub:200: syntax error, unexpected $end, expecting keyword_end

This is a major problem.  Sure, Ruby thinks the “end” is missing way down, but it turns out you have a block on line 36 that wasn’t properly “end”ed.  And you probably first made the mistake because you didn’t indent properly, so it will be impossible to find.

Let’s say, however, that you were smart and tested every time you added a new method or made any significant (not necessarily major) modification.  That’s great!  You’ll have a narrow window to search for the problem, and you won’t have to spend hours looking for the missing keyword.  (This is even more true in languages like Java where semicolons are required at the end of every line; finding that missing semicolon can be a nightmare.)

If your error is more complex, this is even more important.  In short:

Build up your program bit by bit, so you can understand what each part actually does – not just what you thought it would do.

3. Ruby Gems Rock!

If there’s a complex task you want to perform, especially if it’s a common need, search a bit and try to find out if there’s a Ruby Gem that will take care of it for you.  I used Nokogiri to scrape the Ruby website for class names.  I probably could have done it on my own, but why bother, if Nokogiri does it for me?  A little practice with scraping, and it was fairly straightforward.

Luckily, the Ruby community seems to have taken up the Principle of Least Astonishment, so a good gem will hopefully be fairly easy to learn to use.  Invest a few minutes in checking out pre-existing tools before you decide to build your own.

4. Ruby Gems Aren’t a Panacea

Unfortunately, there isn’t a gem for everything.  So if you don’t see a gem that you think should exist, make one!  Which brings me to…

5. Split Up Functionality!

If there’s something in your gem that could be used in ways aside from what you want to do, split up the gem.  If you’re publishing a gem for general use, divide the functionality into classes which can be used independently of each other.  Nokogiri is, I think, a fantastic example of this.  It includes multiple classes for parsing different file types.

On the other hand, if your gem is specialized, but some of the code could be used in a variety of ways, consider publishing 2 gems – one for the basic code, and one for your specialized program.  For example, let’s say you are publishing a gem that finds pictures of cats online and turns them into pictures of exploding cats.  You can probably split up the gem into a PictureExploder gem which turns pictures into pictures of explosions, and a CatExploder gem which webcrawls for lolcats and invokes the PictureExploder class to turn them into explosions.  Then, if someone wants to make a TypewriterExploder gem to make exploding typewriter pictures, half the work is done already!

This of course leads to…

6. Be Open-Minded

Don’t be afraid to change directions.  This is certainly true on the small scale, in terms of the “how” – the way your gem accomplishes its goal, the objects and methods and iterations.  However, it’s also true in terms of the “what” – what your gem can accomplish.

Initially, I intended to write a gem that would store a user’s favorite websites and launch them all with a single command.  (For example, `check_everything morning` would launch any website the user had included in the category ‘morning’.)  Then I realized I could add much more practical functionality with a few additions:

a) scrape the Ruby website for class names
b) store the class names in a file that could be cross-checked
c) allow the user to input a Ruby class, recognize the class name, and spit out the website for that class

I then let things develop further, and at this point it will accept input like `check_everything array#map` and launch the page for that class, targeting the id associated with the method.

So at this point, it’s a pretty awesome gem.  Now, here’s the problem: I like having both of those features.  But a gem shouldn’t really have that sort of dual functionality.  So the answer at this point is probably to split off into 2 gems, and possibly 3 if they share enough code.  Am I going to do it?  Maybe, maybe not.  After all, the Flatiron School is keeping me pretty busy.

But this problem is associated with tip #5 – splitting up functionality.  The more each function is separated, the easier it is to tease everything apart.  Luckily, thanks to tip #1 (abstracting), much of that has already been done.  Most of the code is either applicable to both Ruby Doc links and user-specific links, or has a separate method for each group where the logic diverges.  So when that task comes, it will be easier to do – just make 2 copies, and remove logic specific to each set of links from one or the other.  The hard part is going into shared methods that include logic for each set of links, but if that work is mostly done, the task shouldn’t be impossible.

Finally…

7. Be Inspired!

I would really like to add another bit of functionality to my gem: you can choose to either launch the documentation, or just display it in your command line.  Unfortunately, there doesn’t seem to be a gem that displays web pages.  So now I have a new dream: build a text-based browser written in Ruby!  At least sophisticated enough to display a page and then return to your previously running program.  (When?  I’m not sure, but I will need a lot of help!)

In short, while writing gems, you may discover a great idea for a gem that would be super-useful, and no one has done before.  Be bold!  Be that person who takes the next step!