Skip to content

Instantly share code, notes, and snippets.

@radiospiel
Created February 20, 2017 07:40
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 radiospiel/81836d3950cb24953f325736e1d14e46 to your computer and use it in GitHub Desktop.
Save radiospiel/81836d3950cb24953f325736e1d14e46 to your computer and use it in GitHub Desktop.
require "byebug"
class Record < Struct
def self.new(*members, &block)
s = Struct.new(*members, &block)
s.include Initializer
s
end
module Initializer
def initialize(hsh)
members = self.class.members
values = members.map do |sym|
hsh[sym.to_s] || hsh[sym.to_sym]
end
super(*values)
end
end
end
if __FILE__ == $0
require "test-unit"
class Record::TestCase < Test::Unit::TestCase
UnnamedRecord = Record.new(:foo, :bar, :baz)
NamedRecord = Record.new("Name", :foo, :bar, :baz)
def test_read_from_syms
rec = UnnamedRecord.new(foo: "foovalue", "bar" => "barvalue")
assert_equal("foovalue", rec.foo)
assert_equal("barvalue", rec.bar)
assert_nil(rec.baz)
end
def test_named_record
rec = NamedRecord.new(foo: "foovalue", "bar" => "barvalue")
assert_equal("foovalue", rec.foo)
assert_equal("barvalue", rec.bar)
assert_nil(rec.baz)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment