Ruby > extend vs include

In attempt to dry up some code I was building a tree of modules without much success. I’m going to write this down because I KNOW I will do the same mistake tomorrow.

module A
  def greeting
    puts "hello!"

class ExampleIncluded
  include A

class ExampleExtended
  extend A

Cool. So ExampleIncluded.greeting won’t work and will work. And vice versa for ExampleExtended. Okay here’s why.

When you extend a module you’re basically saying. Hey module all of your instance methods ( methods defined like so: def foo; end ) add those as class methods. When you include something you say hey module add your instance methods to my instance methods list. Cool so far so good. What I was trying to do without much success:

module Common
  def share
    puts "please share!"

  def self.share_also
    puts "hi i'm a class method!"

class ExampleIncluded
  include Common

class ExampleExtended
  include Common

Welp I wanted to call ExampleIncluded.share_also. But nope that gave me a no method error. Instead I had to call ExampleIncluded::Common.share_also. I get a nice fancy warning along with it as well: “Warning top level Constant referenced by ExampleIncluded::Common” but at least it runs share_also

Basically you have to include/exclude modules individually. To rewrite this:

module Common
  module I
    def share
      puts "please share!"

  module C
    def share_also
      puts "hi i'm a class method!"


class Example
  include Common::I
  extend Common::C

Not entirely sure why it’s implemented this way, but I suppose it makes you more aware of what is going where. Seems a bit odd to me though why you would be able to call ExampleIncluded::Common.share_also. I’m still pretty new to this, so if I’m wrong by all means please let me know =)


Okay so I did some reading and meta_programming FTW

So there is a call back that exists in modules that runs whenever you extend or include a module.

module A
  def A.extended(mod)
    # Do crazy stuff

The parameter that included receives is the module/class that includes module A. Well what can I do with that? You can create class or instance methods!
So when we’re inside of the block (where I commented #Do crazy stuff):

def hello
  puts "greeting"

This will actually create a class method. But what if I want to create an instance method? Welp:

mod.send(:define_method, :hello, -> () { puts "greeting" })

BOOM we just made a instance method on a class. The reason we have to use the send method instead of just doing mod.define_method is because define_method is a private method. Yeah there’s a way around that too. Wrong way? Please correct me!

Five months in and still learning

Yup fell through with this blog thing haven’t I?

What have I learned from the last time I posted something?

- Twitter is awesome, I just witnessed an interesting conversation about reactor pattern and threading in ruby. It all started by asking a simple question.

- Reactor pattern.

- Node is built on V8

- Rails Engines

- Volunteering at devOpsDays

- exercise is a must!

Have not learned workman/Dvorak. Some may argue that it may be a disability to type faster. Even if I did know how to type faster would I be able to think code fast enough to keep up? My mind can barely keep up on what I am typing!

Have not been able to read enough books =\ no excuses.

I want to rebuild this blog in rails. That way I can learn the devOps side of things.

Ruby – Metaprogramming

I started working at Mass Relevance last week four weeks ago ( I have been slacking on this blog post ) and I have learned a ton! Specifically how awesomely flexible Ruby is.

1) Private methods can be access via send method.

class Cat
  def meow
    puts "meow"

my_cat =
my_cat.send(:meow) #=> "meow"

2) Define/remove methods on the fly

class Cat

# define_method is a private method
# which is why we need send

Cat.send(:define_method, :meow){ puts "meow"}

my_cat =
my_cat.meow #=> "meow"

Cat.send(:remove_method, :meow)

my_cat.meow #=> undefined method meow

3) Including modules on the fly

module Tricks
  def speak
    puts "meow!"

class Cat
  def learn_to_speak
    class << self
      include Tricks

my_cat =
my_cat.speak #=> undefined method speak
my_cat.speak #=> "meow!"

# This also works
Cat.send(:include, Tricks)

4) Adding a variable module on the fly
I didn’t actually read about this, kind of just put the pieces together.

module Tricks
  def speak
    puts "meow!"

module Be_Mean
  def bite
    puts "BITES YOUR HAND OFF!!"

class Cat
  def learn_to(trick)
      self.class.send(:include, eval(trick))
      puts "Module does not exist"

my_cat =
my_cat.speak #=> "meow!"

Cat.included_modules #=> [Tricks, PP::ObjectMixin, Kernel]
my_cat.learn_to("Get_a_job") #=> "Module does not exist"

5) defining instance methods on specific instances
I made a mistake which then led me to this discovery

class Cat

my_cat =
my_cat.define_singleton_method(:greet) { puts "meow" }
my_cat.greet #=> "meow"

stray_cat =
stray_cat.greet #=> undefined method greet

Mind BlownEmma Stone - Mind Blown
Mind blown yet? Yeah mine too…oh and I’m a cat owner if you haven’t noticed by now…

Lazy Evaluation

I’ve heard about AMD ( asynchronous module definition ) before but until recently haven’t really looked into it. One of the cool things I read about was “lazy evaluation”. Say you have a ton of javascript, but the user never uses it because he doesn’t perform xyz task. Well you just wasted a whole bunch of time loading the script that never got used. So let’s do something hacky with it.

JS can evaluate strings. What that means is…

eval( 'alert("this will run")' )

This will run an alert with the words, this will run. How cool is that? Go ahead and try it! Copy paste it into your console. Please don’t make a liar out of me script!

So let’s say you have some cool animation script and it’s huge! Like 1mb! If the user never clicks on the play button, they don’t need the script, well TOO BAD!! The browser loads it anyway! Well if we wrap that animation script into a string the browser reads it but doesn’t process it, much like my days in English class. This saves a ton of time! So what happens when the user clicks play? We evaluate the string, duh! We just saved her a bunch of time on the front end. Even more so if she didn’t want to see our sad animation in first place!

The article I’m reading

Just on a side note, Ruby has a similar method. eval(string)…shocker…

While applying for jobs… I found a bug in a form.

So while out applying for a web-developer job I came a across a form which would not let me submit. It keep scrolling me back to a field which I had properly filled in. It didn’t have any error messages or anything. So I tried refreshing the browser which promptly killed all of my entries. So I refilled everything in again. Nothing. So I got smarter this time, I opened up a new window and did the old command-c command-v, perhaps I missed something! Nope. I got frustrated and some-what embarrassed. So I decided to see exactly what was stopping the form from being submitted. Into the javascript I dove and well… I found it….

				validURL : function() {
					selected.push(function() {
						return ((this.val().indexOf('http://') == 0) && (this.val().length > 10));

The form wasn’t submitting because the URL I was giving it started with https// instead of http//. This is a small and dangerous oversight. Especially because the field was asking for a website that generally uses SSL. Imagine if I were a client or a potential client. I probably would have given up after the 2nd try.

Lessons learned here: 1) MAKERSQUARE works! 2) Try to think of all possibilities and anticipate edge cases especially with forms. Have someone try using it. I typically ask my non-technical fiance. She tends to break anything electronic. Which gives me the perfect opportunity to be the hero of the day =) otherwise I’m useless around the house…sort of like a cat. 3) Looking at how other people set up their code is really really interesting. After seeing the script of this form I have a ton of questions for my instructors at MakerSquare =)

Keep learning, keep growing =)

Dear Cohort > 2, Take it from me!

I’m writing this post MakerSquare at 7:39AM the day after Career Day. Yes I know we don’t have class until 1pm. Yes I know I need to rest. And yes it has been an exhausting past few months. Little workers in my brain are running around figuring out where to store all the code mana`o I have gain the past few months. My brain is swollen. But this isn’t the end of the journey. This is the end of a small part of the beginning. I think now is a good time to share with the next cohort what worked best for me.

1: Sleep
It’s hard to believe I get any sleep. My round trip commute from Temple is about 3 hours a day. I leave home around 5:30AM and don’t get back until 8:00PM if I’m lucky. But no matter what, I try to get at least 7 hours of sleep. Your brain needs a timeout to grow and store all that brand new information you’ve just learned. You’re right, you could stay up to study, but are you really studying at your optimum level had you had 7-8 hours of sleep? I doubt it and so do experts around the country. You’re tired. You can’t focus and you quickly forget things. Remember where your keys are? Go to sleep! You’ll feel better and be more productive. Don’t believe me? Check out CDC’s website.

2: Exercise
This one was particularly difficult for myself. Because of my long commute I don’t have all the time in the world to exercise. So instead I bought a yoga DVD, AM Yoga. It’s 30 minutes and enough to get the blood flowing so my body doesn’t cramp up. Towards the end of the course I got sloppy and didn’t keep up with the yoga. My body complains more than I want to hear. My posture resembles a C more than an S. Needless to say I’m looking forward to going back to yoga, weight lifting and running on a regular basis. But why is exercise essential to learning? From what I remember in Brain Rules, exercise increases the amount of oxygen you intake. Cardio of course is the best, but John Medina even suggests walking 15 minutes a day will help the increase the flow of oxygen. Apparently our brains need a lot of that…

3: Life outside of code
Do something fun, do something exciting. Code will be a part of your life for the rest of your life. Don’t worry about it, it’ll still be here when you come back! For me it was spending time with the fiance and I couldn’t ask for anything more, even if she made me watch Mama Mia with her.

4: Code without an excuse!
The great thing about code is that the only thing you really need is your computer + google. When we first started to learn rails I needed setup a rails app without taking the shortcuts (scaffold, resources routes etc). It forced to me to really think about how the MVC model really worked. Okay I lost you. Remember this, learn code the hard way and you’ll learn faster and more efficient.

5: Learn how to use iTerm/Sublime hotkeys
Hotkeys are essential. The less time you spend gliding the mouse all over the place and the more time you keep your fingers on your keyboard the more efficient you will become. If you put two devs side by side talent being equal but one uses her mouse to navigate while the other strictly uses her hotkeys, the latter will be more efficient.

I did a screencast to prove my point. It’s my very first screencast. To be honest it’s really nerve wrecking, even if I’m not doing it live.

Here are my favorite hotkeys:


Search for files in your project directory: Command + t
This is vital when you begin to have a full grown web application. Thanks to the nature of inheritance of OOP, you’ll have a ton of different files with a ton of different code, navigating through that mess will save you tons of time!

Search for text in all files: Command + Shift + f
Say you’re looking for that one typo that is breaking your project. Or let’s say you forgot what this one particular message does. You can search for a specific text using Command + Shift + T and sublime will search all of your project files for whatever you give it. It can even take regex, sorry didn’t know you’re a BOSS!

Auto complete tags in HTML/CSS: tag name + tab
Let’s face it, html tags = pain. So type html + tab and you’ll have open and end html tags, LIKE MAGIC! Lorem ipsum works the same way, lorem + tab


Auto-complete – tab
Say you’re trying to get into a directory called supercalifragilisticexpialidocious, I had to Google it to make sure I spelled it right. No thanks, let me just type super hit tab and iterm will fill in the rest. Super! Let’s say we have another directory called super, no problem! iTerm will show you that there are two directories with similar names, hit tab again and you can choose which one with your arrow key or you could continue to type until the path name is unique.

Open directory or file in finder – open (filename or . for current directory)
Instead of clicking and dragging your file into chrome, instead type open index.html in iterm!

SizeUp (Hot keys are listed when you click on the icon on the top part of the menu.)
Manage your windows properly so you can have two things open side by side. I.e. Sublime + Chrome. Don’t know what I’m talking about? Can’t find it? Ask any instructor at MS and demand they tell you this 10,000 year old secret!

There are wayyy too many hotkeys for me to list, some I bet I don’t even know! But these I found to use these the most often.

I showed you mine, now show me yours! What are you favorite studying techniques or hotkeys?

Rails Pluralization

So the creators and editors of Rails placed a nifty pluralization (is that even a word?) engine which takes words and changes it to its plural form. I.e. Goose to Geese. Well this can become confusing when you’re creating variables. When we create a new model, the model name is singular and the class name of that model is also singular. But the table name is plural and so is the controller that deals with that particular model.

Bare with me. According to one of the MakerSquare TAs , Ricardo, if you had an array of numbers, you would call that array numbers. If you had an array of strings, you would call that array strings. Thus a table with multiple instances of the class would be a plural of whatever you have in there. So if you have a model called Movie, the table would be called Movies because it’s basically an array of movies.

At the beginning of Rails Guide I vaguely remember reading that while learning Rails we should do things the Rails way or we’ll have a difficult time.

In the route file, resources refers to the controller unless you tell it otherwise. For example when you’re dying for a controller to be in the singular form.

So if we were keeping track of books:

Model: Book
Model Class name: Book (used to access table data, Book.all, etc)

Rails Generate Model example
Controller: Books

Rails Generate Controller example
Table Name: Books

Screen Shot 2013-10-07 at 5.35.12 PM
Resources Route Name: Books (pointing to the controller)

Seeds of Success

During demos & drinks I met a very awesome guy, Trevor Rosen. He’s a software engineer rather than a sole language enthusiast. Which is exactly the level I want to get to. Don’t get me wrong, I love RoR and loving JS, but there is some truth to using the right tool for the right job. You wouldn’t use a screw driver to hammer something in, unless it’s a screwdriver/hammer. I asked him in an email for some advice. I didn’t get some advice, I got a whole bible of advice. I’d love to share some and interweave advice I’ve been hearing from my audiobooks during my 1.5 hour commute to Austin.

Stay Humble

“It’s hard.” - Trevor Rosen.  I can easily relate to that. The more I accomplish & learn the easier it is to disregard new ideas. Or the need to read a basic book or attend a workshop on a language I’m already comfortable with. For example I felt pretty comfortable about CSS until I met Elyse Holladay. “It can look right, and still be wrong.” This lesson deserves a blog post of it’s own.

Don’t be afraid to Experiment new things

In other words do not be afraid to fail. “Failure is an event not a person” – Zig Ziglar. I find myself doing all kinds of experiments on Chrome’s console and IRB just to figure out why something works one way. Just do it. Don’t sit there trying to see what works and what doesn’t.  Insert a whole army of console logs to find out exactly what is going on!Javascript - How to find out why your code is breaking.

I have not failed, I have found 10,000 ways that won’t work. – Thomas Edison

When you fail, because you will, get back up and try again. You will fail more times than you will succeed. Any successful person will tell you that. The secret to success is through failure.

Don’t climb the mountain, climb the next 20 feet.

Rome wasn’t build in a day. All great things take hard work and dedication. “Success doesn’t happen overnight; it’s a carefully planned blueprint, executed flawlessly.” – Zig Ziglar Success today seems like it happened overnight but really it’s because you’re just discovering it now. Back to the point, “Don’t focus on the prize, focus on the process” – Eric Thomas  “..get in the habit of saying to yourself — “OK, what’s the next ’20ft’?  I can do that much, right?”  And then do it again. And again.  When you do that, you will get momentum.  And momentum is *magic*.  I can’t stress that enough.  Learn to seek personal momentum through small victories — if you do that, you will be amazed at how much you get done subsequently.  I stress this to my direct reports all the time (I manage 7 developers).” - Trevor Rosen

This might be old news to you. But it does help to remember that “People often say that motivation doesn’t last. Well, neither does bathing – that’s why we recommend it daily.” - Ziglar

How I conquered the Library.

Our very first Friday project at MakerSquare was to build a Library using Ruby. Here were the requirements:

Basic Requirements

  • Users should be able to add books to a library
  • Books should be able to have information saved about them (author, title, description)
  • A user should be able to check out books from the library for one week intervals
  • A user should not be able to check out more than two books at any given time
  • Checked-out books should be associated with a user
  • Users with overdue books should not be able to request any new books until they turn all their overdue books in
  • Users should be able to check in books to the library when they’re finished with them
  • Users should be able to check a book’s status (e.g. available, checked out, overdue or lost)
  • Users should be able to see a list of who has checked out which book and when those books are due to be returned
  • Users should be able to see a list of books that are overdue

Daunting right? Thankfully I took it upon myself to create a “game” over the summer to prepare myself for MakerSquare. I made an ruby text-only console game. It took me about a good solid weekend to finish it but I’m glad I did it because my understanding of classes and modules excelled beyond just reading the docs.

I began by compiling the requirements needed and then drawing circles and lines to represent objects and their relation to each other. I still have the drawing but I need to take a picture of it. Shocking since I was a photographer and all…Beside the point, the drawing really help me visualize how my code needed to work. Along with the practice over the summer and my drawing I was able to finish the basic requirements and challenge myself to the extra credit work:

Extra Credit

  • Books should have optional attributes for year-published and edition
  • Users should be able to import a .csv file with a list of books to add to the library
  • Users should be able to leave reviews on books with both a rating and an optional written review
  • Users should be able to schedule a future check-out for a book that is currently checked-out
  • Users should be able to do a one-time extension for a week if no one has scheduled a future check-out for that book

The most exciting part of the extra credit was doing the research and learning more about what the language was capable of. I couldn’t believe how easy it was to import CSV and export CSV. Through lots of research and stack-overflow Q&A I was able to implement all but one (due to time constraints) of the extra credit requirements over a span of a week.

Library RB screenshot - MakerSquare week 1The most challenging part of the code was that we needed to comment things. I realize how helpful this could be because instead of trying to untangle the entire code I can simply read the comments. I suppose it’s difficult because when I write the comments the code makes sense to me. But I can’t assume what I will forget. I suppose as I code more I’ll begin to see a trend.

This project feels like it was a long time ago, though it was only 4 weeks ago. It’s surprising to see how quickly we could go from console only apps to full blown web-apps.

If you’re thinking of apply for MakerSquare, the previous statement should reassure you. You will learn and you will be able to build web-apps at the end of the course. Do it, take a chance and test yourself. I can only assume that we are doing well because everyone in the community continues to express how quickly we (as a cohort as a whole) were able to learn so much in such little time.