Skip to content

Instantly share code, notes, and snippets.

@takuma-saito
Created May 12, 2020 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save takuma-saito/94f659e26f2f74aa73d842768d8b8fb0 to your computer and use it in GitHub Desktop.
Save takuma-saito/94f659e26f2f74aa73d842768d8b8fb0 to your computer and use it in GitHub Desktop.
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