hello,
lets describe my situation: i have two classes which have a lot same
validations defined … to stay DRY i want to put them in one place and
use it within both ActiveRecord classes.
i think subclassing is not possible because both classes are AR of
different tables
tried to include a module but this didnt work either:
hey thx for the quick reply … it worked!
i am just wondering why its “instance_eval” and not “class_eval”…
should the validations not be applied to the whole class?
nearly there!
module CommonStuff
def self.included(base)
base.instance_eval do
validates_length_of :a, :in => 1…10
validates_length_of :b, :in => 1…20
end
end
…
end
hey thx for the quick reply … it worked!
i am just wondering why its “instance_eval” and not “class_eval”…
should the validations not be applied to the whole class?
In this particular case it doesn’t make any difference. instance_eval
means that self will be the base class (ie A) when the validates_*
calls are made. module_eval (which is the same as class eval) would do
the same thing (it would be different if we were defining methods
inside the eval block, but we’re not)
I mean
module CommonStuff
def self.included(base)
base.instance_eval do
validates_length_of :a, :in => 1…10
validates_length_of :b, :in => 1…20
end
end
has the same effect as
module CommonStuff
def self.included(base)
base.class_eval do
validates_length_of :a, :in => 1…10
validates_length_of :b, :in => 1…20
end
end
but if your eval block had
def foo
end
then the method would be added in different places (A.foo instead of
A.new.foo)
In this particular case it doesn’t make any difference. instance_eval
means that self will be the base class (ie A) when the validates_*
calls are made. module_eval (which is the same as class eval) would do
the same thing (it would be different if we were defining methods
inside the eval block, but we’re not)
i see… you mean if we would do this??
def self.included(base)
class_eval do
…
end
end
Fred
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.