Created
February 26, 2014 14:51
-
-
Save jhiemer/9230799 to your computer and use it in GitHub Desktop.
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
module InitFromHash | |
def initialize(*args) | |
args.first.each do |k, v| | |
unless defined?(k).nil? | |
result = v.instance_of?(Array) ? v.inject([]) {|arr, v1| arr << init_object(v1, k)} : init_object(v, k) | |
instance_variable_set("@#{k}", result) | |
end | |
end if (args.length == 1 && args.first.is_a?(Hash)) | |
end | |
def init_object(value, klass) | |
value.instance_of?(Hash) ? constantize(get_module_name + klass.to_s.capitalize).new(value) : value | |
end | |
def get_module_name | |
(self.class.name =~ /^(.+::).+$/) ? $1 : '' | |
end | |
def constantize(camel_cased_word) | |
names = camel_cased_word.split('::') | |
names.shift if names.empty? || names.first.empty? | |
constant = Object | |
names.each do |name| | |
constant = constant.const_defined?(name) ? constant.const_get(name) : constant.const_missing(name) | |
end | |
constant | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment