简体   繁体   中英

Creating a gem that contains rails models

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.

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 .

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 etc into you engine. Generate gem from it. Add this gem to you MasterApp. All models will be available under EngineName namespace.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM