3
3
class Tram ::Page
4
4
extend ::Dry ::Initializer
5
5
6
+ require_relative "page/section"
7
+
6
8
class << self
7
9
attr_accessor :i18n_scope
8
10
9
11
def section ( name , options = { } )
10
- @__sections ||= [ ]
11
-
12
- n = name . to_sym
13
- if @__sections . map ( &:first ) . include? ( n )
14
- raise "Section #{ n } already exists"
15
- end
12
+ name = name . to_sym
13
+ raise "Section #{ name } already exists" if sections . key? name
16
14
17
- n = define_section_method ( n , options )
18
- @__sections << [ n , options ]
15
+ section = Section . new ( name , options )
16
+ sections [ name ] = section
17
+ define_method ( name , §ion . block ) if section . block
19
18
end
20
19
21
20
def url_helper ( name )
22
21
raise "Rails url_helpers module is not defined" unless defined? ( Rails )
23
22
delegate name , to : :"Rails.application.routes.url_helpers"
24
23
end
25
24
26
- private
27
-
28
- def define_section_method ( n , options )
29
- return n unless options [ :value ]
30
- define_method ( n ) { instance_exec ( &options [ :value ] ) }
31
- n
25
+ def sections
26
+ @sections ||= { }
32
27
end
33
28
end
34
29
35
- def to_h ( options = { } )
36
- data = page_methods ( options ) . map do |( name , opts ) |
37
- value = public_send ( opts [ :method ] || name )
38
- [ name , value ]
39
- end
40
- Hash [ data ]
30
+ def to_h ( except : nil , only : nil , **)
31
+ obj = self . class . sections . values . map { |s | s . call ( self ) } . reduce ( { } , :merge )
32
+ obj = obj . reject { |k , _ | Array ( except ) . map ( &:to_sym ) . include? k } if except
33
+ obj = obj . select { |k , _ | Array ( only ) . map ( &:to_sym ) . include? k } if only
34
+ obj
41
35
end
42
36
43
37
private
@@ -47,21 +41,5 @@ def t(key)
47
41
I18n . t key , scope : [ Tram ::Page . i18n_scope , self . class . name . underscore ]
48
42
end
49
43
50
- def page_methods ( options )
51
- methods = self . class . instance_variable_get ( :"@__sections" ) || [ ]
52
- except = Array ( options [ :except ] )
53
- only = Array ( options [ :only ] )
54
- methods . reject do |( name , opts ) |
55
- ( except . any? && except . include? ( name ) ) ||
56
- ( only . any? && !only . include? ( name ) ) ||
57
- __hide? ( opts )
58
- end
59
- end
60
-
61
- def __hide? ( opts )
62
- black , white = opts . values_at ( :unless , :if )
63
- ( black && public_send ( black ) ) || ( white && !public_send ( white ) )
64
- end
44
+ self . i18n_scope = "pages"
65
45
end
66
-
67
- Tram ::Page . i18n_scope = "pages"
0 commit comments