Can my rails gem interact with models defined in the application that the gem is used in?

28 Views Asked by At

I have 2 rails applications and there is a service that is used by both. I have refactored the service to be a gem that can be leveraged by both rails applications.

As an example, the service defined in the gem

class MyService

  def method_that_uses_a_model
    ApiModel.create({})
  end

end

But the model is defined in the rails application

class ApiModel
end

As a gem, can the service access the Rails model within the rails applications that it will be used within?

If not, how can I access a model defined in the rails application from within a gem?

1

There are 1 best solutions below

0
smathy On

Yes. Although it means your gem is very fragile. You'd be better providing that class as a configuration option for your gem, so your app would set that config option, or even set a constant in the gem in an initializer in the app.