#adding ‘created_by’ and ‘updated_by’ to all models
module ObjectStatistics
def self.append_features(base)
base.before_create do |model|
model.created_by ||= User.backend_user.id if
model.respond_to?(:created_by)
end
base.before_save do |model|
model.updated_by = User.backend_user.id if
model.respond_to?(:updated_by)
end
end
I had the same question about how to implement the belongs_to in a more
dry fashion. I din’;t figure it out, os i have that declaration in
most all of my models. Not ideal.
As for displaying the login, you could override the accessor
This will call the belongs_to method on the class that the module is
included in. You may need to fiddle with the syntax, can’t test this
at the moment.
I am trying to do a functional test on a controller that mixes in a
module
with an expensive method, but I would like to mock out that method for
my
testing purposes. I can’t seem to do it. Here’s what I have tried
def setup @controller = MyController.new
klass = class << @controller; self; end
klass.send(:undef_method, :something_expensive)
klass.send(:define_method, :something_expensive, lambda {nil})
end
I have also tried to do the less idiomatic but more straightforward
def @controller.something_expensive; nil; end
but that didn’t help, either. The undef_method fails because it can’t
find
the method (I guess becaues it’s actually defined in the module). The
other way just silently fails to accomplish its objective. I’ve googled
some but am somewhat perplexed. Ideas?
this is what the controller looks like
class MyController
include ModuleWithExpensiveMethod
end
module ModuleWithExpensiveMethod
def something_expensive
sleep(100)
end
end
Both of these techniques work fine when I try your examples - are you
sure
your example illustrates the problem you are seeing?
A third way is like this…
def setup @controller = MyController.new
class << @controller
undef something_expensive # not strictly necessary
def something_expensive; end
end
end
But if you are getting into mocking and stubbing, you might like to have
a
look at Mocha at http://mocha.rubyforge.org which can make your life a
bit
easier.
James.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.