DaniG2k
DaniG2k

Reputation: 4903

Using a database within a Ruby gem

I'd like to use a database within a Ruby gem that I'm writing. The gem is meant to be used within Rails applications, and will contain an inverted index of documents passed in from the main Rails app.

I'm a bit confused as to how to go about this. Should I hook into the main Rails database somehow? Or should I have a standalone database? Ideally I'd just like to use ActiveRecord to create, update, delete and query entries but I am not sure how I'd set this up.

Data would go into the database at this point:

module ActiveRecordExtension
  extend ActiveSupport::Concern

  class_methods do
    def foo
      "bar"
    end
  end

  included do
    after_save :add_to_inverted_index
  end

  def add_to_inverted_index
    # This is where I'd take the fields from the Rails app
    # and include them to my inverted index. However, I'm struggling
    # to find a way to hook into a database from my gem to do this.
  end
end
# Include the extension 
ActiveRecord::Base.send(:include, ActiveRecordExtension)

Suggestions are much appreciated! Thanks

Upvotes: 0

Views: 1209

Answers (1)

Miguel Cunha
Miguel Cunha

Reputation: 663

Well after your clarification, you should use main Rails database. Just create a migration and insert the table(s) you need. You should do that because:

  • Everyone that uses your gem will know what is stored at the database.
  • With migrations, you can easily rollback the migration, making it simple to reverse something, if needed.
  • There's no need to create extra dependencies. Imagine a project that you did in RoR and think if the mess it would be if every gem that you used created its own database.

Maybe you should take a look at known gems and how they do that. I'm thinking about Devise.

Upvotes: 1

Related Questions