Reputation: 741
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 Stack Overflow.
I have an existing Rails application with a lot of infrastructure in it. I want to take a few of its 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 fail on collisions or lack of Rails.
I'm running Rails 3.2.3 and Ruby 1.9.3.
Upvotes: 25
Views: 8998
Reputation: 678
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.
Upvotes: 27
Reputation: 91
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.
Upvotes: 2