Created
February 28, 2016 08:39
-
-
Save 844196/12cd1f905240cf7197a1 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 'n_cipher/argument_validation' | |
class Configuration | |
include NCipher::ArgumentValidation | |
def initialize(hash, &block) | |
hash.each(&method(:set_attribute)) | |
hash.each(&method(:define_accessor)) | |
define_reseter(hash) | |
yield(self) if block_given? | |
end | |
def to_h | |
instance_variables.map(&:to_s).each_with_object({}) do |key, rtn_hash| | |
rtn_hash[key.sub(/\A@/, '').to_sym] = instance_variable_get(key) | |
end | |
end | |
def add_validation(name, message=nil, &validation) | |
singleton_class.class_eval { args_validation(name, message, &validation) } | |
end | |
private | |
def define_reseter(initial_hash) | |
define_singleton_method(:reset) { initial_hash.each(&method(:set_attribute)); self } | |
end | |
def define_reader(name) | |
define_singleton_method(name) { instance_variable_get("@#{name}") } | |
end | |
def define_writer(name) | |
define_singleton_method("#{name}=") {|arg| instance_variable_set("@#{name}", arg) } | |
end | |
def define_accessor((name, *)) | |
%i(reader writer).each {|function| __send__("define_#{function}", name) } | |
end | |
def set_attribute((name, value)) | |
instance_variable_set("@#{name}", value) | |
end | |
end |
This file contains hidden or 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
config = Configuration.new(:seed => 'にゃんぱす', :delimiter => '〜') do |setter| | |
setter.add_validation :seed=, 'Seed must be 2 to 36 characters.' do |seed| | |
seed.length.between?(2, 36) | |
end | |
setter.add_validation :seed=, 'Character is duplicated in seed.' do |seed| | |
seed.length == seed.chars.uniq.length | |
end | |
setter.add_validation :seed=, 'Seed and delimiter are duplicated.' do |seed| | |
!seed.include?(@delimiter) | |
end | |
setter.add_validation :delimiter=, 'Delimiter and seed are duplicated.' do |delimiter| | |
[email protected]?(delimiter) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment