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.
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
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
1 2 3 4 5 6 7 8 9 10 11
What’s that engine stuff?
There’s a great explanation of engines in the Rails documentation but 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?
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