-
-
Save 844196/939cc050177f8a6af26b 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) | |
hash.each_pair(&method(:define_accessor)) | |
define_singleton_method(:reset) { initialize(hash); self } | |
end | |
def to_h | |
self.instance_variables.map(&:to_s).each_with_object({}) do |key, rtn_hash| | |
rtn_hash[key.sub(/\A@/, '').to_sym] = self.instance_variable_get(key) | |
end | |
end | |
def add_validation(method_name, message=nil, &validation) | |
self.singleton_class.class_eval { args_validation(method_name, message, &validation) } | |
end | |
args_validation :initialize, 'Argument should be a hash object.' do |object| | |
object.is_a?(Hash) | |
end | |
args_validation :add_validation, 'undefined method' do |name| | |
self.singleton_class.method_defined?(name) | |
end | |
private | |
def define_accessor(name, value) | |
instance_variable_set("@#{name}", value) | |
define_singleton_method(name) { self.instance_variable_get("@#{name}") } | |
define_singleton_method("#{name}=") {|arg| self.instance_variable_set("@#{name}", arg) } | |
end | |
end | |
config = Configuration.new(:foo => :bar) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment