Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a gem that contains rails models

Tags:

I've been reading a lot on the topic and nothing seems to quite cover my needs. I'm sorry if I'm repeating or unclear about something I'm both new to ruby and rails and new to stackoverflow.

I have an existing rails application with a lot of infrastructure in it. I want to take a few of it's models, nest them in a namespace and put all that into a ruby gem for use in other rails applications. From my understanding there's a problem with the loading paths for rails as they are a convention and a problem with defining another engine as then you have two and they crash.

I've been looking for a guide or tutorial to learn how to do this without much luck but I'm positive there's something out there if someone can point me at it that would be wonderful.

My attempts at making a gem with an engine fails on collisions or lack of rails.

I'm running rails 3.2.3 and ruby 1.9.3.

like image 726
Shrewd Avatar asked Aug 09 '12 16:08

Shrewd


People also ask

Is Ruby on Rails a gem?

Gems in Rails are libraries that allow any Ruby on Rails developer to add functionalities without writing code. You can also call Ruby on Rails gems as plugins for adding features. A Ruby gem enables adding features without creating the code again and again.


1 Answers

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   end end 
  • 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.

like image 98
vikas Avatar answered Sep 19 '22 18:09

vikas