1

I'm just developing a Rails application which will have many Engines. However, I'm not able to edit relationships inside the Engines.

To solve this issue, I want to create a relationships-Gem which will be included in the Application and defines the relationships (see: https://stackoverflow.com/a/11835899/603126).

Let's assume, I have a User (namespaced and isolated) Engine and a Comment (namespaced and isolated) Engine. What I want is to override / extend the relationships inside the relationships-Gem which will share the relationships.

So I added a file /app/models/comment.rb with these lines (to the relationships-Gem):

class Comment < CommentEngine::Comment
  belongs_to :user
end

class User < UserEngine::User
  has_many :comments
end

If I run my rails application, the relationships won't be established.

What am I missing? How can this be achieved?

Thank you very much in advance

Community
  • 1
  • 1
pmuens
  • 788
  • 6
  • 16
  • 1
    Can you post your controller's code where the associations are built (new and create actions)? – R Milushev Aug 26 '13 at 19:58
  • Inside the comments_controller: def index @comments = current_user.comments end undefined method `comments' for # It seems like the model is never loaded. Even if I put a typo in the file, nothing happens. Thank you very much! – pmuens Aug 26 '13 at 20:03
  • On the stage of creation of a new comment, in CommentsController , how are your `new` and `create` actions look like ? – R Milushev Aug 26 '13 at 20:07
  • They are not implemented yet. I only have an index-action which looks like described above. – pmuens Aug 26 '13 at 20:11
  • I suppose you are dealing with existing database records? You can take a look at this [Rails guide](http://guides.rubyonrails.org/association_basics.html) , look for point 4.1 – R Milushev Aug 26 '13 at 20:18

2 Answers2

0

Ok, so I've found a solution for that.

You can just monkey-patch your Engine with Decorators (you need to put it into config/initializers/initializer_name.rb)

see: Extending a ruby gem in Rails

Don't know if this is a good thing, but it works like a charm...

The downside is that you have to restart the server every single time you make a change to the monkey-patching...

EDIT: It seems that this monkey-patch will be garbage collected after a few requests.

EDIT 2: This post helped me out How to monkey-patch code that gets auto-loaded in Rails? you need to add thin sin your Intializer to force rails to reload your patch for every request

Rails.configuration.to_prepare do
Community
  • 1
  • 1
pmuens
  • 788
  • 6
  • 16
0

The activesupport-decorators gem can load your decorators for you when the original class is loaded.

Pierre Pretorius
  • 2,869
  • 22
  • 21