Created
August 12, 2014 03:27
-
-
Save arv25/c8334796fea5b9c40e25 to your computer and use it in GitHub Desktop.
auto define methods on class from hash
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
class Homeboy | |
def initialize( params={} ) | |
params.map do |kv| | |
self.instance_variable_set("@#{kv[0]}", kv[1]) | |
self.class.send(:define_method, "#{kv[0]}") { kv[1] } | |
end | |
end | |
def to_s | |
instance_variables.map { |sym| "#{sym.to_s[1..-1]},#{self.send(sym.to_s[1..-1])}" } | |
end | |
end | |
# ------------- | |
# Usage | |
best_customer = Homeboy.new( { customer_first_name: 'bub', customer_email: '[email protected]' } ) | |
best_customer.customer_first_name | |
... | |
best_customer.to_s.map { |str| type( str.split(",").first, str.split(",").last ) } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment