Creating a gem that contains rails models Creating a gem that contains rails models ruby-on-rails ruby-on-rails

Creating a gem that contains rails models


Yes, you can create a gem containing models and include them in multiple Rails applications. This is one way to do it:

  • Create a gem: bundle gem demo_gem

  • Create or move your models to the demo_gem. I prefer putting them in lib/ folder of the gem like for example demo_gem/lib/app/models/student.rb.

    module DemoGem  class Student < ActiveRecord::Base  endend
  • Require all your models in demo_gem/lib/demo_gem.rb

    require "demo_gem/version"require "demo_gem/app/models/student.rb"module DemoGem  # Your code goes here...end
  • Include the gem in your Rails applications Gemfile (I'm assuming that your code is not open source and you don't plan to publish the gem):

    gem 'demo_gem', path: '../demo_gem'

Now you can use these models anywhere in multiple rails application, just by using DemoGem::Student.

It is assumed here that you are using single database and that the tables exist. However you can create migrations in the gem itself and copy them to app using Rails generators.


Start with this manual - http://guides.rubyonrails.org/engines.html

Create an engine with comand

$ rails plugin new "EngineName" --mountable

Than put all that you need, models, controllers e.t.c into you engine. Generate gem from it.Add this gem to you MasterApp. All models will be available under EngineName namespace.