1- require 'yaml'
1+ load_library :bubble_yaml
22
33attr_reader :bubbles , :bubble_data
44
5- MAX_BUBBLE = 10
6-
75def settings
86 size ( 640 , 360 )
97end
@@ -23,87 +21,27 @@ def draw
2321end
2422
2523def load_data
26- yaml = YAML . load_file ( data_path ( 'data.yml' ) )
27- # parse the source string
28- @bubble_data = BubbleData . new 'bubbles'
29- # get the bubble_data from the top level hash
30- data = bubble_data . extract_data yaml
31- # map the bubble_data array to an array of bubbles
24+ data = BubbleReader . new . read ( data_path ( 'data.yml' ) ) . fetch ( 'emotions' )
3225 @bubbles = data . map do |point |
33- pos = point [ 'position' ]
34- Bubble . new ( pos [ 'x' ] , pos [ 'y' ] , point [ 'diameter' ] , point [ 'label' ] )
26+ Bubble . new ( point [ 'position' ] , point [ 'diameter' ] , point [ 'label' ] )
3527 end
28+ @bubble_data = BubbleData . new ( bubbles )
3629end
3730
3831def save_data
39- # demonstrate how easy it is to create json object from a hash in ruby
40- hash = bubble_data . to_hash
32+ # demonstrate how easy it is to create yaml object from a hash in ruby
33+ # you could easily store 'colors as well as 'emotions' bubbles
34+ writer = BubbleWriter . new ( type : 'emotions' , data : bubble_data . to_h )
4135 # overwite existing 'data.yml'
42- open ( data_path ( 'data.yml' ) , 'w' ) { | file | file . write ( hash . to_yaml ) }
36+ writer . write ( data_path ( 'data.yml' ) )
4337end
4438
4539def mouse_pressed
4640 # create a new bubble instance, where mouse was clicked
4741 @bubble_data . add_bubble (
48- Bubble . new ( mouse_x , mouse_y , rand ( 40 ..80 ) , 'new label' )
42+ Bubble . new ( [ mouse_x , mouse_y ] , rand ( 40 ..80 ) , 'new label' )
4943 )
5044 save_data
5145 # reload the yaml data from the freshly created file
5246 load_data
5347end
54-
55- # Bubble data holder
56- class BubbleData
57- attr_reader :name , :data
58- def initialize ( name = 'bubbles' )
59- @name = name
60- @bubbles = [ ]
61- end
62-
63- def add_bubble ( bubble )
64- bubbles << bubble
65- bubbles . shift if bubbles . size > MAX_BUBBLE
66- end
67-
68- def extract_data ( yaml )
69- @bubbles = yaml [ name ]
70- end
71-
72- def to_hash
73- { name => bubbles . map ( &:to_hash ) }
74- end
75- end
76-
77- # The Bubble class
78- class Bubble
79- attr_reader :x , :y , :diameter , :name , :over
80-
81- def initialize ( x , y , diameter , name )
82- @x , @y , @diameter , @name = x , y , diameter , name
83- @over = false
84- end
85-
86- def rollover ( px , py )
87- distance = dist px , py , x , y
88- @over = ( distance < diameter / 2.0 )
89- end
90-
91- def display
92- stroke 0
93- stroke_weight 2
94- no_fill
95- ellipse x , y , diameter , diameter
96- return unless over
97- fill 0
98- text_align CENTER
99- text ( name , x , y + diameter / 2.0 + 20 )
100- end
101-
102- def to_hash
103- {
104- 'position' => { 'x' => x , 'y' => y } ,
105- 'diameter' => diameter ,
106- 'label' => name
107- }
108- end
109- end
0 commit comments