3

In my app I use an engine (blogit) to which I want to add some changes / behaviours.

I followed the guides on how to override engine controllers/models and added the following:

The Code

In config/initializer/blogit.rb

# Requires extension ruby files in lib/blogit.
Dir[Rails.root.join("lib/blogit/*.rb")].each {|f| require f}

In lib/blogit/engine.rb

module Blogit
  class Engine < ::Rails::Engine
    isolate_namespace Blogit

    config.to_prepare do
      Dir.glob(Rails.root + "app/decorators/**/blogit/*_decorator*.rb").each do |c|
        require_dependency(c)
      end
    end
  end
end

In app/decorators/controllers/blogit/comments_controller_decorator.rb

Blogit::CommentsController.class_eval do
  def create
    Rails.logger.info "decorated controller action"
    # ... overridden stripped ...
  end
end

In app/decorators/models/blogit/comment_decorator.rb

Blogit::Comment.class_eval do
  belongs_to :user
end

To be mentioned:

  • I have also created a migration to add a user reference to the comments model, since my app uses devise and I only want logged_in users to be able to comment. (Therefore I don't need the standard behaviour, so I'm going to override it.)

The Problem

If I run rake I get the weird error:

/Users/Kassi/.rvm/rubies/ruby-1.9.3-p392-railsexpress/bin/ruby -S rspec ./spec/controllers/home_controller_spec.rb ./spec/models/user_spec.rb
/Users/Kassi/demo/app/decorators/controllers/blogit/comments_controller_decorator.rb:3:in `<top (required)>': uninitialized constant Blogit::CommentsController (NameError)

However, if I run the first line that rake mentions by hand (.../ruby -S ...), all tests are being run successfully.

In my project I'm using guard with spork. Running guard will also let the tests pass without any error.

The app itself runs fine, i.e. it starts without errors and I'm able to comment as I want. My decorator action code is being executed.

So what's different when running rake? Why does it break?

Note:

  • Adding require "blogit" or require "blogit/comments_controller" doesn't help. It actually can't find the controller using require.

A Demo Application

Since this problem is part of a bigger project, I created a new app from scratch for testing purposes that contains only the relevant stuff: basic rails app, rspec, devise, blogit and the decorators. It can be found here: https://github.com/kassi/decorator_demo_rspec (git://github.com/kassi/decorator_demo_rspec.git)

Another repo using testunit (which is working!) can be found here: https://github.com/kassi/decorator_demo_testunit (git://github.com/kassi/decorator_demo_testunit.git)

4

1 回答 1

0

您可以尝试为您执行此操作的activesupport-decorators ,而不是自己执行 require 语句。

于 2014-03-04T13:03:08.237 回答