Extracting code into a module

1.) Make sure that in application.rb files from the /lib folder are imported.

# application.rb
# ...
config.autoload_paths += %W(#{config.root}/lib) # config.root is our application root and /lib is the lib folder
# ...

2.) In the lib folder we can create a file like voteable.rb

# lib/voteable.rb

module Voteable
  extend ActiveSupport::Concern

  included do
    has_many :votes, as: :voteable # This includes lines in between do/end automatically when including the module somewhere else.
  end

  def method_one
  end

  def method_two
  end

end

  • Note that by convention we call modules ...able.rb
  • Using ActiveSupport::Concern means, that all the instance methods created will be instance methods when I include or mixin this module.

3.) In other files I can now mix in this module

# post.rb

class Post < ActiveRecord::Base
  include Voteable

  #...


Creating gems

1.) Install the gem gemcutter
2.) Create a new folder for the gem
3.) Create a gem specification file *.gemspec

# voteable.gemspec

Gem::Specification.new do |s|
  s.name = "voteable_file_name"
  s.version = '0.0.0'
  s.date = '2013-10-23'
  s.summary = 'A voting gem'
  s.description = 'The best voting gem ever.'
  s.authors =['Author name']
  s.email = '[email protected]'
  s.files = ['lib/voteable_file_name.rb']
  s.homepage = 'http://github.com'
end


4.) create the /libfolder and underneath insert the file voteable_file_name.rb. The module name has to match the file name (snake_case for file name, CamelCase for module name:

module VoteableFileName
  extend ActiveSupport::Concern

  included do 
    has_many :votes, as: :voteable
  end

  def method_one
  end

  def method_two
  end
end

5.) Now we package this gem with the gemcutter gem

In the terminal $ gem build voteable.gemspec
This creates a * .gem file for us.

6.) Push the gem to http://rubygems.org with $ gem push file_name.gem (This will require username and password from rubygems.org)

7.) Check if the gem has been published correctly on rubygems.org. You can do this by checking on the website or with $ gem list -r file_name

8.) Now we are ready to include the published gem in our own gemfile in our Rails app.

# Gemfile

#...
gem 'voteable_file_name'

Don’t forget to run $ bundle install and restart your rails server.

9.) We also have to require the file in the application.rb file to use it application wide.

# application.rb

require 'voteable_file_name'

Finally in the model we can just include the module name, e.g.

# post.rb
#... 
include VoteableFileName
#...


For more information see http://guides.rubygems.org/