Sha256: 7e0404d426f2d4e00c160dacb402f6f6412971b63bef1fc51c4a0f9a5b6ec424
Contents?: true
Size: 1.67 KB
Versions: 9
Compression:
Stored size: 1.67 KB
Contents
module RubyPsigate # In your class, you can define the instance variables you want to wrap in a hash output # # Usage: # # hashable :billing, [:name, :address, :city, :state, :country, :zipcode] # # What this will do is create a hash like this when you call the class' instance #to_hash(:billing) # { :name => "Bob", :address => "1234 West St", :city => "North York", :state => "NY", :country => "USA", zipcode => "12345"} # # If you don't specify a "name", you can simply call #to_hash: # # hashable [:name, :address, :city, :state, :country, :zipcode] # instance#to_hash will yield the same output as above # module HashVariables def self.included(klass) klass.extend ClassMethods klass.send(:include, InstanceMethods) end module ClassMethods def hashable(*args) @hashable_attributes ||= {} if args[0].is_a?(Symbol) && args[1].is_a?(Array) @hashable_attributes[args[0]] = args[1] elsif args[0].is_a?(Array) @hashable_attributes[:default] = args[0] else raise ArgumentError end end def hashable_attributes @hashable_attributes end end module InstanceMethods def to_hash(name=nil) return_hash = {} if name.nil? attributes = self.class.hashable_attributes[:default] else attributes = self.class.hashable_attributes[name.to_sym] end attributes.each do |a| key = "#{a}" value = self.send(a.downcase) return_hash[key.to_sym] = value end return_hash end end end end
Version data entries
9 entries across 9 versions & 1 rubygems