Skip to content

Instantly share code, notes, and snippets.

@bestie
Created October 28, 2013 17:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bestie/7200969 to your computer and use it in GitHub Desktop.
Save bestie/7200969 to your computer and use it in GitHub Desktop.
An HStruct that also contains type data,
require 'hstruct'
class TypedStruct < HStruct
def self.schema(schema = nil)
@__schema ||= schema
end
end
def TypedStruct(members_hash, &block)
member_names = members_hash.keys
TypedStruct.new(*member_names, &block).tap { |struct|
struct.schema(members_hash)
}
end
# Example
Condition = TypedStruct(
id: String,
concept_id: Fixnum,
started_at: Time,
finished_at: Time,
patient_id: String,
medications: Array,
procedures: Array,
professionals: Array,
) do
# ...
end
p Condition.schema
=>
{
:id => String < Object,
:concept_id => Fixnum < Integer,
:started_at => Time < Object,
:finished_at => Time < Object,
:patient_id => String < Object,
:medications => Array < Object,
:procedures => Array < Object,
}
@bestie
Copy link
Author

bestie commented Oct 28, 2013

Not sure if I like the uppercase method overloading but mimicking the way that Struct.new returns a class is a bit crazy.

If you're curious check out the rubinius implementation of Struct https://github.com/rubinius/rubinius/blob/f290f2a4f7c59894ea567f9cb05cbe00a31a6654/kernel/common/struct.rb

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment