Created
May 12, 2020 14:13
-
-
Save tsaito-cyber/94f659e26f2f74aa73d842768d8b8fb0 to your computer and use it in GitHub Desktop.
validatable.rb
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
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