Writing a Rails Application. I would like to make some more commonly used validations available in my models. I understand how to do inline checks, and how to write my own methods. However, I find that I use the same checks in several places, and I'm embarrassed to use mixins for different classes.
Here is an example: I have an object with prop1 and prop2. Any of them is valid, but it is incorrect to set both parameters. Right now, I have something like
class MyClass < ActiveRecord::Base
attr_accessor :prop1, :prop2
validate :prop1_prop2_mutex
def prop1_prop2_mutex
errors.add(:base, "Can not set prop1 and prop2") if prop1 && prop2
end
end
What I really like is something like
class MyClass < ActiveRecord::Base
attr_accessor :prop1, :prop2
validate_mutex :prop1, :prop2
end
and then elsewhere, I guess I need something like
def validate_mutex(property1, property2)
rrors.add(:base, "Can not set prop1 and prop2") if self.send(property1) && self.send(property2)
end
Perhaps this is not so.
So how can I create a new reuse method? Or is there a better way to approach this problem?
, . . -, , , .