Skip to content

Instantly share code, notes, and snippets.

@arv25
Created August 12, 2014 03:27
Show Gist options
  • Save arv25/c8334796fea5b9c40e25 to your computer and use it in GitHub Desktop.
Save arv25/c8334796fea5b9c40e25 to your computer and use it in GitHub Desktop.
auto define methods on class from hash
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