Skip to content

Instantly share code, notes, and snippets.

@AJFaraday
Created April 12, 2017 15:52
Show Gist options
  • Save AJFaraday/ddb915e9bcd207b6a875af9ec49a6545 to your computer and use it in GitHub Desktop.
Save AJFaraday/ddb915e9bcd207b6a875af9ec49a6545 to your computer and use it in GitHub Desktop.
Dynamically extending an AR class with a validation
# 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