Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Ruby Struct utilities: use named parameters to create Struct-based objects and return JSON from Structs
# 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
@rohitpaulk

This comment has been minimized.

Copy link

rohitpaulk commented Sep 27, 2017

I found myself having to redeclare this in almost every project, so I created a gem: https://github.com/rohitpaulk/named_struct

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.