Created
April 12, 2017 15:52
-
-
Save AJFaraday/ddb915e9bcd207b6a875af9ec49a6545 to your computer and use it in GitHub Desktop.
Dynamically extending an AR class with a validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This works like a dream! | |
module FooValidator | |
attr_accessor :foo | |
def FooValidator.extended(base) | |
base.singleton_class.validates_presence_of :foo | |
end | |
end | |
u = User.first | |
u.extend(FooValidator) | |
u.valid? | |
u.errors.full_messages | |
["Foo can't be blank"] | |
# However, now this throws an error | |
User.first.valid? | |
# NameError: undefined local variable or method `_callback_before_12716' for #<User:0x0000000feec938> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment