SHARE:
Uncategorized

What Is a Ruby Gem?

Flatiron School / 14 December 2012

The following is a guest post by Nikhil Thomas and originally appeared on his blog. Nikhil is currently a student a The Flatiron School. You can learn more about him here, or follow him on twitter here.

I’ve spent the last week working on GemifyJS, a cool new project that turns Javascripts into Ruby gems. Of course, to do this, I needed to answer the question what is a gem?

I always assumed gems were this secret black box where code goes in and magic comes out, but that was really just me being lazy. As it turns out, gems aren’t all that difficult to understand.

Not like this.

What’s the structure?

All gems revolve around what is called a gemspec file. The best way to explain what a gemspec is in to use the tangible world. All gems follow a standardized structure – the gemspec serves as a blueprint.

That’s what our gemspec template looks like (all created Javascript gems are creatively referred to as jems). This is all Ruby! There’s nothing special about this, all we do is define the basic attributes of the gem here.

However, this is the framework of what our gem looks like. It’s the scaffold of our code. Let’s fill in the blanks.

How do we write the functionality?

As it turns out, we probably want our gem to look do something. You can do that by including your code in the lib directory. For example, if your code might be in lib/bicycle.rb.

GemifyJS’s code does nothing more than package a Javascript so our code looks like this:

What’s that engine stuff?

There’s a great explanation of engines in the Rails documentationbut the best way to explain it simply is that it allows your package of code to be run. All you need to worry about is that you make sure you include the engine so it’s considered a module of code by Rails.

How do I build my gem?

Easy!

gem build gemname.gemspec will take your gemspec (our blueprint) and generate the gem.

gem install gemname will install it. How easy was that?

If you have any other questions or thoughts, I highly recommend you check out the Rails documentation. It’s a little dense but don’t be afraid to play around with the code examples. You can also reach me on Twitter at @nikhilthomas90

Metaprogramming: #const_set Previous Post A Recursive Method Next Post