I am creating an application using rails and spree at work. One point
of value is the administrator being able to upload files that will seed
the database.
Two problems arose. 1) apparently, the datashift bundle is 250 MB and
was hindering our deployment to heroku. 2) We couldn't figure out how
to use it from within a deployed application.
After a few people spent a few days with these problems, I ended up just
writing the functionality myself ( no datashift at all ). We have two
applications being developed, and the code is valuable to both.
We would like to extract it, and the first thought was 'gem'.
And thus the questions arise
Assuming making a gem is the correct idea, I'm going to need to call
ActiveRecord methods such as 'create' from within the gem. How do I
create or simulate a database that the gem can connect to? When I do
get passed that question, how do I tell the gem to be able to 'know'
when it is just me testing it, and it being in a real rails environment?
There's no reason a rails engine cannot be a gem. It starts out life that
way if you build it with rails anyway, since it creates a .gemspec file for
the engine.
Writing your code as a rails engine should address this. When loaded in your app, database settings etc are inherited (or rather if the models inherit from ActiveRecord::Base and your app has already configured activerecord then the engine’s activerecord models will also use those settings)
When you’re writing tests, depending on what you doing, you can either test it as you would any plain ruby code (you may have to configure an activerecord connection) and/or load your engine inside a dummy application. You can generate a skeleton with
rails plugin new my_engine
Personally I only find this useful if the shared code starts having controllers, assets etc. If it’s just a bunch of modules people can include or some useful baseclasses or some pure ruby code, then just a plain non engine gem is less hassle (bundler has a template for this). It’s also not a big deal to start off as the latter and then turn it into a full blown engine later on.