Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
url_mappable.rb
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
You can’t perform that action at this time.