strukt 0.0.3 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. data/lib/strukt.rb +9 -1
  2. data/spec/strukt_spec.rb +20 -4
  3. metadata +1 -1
data/lib/strukt.rb CHANGED
@@ -1,5 +1,5 @@
1
1
  class Strukt
2
- VERSION = "0.0.3"
2
+ VERSION = "0.0.4"
3
3
 
4
4
  include Enumerable
5
5
 
@@ -10,6 +10,14 @@ class Strukt
10
10
  include Enumerable
11
11
 
12
12
  const_set(:MEMBERS, members.dup.freeze)
13
+
14
+ def self.coerce(coercable)
15
+ case coercable
16
+ when self then coercable
17
+ when Hash then new(coercable)
18
+ else raise TypeError, "Unable to coerce #{coercable.class} into #{self}"
19
+ end
20
+ end
13
21
 
14
22
  def initialize(params = {})
15
23
  params.each { |k, v| send("#{k}=", v) }
data/spec/strukt_spec.rb CHANGED
@@ -79,8 +79,8 @@ describe Strukt do
79
79
 
80
80
  describe "#hash" do
81
81
  it "is stable" do
82
- bob_1 = Person.new(:name => "BOB")
83
- bob_2 = Person.new(:name => "BOB")
82
+ bob_1 = Person.new(:name => "Bob")
83
+ bob_2 = Person.new(:name => "Bob")
84
84
 
85
85
  expect(bob_1.hash).to eq(bob_2.hash)
86
86
  end
@@ -101,12 +101,28 @@ describe Strukt do
101
101
 
102
102
  describe "#to_hash" do
103
103
  it "returns the struct as a hash" do
104
- person = Person.new(:name => "bob", :age => 50)
105
- expect(person.to_hash).to eq({:name => "bob", :age => 50})
104
+ person = Person.new(:name => "Bob", :age => 50)
105
+ expect(person.to_hash).to eq({:name => "Bob", :age => 50})
106
106
  end
107
107
 
108
108
  it "is frozen" do
109
109
  expect { Person::MEMBERS << :height }.to raise_error(/can't modify frozen/)
110
110
  end
111
111
  end
112
+
113
+ describe ".coerce" do
114
+ it "returns the input unmodified if it is already an instance of the struct" do
115
+ person = Person.new
116
+ expect(Person.coerce(person)).to be(person)
117
+ end
118
+
119
+ it "initializes a new instance if the input is a hash" do
120
+ person = Person.coerce({:name => "Bob"})
121
+ expect(person).to eq(Person.new(:name => "Bob"))
122
+ end
123
+
124
+ it "raises a TypeError otherwise" do
125
+ expect { Person.coerce("15 lbs of squirrel fur") }.to raise_error(TypeError)
126
+ end
127
+ end
112
128
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: strukt
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.0.3
4
+ version: 0.0.4
5
5
  prerelease:
6
6
  platform: ruby
7
7
  authors: