Created
May 12, 2020 15:12
-
-
Save tsaito-cyber/220d037b6be4d28da9385e8de44063da to your computer and use it in GitHub Desktop.
url_mappable.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
require 'open-uri' | |
module Concern | |
def self.extended(base) | |
base.instance_variable_set(:@__deps, []) | |
end | |
def included(base) | |
if (deps = base.instance_variable_get(:@__deps)) | |
deps << self | |
else | |
@__deps.each {|dep| base.include(dep)} | |
super | |
base.class_eval(&@__block) unless @__block.nil? | |
end | |
end | |
def injected(&block) | |
@__block = block | |
end | |
end | |
module Validatable | |
extend Concern | |
injected do | |
def self.validate(attribute, &block) | |
attr_accessor attribute unless method_defined?(attribute) | |
orig = "#{attribute}_orig=" | |
alias_method orig, "#{attribute}=" | |
define_method("#{attribute}=") do |val| | |
self.__send__(orig, val) if block.(val) | |
end | |
end | |
end | |
end | |
module URLMappable | |
extend Concern | |
include Validatable | |
injected do | |
def self.url_map_for(attribute) | |
storage = "#{attribute}_storage" | |
assign_attr = "#{attribute}=" | |
attr_accessor storage | |
define_method(assign_attr) do |url| | |
self.__send__("#{storage}=", URI.open(url).string) | |
end | |
define_method(attribute) do | |
self.__send__(storage) | |
end | |
validate attribute do |val| | |
begin | |
res = URI.parse(val) | |
res.is_a? URI::HTTP | |
rescue URI::InvalidURIError | |
nil | |
end | |
end | |
end | |
end | |
end | |
class X | |
include URLMappable | |
url_map_for :url | |
end | |
p X.new.tap {|x| x.url = 'http://ipcheck.com/' }.url | |
p X.new.tap {|x| x.url = 'aa' }.url |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment