11require_relative "inertia_rails"
22require_relative "helper"
3+ require_relative "action_filter"
34
45module InertiaRails
56 module Controller
@@ -14,10 +15,19 @@ module Controller
1415 end
1516
1617 module ClassMethods
17- def inertia_share ( attrs = { } , &block )
18- @inertia_share ||= [ ]
19- @inertia_share << attrs . freeze unless attrs . empty?
20- @inertia_share << block if block
18+ def inertia_share ( hash = nil , **props , &block )
19+ options = extract_inertia_share_options ( props )
20+ return push_to_inertia_share ( **( hash || props ) , &block ) if options . empty?
21+
22+ push_to_inertia_share do
23+ next unless options [ :if ] . all? { |filter | instance_exec ( &filter ) } if options [ :if ]
24+ next unless options [ :unless ] . none? { |filter | instance_exec ( &filter ) } if options [ :unless ]
25+
26+ next hash unless block
27+
28+ res = instance_exec ( &block )
29+ hash ? hash . merge ( res ) : res
30+ end
2131 end
2232
2333 def inertia_config ( **attrs )
@@ -55,6 +65,53 @@ def _inertia_shared_data
5565 end . freeze
5666 end
5767 end
68+
69+ private
70+
71+ def push_to_inertia_share ( **attrs , &block )
72+ @inertia_share ||= [ ]
73+ @inertia_share << attrs . freeze unless attrs . empty?
74+ @inertia_share << block if block
75+ end
76+
77+ def extract_inertia_share_options ( props )
78+ options = props . slice ( :if , :unless , :only , :except )
79+
80+ return options if options . empty?
81+
82+ if props . except ( :if , :unless , :only , :except ) . any?
83+ raise ArgumentError , "You must not mix shared data and [:if, :unless, :only, :except] options, pass data as a hash or a block."
84+ end
85+
86+ transform_inertia_share_option ( options , :only , :if )
87+ transform_inertia_share_option ( options , :except , :unless )
88+
89+ options . transform_values! do |filters |
90+ Array ( filters ) . map! ( &method ( :filter_to_proc ) )
91+ end
92+
93+ options
94+ end
95+
96+ def transform_inertia_share_option ( options , from , to )
97+ if ( from_value = options . delete ( from ) )
98+ filter = InertiaRails ::ActionFilter . new ( from , from_value )
99+ options [ to ] = Array ( options [ to ] ) . unshift ( filter )
100+ end
101+ end
102+
103+ def filter_to_proc ( filter )
104+ case filter
105+ when Symbol
106+ -> { send ( filter ) }
107+ when Proc
108+ filter
109+ when InertiaRails ::ActionFilter
110+ -> { filter . match? ( self ) }
111+ else
112+ raise ArgumentError , "You must pass a symbol or a proc as a filter."
113+ end
114+ end
58115 end
59116
60117 def default_render
0 commit comments