Created
May 2, 2011 14:25
-
-
Save mjohnsullivan/951668 to your computer and use it in GitHub Desktop.
Ruby Struct utilities: use named parameters to create Struct-based objects and return JSON from Structs
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
# Struct utilities | |
# Author:: Matt Sullivan (mailto:matt.j.sullivan@gmail.com) | |
# Attempt to require Ruby Gems; 1.8.X gem support only | |
begin | |
require 'rubygems' | |
rescue LoadError | |
# Ruby Gems not installed | |
end | |
require 'json' | |
# Extends Structs to support named parameter hashes | |
class NamedStruct < Struct | |
# Override the initialize constructor to handle hashes of named parameters | |
def initialize *args | |
return super unless (args.length == 1 and args.first.kind_of? Hash) | |
args.first.each_pair do |k, v| | |
# Keys get converted to symbols for consitency | |
# Structs in 1.9.x store their members as symbols, but in 1.8.7 and JRuby, | |
# they're stored as strings, so ensure you're comparing members as symbols | |
self[k.intern] = v if members.map {|x| x.intern}.include? k.intern | |
end | |
end | |
end | |
# Extends NamedStructs to support Hash and JSON outputting | |
class JSONStruct < NamedStruct | |
# Converts a Struct to a hash | |
def to_hash | |
hash = Hash.new | |
self.members.each { |m| hash[m] = self[m] } | |
hash | |
end | |
# Converts a Struct to a JSON string | |
def to_json *args | |
to_hash.to_json *args | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I found myself having to redeclare this in almost every project, so I created a gem: https://github.com/rohitpaulk/named_struct