Here is a small problem I have. Take note that this is a simplified example.
Let's say I have a class with several instance methods and I want to log one of the instance methods using a ActiveSupport::Concern
:
class Car
include LogStartEngine
def start_engine
# useful thing
end
def check_oil
# useful thing
end
def open_doors
# useful thing
end
end
Here is what I first came up for the concern:
module LogStartEngine
extend ActiveSupport::Concern
included do
alias_method_chain :start_engine, :logging
end
def start_engine_with_logging
Rails.logger.info("Starting engine!")
start_engine_without_logging
Rails.logger.info("Engine started!")
end
end
But this will lead to
NameError: undefined method `start_engine' for class `Car'
from /Users/david/.gem/ruby/1.9.3/gems/activesupport-4.0.3/lib/active_support/core_ext/module/aliasing.rb:32:in `alias_method'
This is understandable since when LogStartEngine
is included, class Car
doesn't have any method called start_engine
.
I know I could solve this putting include LogStartEngine
after method start_engine
but I'd like to keep this statement where it is.
So the constraints are:
- log only the method
start_engine
, not all the methods. Car
just need to includeLogStartEngine
concern. I'd like to avoid having to call any custom helper methods added by the concern, something likelog_method :start_engine
.- I want to keep the
include LogStartEngine
statement where it is. I don't want it to be below methodstart_engine
or at the end of the class. - This is using Ruby 1.9. So
Module#prepend
is not a valid solution :)