Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
validatable.rb
module Validatable
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def validate(attribute, &block)
attr_accessor attribute unless defined?(attribute)
alias_method "#{attribute}_orig=", "#{attribute}="
define_method("#{attribute}=") do |val|
self.__send__("#{attribute}_orig=", val) if block.(val)
end
end
end
end
class X
attr_accessor :val
include Validatable
validate :val do |val|
/\d+/.match val.to_s
end
end
p X.new.tap {|x| x.val = 'hoge' }.val
p X.new.tap {|x| x.val = 5 }.val
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.