Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to share activerecord models via Ruby Gem

I have a couple of Rails project which have some codebase in common. The common code consists of some ActiveRecord Models and an api on top of that. Currently I am duplicating the common code in all projects which is a very bad practice. Now I want to move the common code to a Ruby Gem. I am new to Ruby on Rails. I have looked at several Gem tutorials but could not find anything useful that will help me create a gem with reusable ActiveRecord models.

Essentially I want is that -

  • Gem contains some common active record models.
  • Gem contains some code which provides an api upon these models
  • This gem will be used by several Rails projects and they will initialize database etc.

Please let me know what are the best practices for such case.

like image 494
MoveFast Avatar asked Oct 01 '22 17:10

MoveFast


1 Answers

I remember having the same issue with my ecommerce project and later I moved it to separate repository. By simply moving the whole repetitive code to a rails engine.

There are couple of guides available which you can follow:

  1. http://edgeguides.rubyonrails.org/engines.html

  2. http://coding.smashingmagazine.com/2011/06/23/a-guide-to-starting-your-own-rails-engine-gem/

  3. http://railscasts.com/episodes/277-mountable-engines

You can create a generator to install your migration files of your models. So, whenever you mount your rails engine to any rails application and run generators. You'll be up and running with just few commands like: rake db:migrate etc..

Well, what I shared is my experience. I do not know if there is any other better way of doing it.

P.S.: Here is the link to repository of engine I created - https://github.com/suryart/spree_active_sale, maybe code there can help you as a reference.

like image 151
Surya Avatar answered Oct 13 '22 10:10

Surya