I created my first Ruby Gem: body_id on GitHub, and I have successfully implemented it my own project. My goals were to see what goes in making a gem and making a process simpler.
The Problem
I first saw the use of @bodyid
when Derek Sivers announced that he open sourced all his projects. Which was useful in learning about Sinatra He had @bodyid
in his controller, and he called it within the body tag.
When I saw this, I thought it was incredibly useful for styling, so I used it on my own rails project. The problem arose when I was defining my @bodyid
to strings like page-index
or new-car.
Eventually each controller action had a @bodyid
.
The Solution
I searched online if anyone already made a gem that did this, and I found these two links. Automatic Body ID in Rails on GitHub and Create a simple Rails 3 text helper Gem by on StackOverflow. The first link showed how you could combine the controller and action name into a single string. I like how he extracted my current process out into a helper, but I saw there were a few unnecessary method calls.
The second link essentially asked how to make the same gem I was planning on making. What I liked about his approach was how he made the id both semantic and similar to RESTful Rails path name. i.e. new_page_path and new_page_view. The answers and the asker’s GitHub repo was key to showing me how to make the actual gem.
There was a problem with these two helpers however. They both did not allow for the user to define their own ID in case they wanted to diverge from the helper’s convention. That’s where I added a simple || operator with the generated ID and an instance variable defined within the controller.
The final helper:
I first removed the controller
object in favor to just calling controller_name
and action_name
directly. This eliminates the need for the gsub()
to make ‘controller’ to nothing. Next was the underscore()
. I wasn’t sure why I needed this method until I remembered that some controller names and action names were written in CamelCase, so if I wanted to have the generated output look more consistent, then it would be best to leave it in. Finally I combined the two variables into the body_id
variable after replacing _underscore with – hyphens to match with CSS conventions. The last line determines if we’ll use the controller declared instance if truthy or the helper’s generated string if @body_id is not defined.
I used bundler to generate the gem files I needed, while I referenced RailsCast #245 New Gem with Bundler and Railtie’s docs One of the things I read online about making a gem was to add some graphics love and make good README. So I got some Illustrator practice in while making the gem’s logo, and I looked at other README for common practices.
Overall I found the process easier than I thought it would be and helpful in understanding what goes into making a simple open source Ruby Gem available.
Fork me on GitHub the4dpatrick / body-id-gem