Building my first little Ruby gem

Strategies when creating a new gem:

  1. add a module to application_controller.rb
  2. think about from where the gem should be called from

 


module BillesViewTool

class Renderer

def self.copyright name, msg

"&copy; #{Time.now.year} | <b>#{name}</b> #{msg}".html_safe

end

end

end

 

with the code above I’m going to implement a copyright that shows on all of my pages, I just have to call it with


def set_copyrightdef

@copyright = BillesViewTool::Renderer.copyright 'Mark Billes', 'All rights reserved'

end

 

and voila I got what I wanted:

© 2017 | Mark Billes All rights reserved

 

Now that the funcionality is done, let’s focus on acutally building the gem.

check on http://www.rubygems.org if theres a conflict with the name I’ve chosen for my gem.

now run the following command:

bundle gem billes_view_tool

To generate all the files that we need to create our gem.

cd into it.

cd billes_view_tool

 

Open the file with sublime text and open billes_view_tool.gemspec

Under spec.summary and spec.description it’s needed to edit the TODOs


spec.summary = %q{TODO: Write a short summary, because Rubygems requires one.}
spec.description = %q{TODO: Write a longer description or delete this line.}

to:


spec.summary = %q{Various view specific methods for application I use.}
spec.description = %q{Provides generated HTML data for Rails applications.}

 

next, delete the barrier to push the gem to RubyGems.org , because that is what I want.

 

Go to lib directory:

under version.rb it’s displaying the version of our gem

VERSION = “0.1.0” #constant variable

and under the actual billes_view_tool.rb file you can find all the logic components

now we have to import our version inside of the billes_view_tool.rb file


require "billes_view_tool/renderer"

create the renderer class inside the same directory:

inside renderer.rb copy&paste the code we wrote inside application_controller.rb file


module BillesViewTool

class Renderer

def self.copyright name, msg

"&copy; #{Time.now.year} | <b>#{name}</b> #{msg}".html_safe

end

end

end

 

To use the gem we have to create a github repository first. add the gemfile to the gitignore list:

/tmp/

….

*.gem

 

build the gem with:

gem build billes_view_tool.gemspec

 

add the gem to the gemfile with:

gem ‘billes_view_tool’, git: ‘https://github.com/DRAEIN/billes_view_tool&#8217;

then run bundle install! If all went right, we would still see our little copyright on each page.

 

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s