hash_struct 0.1 → 0.2
Sign up to get free protection for your applications and to get access to all the features.
- data/README.textile +20 -0
- data/lib/hash_struct.rb +18 -0
- data/spec/hash_struct_spec.rb +19 -0
- metadata +1 -1
data/README.textile
CHANGED
@@ -10,3 +10,23 @@ h1. Usage
|
|
10
10
|
User = HashStruct.new(:first_name, :last_name)
|
11
11
|
@user = User.new(first_name: "Jakub", last_name: "Stastny")
|
12
12
|
</pre>
|
13
|
+
|
14
|
+
h1. Inheritance
|
15
|
+
|
16
|
+
<pre>
|
17
|
+
module TestMixin
|
18
|
+
def say_hi() puts("Hi!") end
|
19
|
+
end
|
20
|
+
|
21
|
+
HashStruct.extend(TestMixin)
|
22
|
+
User = HashStruct.new(:first_name, :last_name)
|
23
|
+
User.say_hi
|
24
|
+
# => "Hi!"
|
25
|
+
</pre>
|
26
|
+
|
27
|
+
<pre>
|
28
|
+
HashStruct.send(:include, TestMixin)
|
29
|
+
User = HashStruct.new(:first_name, :last_name)
|
30
|
+
User.new.say_hi
|
31
|
+
# => "Hi!"
|
32
|
+
</pre>
|
data/lib/hash_struct.rb
CHANGED
@@ -5,6 +5,10 @@ class HashStruct
|
|
5
5
|
# @user = User.new(first_name: "Jakub", last_name: "Stastny")
|
6
6
|
def self.new(*attributes)
|
7
7
|
raise ArgumentError, "you have to specify some attributes" if attributes.empty?
|
8
|
+
|
9
|
+
included = self.included_modules
|
10
|
+
extended = (class << self; self; end).included_modules
|
11
|
+
|
8
12
|
Class.new do
|
9
13
|
# setup accessors
|
10
14
|
attributes.each do |attribute|
|
@@ -17,6 +21,20 @@ class HashStruct
|
|
17
21
|
self.send("#{attribute}=", value)
|
18
22
|
end
|
19
23
|
end
|
24
|
+
|
25
|
+
# NOTE: second possible implementation (maybe better) is Class.new(self)
|
26
|
+
# but then we have to used the original new method, so the object will be properly created
|
27
|
+
# include modules
|
28
|
+
(included - self.included_modules).each do |mixin|
|
29
|
+
puts "Including #{mixin}"
|
30
|
+
self.send(:include, mixin)
|
31
|
+
end
|
32
|
+
|
33
|
+
# extended modules
|
34
|
+
(extended - (class << self; self; end).included_modules).each do |mixin|
|
35
|
+
puts "Extending #{mixin}"
|
36
|
+
self.extend(mixin)
|
37
|
+
end
|
20
38
|
end
|
21
39
|
end
|
22
40
|
end
|
data/spec/hash_struct_spec.rb
CHANGED
@@ -29,4 +29,23 @@ describe HashStruct do
|
|
29
29
|
instance.first_name.should eql("Jakub")
|
30
30
|
end
|
31
31
|
end
|
32
|
+
|
33
|
+
describe "inheritance" do
|
34
|
+
before(:each) do
|
35
|
+
@hs = Class.new(HashStruct)
|
36
|
+
@mixin = Module.new { def say_hi() end }
|
37
|
+
end
|
38
|
+
|
39
|
+
it "should inherit all mixins of HashStruct" do
|
40
|
+
@hs.send(:include, @mixin)
|
41
|
+
@struct = @hs.new(:first_name, :last_name)
|
42
|
+
@struct.instance_methods.should include(:say_hi)
|
43
|
+
end
|
44
|
+
|
45
|
+
it "should be extended by all mixins of HashStruct" do
|
46
|
+
@hs.extend(@mixin)
|
47
|
+
@struct = @hs.new(:first_name, :last_name)
|
48
|
+
@struct.methods.should include(:say_hi)
|
49
|
+
end
|
50
|
+
end
|
32
51
|
end
|