Skip to content

Instantly share code, notes, and snippets.

@alex-fedorov
Last active August 29, 2015 14:11
Show Gist options
  • Save alex-fedorov/ef2c059c4cd3b0917707 to your computer and use it in GitHub Desktop.
Save alex-fedorov/ef2c059c4cd3b0917707 to your computer and use it in GitHub Desktop.
BetterStruct
class BetterStruct < Struct
class << self
def new(*required, **properties)
super(*(required + properties.keys)) do
define_singleton_method(:_default_values) do
properties
end
end
end
def default_value_for(key)
_default_values.fetch(key) do
raise ArgumentError, "#{key} is required argument"
end
end
end
def initialize(**options)
super(*(_get_struct_values_from(options)))
end
def _get_struct_values_from(options)
members.map { |key|
options.fetch(key) {
self.class.default_value_for(key)
}
}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment