/
application_helper.rb
1692 lines (1456 loc) · 64.4 KB
/
application_helper.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# encoding: utf-8
# ##### BEGIN LICENSE BLOCK #####
# Ekylibre - Simple ERP
# Copyright (C) 2009 Brice Texier, Thibaud Merigon
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# ##### END LICENSE BLOCK #####
# require_dependency Rails.root.join("lib", "exchanges", "svf", "loader").to_s
# module ActiveRecord
# class Base
# def merge(object, force=false)
# raise Exception.new("Unvalid object to merge: #{object.class}. #{self.class} expected.") if object.class != self.class
# reflections = self.class.reflections.collect{|k,v| v if v.macro==:has_many}.compact
# if force
# for reflection in reflections
# klass = reflection.class_name.constantize
# begin
# klass.update_all({reflection.foreign_key=>self.id}, {reflection.foreign_key=>object.id})
# rescue
# for item in object.send(reflection.name)
# begin
# item.send(reflection.foreign_key.to_s << '=', self.id)
# item.send(:update_without_callbacks)
# rescue
# # If the item can't be attached, the item can't be.
# puts item.inspect
# klass.delete(item)
# end
# end
# end
# end
# object.delete
# else
# ActiveRecord::Base.transaction do
# for reflection in reflections
# reflection.class_name.constantize.update_all({reflection.foreign_key=>self.id}, {reflection.foreign_key=>object.id})
# end
# object.delete
# end
# end
# return self
# end
# def has_dependencies?
# end
# end
# end
# encoding: utf-8
module ApplicationHelper
def authorized?(url={})
if url.is_a?(String) and url.match(/\#/)
action = url.split("#")
url = {:controller=>action[0].to_sym, :action=>action[1].to_sym}
end
url[:controller]||=controller_name
ApplicationController.authorized?(url)
end
# It's the menu generated for the current user
# Therefore: No current user => No menu
def menus
session[:menus]
end
# Return an array of menu and submenu concerned by the action (controller#action)
def reverse_menus(action=nil)
action ||= "#{self.controller.controller_name}::#{action_name}"
Ekylibre.reverse_menus[action]||[]
end
# LEGALS_ITEMS = [h("Ekylibre " + Ekylibre.version), h("Ruby on Rails " + Rails.version), h("Ruby "+ RUBY_VERSION.to_s)].join(" – ".html_safe).freeze
def legals_sentence
# "Ekylibre " << Ekylibre.version << " - Ruby on Rails " << Rails.version << " - Ruby #{RUBY_VERSION} - " << ActiveRecord::Base.connection.adapter_name << " - " << ActiveRecord::Migrator.current_version.to_s
return [h("Ekylibre " + Ekylibre.version), h("Ruby on Rails " + Rails.version), h("Ruby "+ RUBY_VERSION.to_s), h("HTML 5"), h("CSS 3")].join(" – ").html_safe
end
def choices_yes_no
[ [::I18n.translate('general.y'), true], [I18n.t('general.n'), false] ]
end
def radio_yes_no(name, value=nil)
radio_button_tag(name, 1, value.to_s=="1", id=>"#{name}_1") <<
content_tag(:label, ::I18n.translate('general.y'), :for=>"#{name}_1") <<
radio_button_tag(name, 0, value.to_s=="0", id=>"#{name}_0") <<
content_tag(:label, ::I18n.translate('general.n'), :for=>"#{name}_0")
end
def radio_check_box(object_name, method, options = {}, checked_value = "1", unchecked_value = "0")
# raise Exception.new eval("@#{object_name}.#{method}").inspect
radio_button_tag(object_name, method, TrueClass, :id=>"#{object_name}_#{method}_#{checked_value}") << " " <<
content_tag(:label, ::I18n.translate('general.y'), :for=>"#{object_name}_#{method}_#{checked_value}") << " " <<
radio_button_tag(object_name, method, FalseClass, :id=>"#{object_name}_#{method}_#{unchecked_value}") << " " <<
content_tag(:label, ::I18n.translate('general.n'), :for=>"#{object_name}_#{method}_#{unchecked_value}")
end
def number_to_accountancy(value)
number = value.to_f
if number.zero?
return ''
else
number_to_currency(number, :precision=>2, :format=>'%n', :delimiter=>' ', :separator=>',')
end
end
def number_to_management(value)
number = value.to_f
number_to_currency(number, :precision=>2, :format=>'%n', :delimiter=>' ', :separator=>',')
end
# Take an extra argument which will translate
def number_to_money(amount, currency, options={})
return unless amount and currency
return currency.to_currency.localize(amount, options)
end
def preference(name)
# name = self.controller.controller_name.to_s << name.to_s if name.to_s.match(/^\./)
@current_company.preference(name)
end
def locale_selector
# , :selected=>::I18n.locale)
locales = ::I18n.active_locales.sort{|a,b| a.to_s<=>b.to_s}
locale = nil # ::I18n.locale
if params[:locale].to_s.match(/^[a-z][a-z][a-z]$/)
locale = params[:locale].to_sym if locales.include? params[:locale].to_sym
end
locale ||= ::I18n.locale||::I18n.default_locale
options = locales.collect do |l|
content_tag(:option, ::I18n.translate("i18n.name", :locale=>l), {:value=>l, :dir=>::I18n.translate("i18n.dir", :locale=>l)}.merge(locale == l ? {:selected=>true} : {}))
end.join.html_safe
select_tag("locale", options, "data-redirect"=>url_for())
end
# Re-writing of link_to helper
def link_to(*args, &block)
if block_given?
options = args.first || {}
html_options = args.second
link_to(capture(&block), options, html_options)
else
name = args[0]
options = args[1] || {}
html_options = args[2] || {}
if options.is_a? Hash
return (html_options[:keep] ? "<a class='forbidden'>#{name}</a>".html_safe : "") unless authorized?(options)
end
html_options = convert_options_to_data_attributes(options, html_options)
url = url_for(options)
if html_options
html_options = html_options.stringify_keys
href = html_options['href']
tag_options = tag_options(html_options)
else
tag_options = nil
end
href_attr = "href=\""+url+"\"" unless href
"<a #{href_attr}#{tag_options}>".html_safe+(name || url)+"</a>".html_safe
end
end
def li_link_to(*args)
options = args[1] || {}
# if authorized?({:controller=>controller_name, :action=>action_name}.merge(options))
if authorized?({:controller=>controller_name, :action=>:index}.merge(options))
content_tag(:li, link_to(*args).html_safe)
else
''
end
end
def countries
[[]]+t('countries').to_a.sort{|a, b| a[1].ascii.to_s<=>b[1].ascii.to_s}.collect{|a| [a[1].to_s, a[0].to_s]}
end
def currencies
I18n.active_currencies.values.sort{|a, b| a.name.ascii.to_s<=>b.name.ascii.to_s}.collect{|c| [c.label, c.code]}
end
def languages
I18n.valid_locales.collect{|l| [t("languages.#{l}"), l.to_s]}.to_a.sort{|a, b| a[0].ascii.to_s<=>b[0].ascii.to_s}
end
def back_url
if session[:history].is_a?(Array) and session[:history][0].is_a?(Hash)
return session[:history][0][:url]
else
return :back
end
end
def link_to_back(options={})
link_to(tg(options[:label]||'back'), back_url)
end
#
#
def evalue(object, attribute, options={})
label, value = attribute_item(object, attribute, options={})
if options[:orient] == :vertical
code = content_tag(:tr, content_tag(:td, label.to_s, :class=>:label))
code << content_tag(:tr, content_tag(:td, value.to_s, :class=>:value))
return content_tag(:table, code, :class=>"evalue verti")
else
code = content_tag(:td, label.to_s, :class=>:label)
code << content_tag(:td, value.to_s, :class=>:value)
return content_tag(:table, content_tag(:tr, code), :class=>"evalue hori")
end
end
def attribute_item(object, attribute, options={})
value_class = 'value'
if object.is_a? String
label = object
value = attribute
value = value.to_s unless [String, TrueClass, FalseClass].include? value.class
else
# label = object.class.human_attribute_name(attribute.to_s)
value = object.send(attribute)
model_name = object.class.name.underscore
default = ["activerecord.attributes.#{model_name}.#{attribute.to_s}_id".to_sym]
default << "activerecord.attributes.#{model_name}.#{attribute.to_s[0..-7]}".to_sym if attribute.to_s.match(/_label$/)
default << "attributes.#{attribute.to_s}".to_sym
default << "attributes.#{attribute.to_s}_id".to_sym
label = ::I18n.translate("activerecord.attributes.#{model_name}.#{attribute.to_s}".to_sym, :default=>default)
if value.is_a? ActiveRecord::Base
record = value
value = record.send(options[:label]||[:label, :name, :code, :number, :inspect].detect{|x| record.respond_to?(x)})
options[:url] = {:action=>:show} if options[:url].is_a? TrueClass
if options[:url].is_a? Hash
options[:url][:id] ||= record.id
# raise [model_name.pluralize, record, record.class.name.underscore.pluralize].inspect
options[:url][:controller] ||= record.class.name.underscore.pluralize
end
else
options[:url] = {:action=>:show} if options[:url].is_a? TrueClass
if options[:url].is_a? Hash
options[:url][:controller] ||= object.class.name.underscore.pluralize
options[:url][:id] ||= object.id
end
end
value_class << ' code' if attribute.to_s == "code"
end
if [TrueClass, FalseClass].include? value.class
value = content_tag(:div, "", :class=>"checkbox-#{value}")
elsif attribute.to_s.match(/(^|_)currency$/)
value = value.to_currency.label
elsif options[:currency] and value.is_a?(Numeric)
value = ::I18n.localize(value, :currency=>(options[:currency].is_a?(TrueClass) ? object.send(:currency) : options[:currency]))
value = link_to(value.to_s, options[:url]) if options[:url]
elsif value.respond_to?(:strftime) or value.is_a?(Numeric)
value = ::I18n.localize(value)
value = link_to(value.to_s, options[:url]) if options[:url]
elsif options[:duration]
duration = value
duration = duration*60 if options[:duration]==:minutes
duration = duration*3600 if options[:duration]==:hours
hours = (duration/3600).floor.to_i
minutes = (duration/60-60*hours).floor.to_i
seconds = (duration - 60*minutes - 3600*hours).round.to_i
value = tg(:duration_in_hours_and_minutes, :hours=>hours, :minutes=>minutes, :seconds=>seconds)
value = link_to(value.to_s, options[:url]) if options[:url]
elsif value.is_a? String
classes = []
classes << "code" if attribute.to_s == "code"
classes << value.class.name.underscore
value = link_to(value.to_s, options[:url]) if options[:url]
value = content_tag(:div, value.html_safe, :class=>classes.join(" "))
end
return label, value
end
def attributes_list(record, options={}, &block)
columns = options[:columns] || 3
attribute_list = AttributesList.new
raise ArgumentError.new("One parameter needed") unless block.arity == 1
yield attribute_list if block_given?
unless options[:without_stamp]
attribute_list.attribute :creator
attribute_list.attribute :created_at
attribute_list.attribute :updater
attribute_list.attribute :updated_at
# attribute_list.attribute :lock_version
end
code = ""
size = attribute_list.items.size
if size > 0
column_height = (size.to_f/columns.to_f).ceil
column_height.times do |c|
line = ""
columns.times do |i|
args = attribute_list.items[i*column_height+c] # [c*columns+i]
next if args.nil?
label, value = if args[0] == :custom
attribute_item(*args[1])
elsif args[0] == :attribute
attribute_item(record, *args[1])
end
line << content_tag(:td, label, :class=>:label) << content_tag(:td, value, :class=>:value)
end
code << content_tag(:tr, line.html_safe)
end
code = content_tag(:table, code.html_safe, :class=>"attributes-list")
end
return code.html_safe
end
class AttributesList
attr_reader :items
def initialize()
@items = []
end
def attribute(*args)
@items << [:attribute, args]
end
def custom(*args)
@items << [:custom, args]
end
end
def last_page(menu)
session[:last_page][menu.to_s]||url_for(:controller=>:dashboards, :action=>menu)
end
def doctype_tag
return "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN\" \"http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd\">".html_safe
end
# Permits to use themes for Ekylibre
# stylesheet_link_tag 'application', 'list', 'list-colors'
# stylesheet_link_tag 'print', :media=>'print'
def theme_link_tag(name=nil)
name ||= 'tekyla'
code = ""
Dir.chdir(Rails.root.join("app", "assets", "stylesheets", "themes", name)) do
for media in ["all", "embossed", "handheld", "print", "projection", "screen", "speech", "tty", "tv"]
if File.exist?(media+".css") or File.exist?(media+".css.scss")
code << stylesheet_link_tag("themes/#{name}/#{media}.css", :media=>media)+"\n"
end
end
end
return code.html_safe
end
def theme_button(name, theme='tekyla')
image_path("themes/#{theme}/buttons/#{name}.png").to_s
end
def resizable?
return (session[:view_mode] == "resized" ? true : false)
end
def top_tag
session[:last_page] ||= {}
render :partial=>"layouts/top"
end
def title_tag
r = reverse_menus
title = if @current_company
if r.empty?
tc(:page_title_special, :company_code=>@current_company["code"], :company_name=>@current_company["name"], :action=>controller.human_action_name)
else
tc(:page_title, :company_code=>@current_company["code"], :company_name=>@current_company["name"], :action=>controller.human_action_name, :menu=>tl("menus.#{r[0]}"))
end
else
tc(:page_title_by_default, :action=>controller.human_action_name)
end
return ("<title>" << h(title) << "</title>").html_safe
end
def title_header_tag
titles = controller.human_action_name
content_tag(:h1, titles, :class=>"title", :title=>titles)
end
def subheading(key, options={})
content_tag(:div, tl(key, options), :class=>"subheading")
end
def side_tag # (submenu = self.controller.controller_name.to_sym)
path = reverse_menus
return '' if path.nil?
render(:partial=>'layouts/side', :locals=>{:path=>path})
end
def side_module(name, options={}, &block)
session[:modules] ||= {}
session[:modules][name.to_s] = true unless [TrueClass, FalseClass].include?(session[:modules][name.to_s].class)
shown = session[:modules][name]
html = ""
html << "<div class='sd-module#{' '+options[:class].to_s if options[:class]}#{' collapsed' unless shown}'>"
html << "<div class='sd-title'>"
html << link_to("", {:action=>:toggle_module, :controller=>:interfacers}, "data-toggle-module"=>name, :class=>(shown ? :hide : :show))
html << "<h2>" + (options[:title]||tl(name)) + "</h2>"
html << "</div>"
html << "<div class='sd-content'" + (shown ? '' : ' style="display: none"') + ">"
html << capture(&block)
html << "</div>"
html << "</div>"
return html.html_safe
end
# def toolbar_tag
# html = ""
# if action_name.to_s == "show"
# buttons = ""
# buttons << tool_to("???", {:action => :show}, :class => :large)
# buttons << tool_to("???", {:action => :edit}, :class => :large)
# buttons << tool_to("???", {:action => :destroy}, :class => :large)
# html << content_tag(:div, buttons.html_safe, :id => :toolbar, :class => :toolbar)
# end
# return html.html_safe
# end
def notification_tag(mode)
# content_tag(:div, flash[mode], :class=>'flash ' << mode.to_s) unless flash[mode].blank?
code = ''
if flash[:notifications].is_a?(Hash) and flash[:notifications][mode].is_a?(Array)
for message in flash[:notifications][mode]
message.force_encoding('UTF-8') if message.respond_to? :force_encoding
code << "<div class='flash #{mode}'><div class='icon'></div><div class='message'><h3>#{tg('notifications.' << mode.to_s)}</h3><p>#{h(message).gsub(/\n/, '<br/>')}</p></div><div class='end'></div></div>"
end
end
code.html_safe
end
def notifications_tag
return notification_tag(:error) <<
notification_tag(:warning) <<
notification_tag(:success) <<
notification_tag(:information)
end
def table_of(array, html_options={}, &block)
coln = html_options.delete(:columns)||3
html, line, size = "", "", 0
for item in array
line << content_tag(:td, capture(item, &block))
size += 1
if size >= coln
html << content_tag(:tr, line).html_safe
line, size = "", 0
end
end
html << content_tag(:tr, line).html_safe unless line.blank?
return content_tag(:table, html, html_options).html_safe
end
def wikize(content, options={})
# AJAX fails with XHTML entities because there is no DOCTYPE in AJAX response
content.gsub!(/(\w)(\?|\:)([\s$])/ , '\1~\2\3' )
content.gsub!(/(\w+)[\ \~]+(\?|\:)/ , '\1~\2' )
content.gsub!(/\~/ , ' ')
content.gsub!(/^\ \ \*\ +(.*)\ *$/ , '<ul><li>\1</li></ul>')
content.gsub!(/<\/ul>\n<ul>/ , '')
content.gsub!(/^\ \ \-\ +(.*)\ *$/ , '<ol><li>\1</li></ol>')
content.gsub!(/<\/ol>\n<ol>/ , '')
content.gsub!(/^\ \ \?\ +(.*)\ *$/ , '<dl><dt>\1</dt></dl>')
content.gsub!(/^\ \ \!\ +(.*)\ *$/ , '<dl><dd>\1</dd></dl>')
content.gsub!(/<\/dl>\n<dl>/ , '')
content.gsub!(/^>>>\ +(.*)\ *$/ , '<p class="notice">\1</p>')
content.gsub!(/<\/p>\n<p class="notice">/ , '<br/>')
content.gsub!(/^!!!\ +(.*)\ *$/ , '<p class="warning">\1</p>')
content.gsub!(/<\/p>\n<p class="warning">/ , '<br/>')
content.gsub!(/\{\{\ *[^\}\|]+\ *(\|[^\}]+)?\}\}/) do |data|
data = data.squeeze(' ')[2..-3].split('|')
align = {' '=>'center', ' x'=>'right', 'x '=>'left', 'xx'=>''}[(data[0][0..0] + data[0][-1..-1]).gsub(/[^\ ]/,'x')]
title = data[1]||data[0].split(/[\:\\\/]+/)[-1].humanize
src = data[0].strip
if src.match(/^theme:/)
# src = image_path("/themes/#{@current_theme}/images/#{src.split(':')[1]}")
path = src.split(':')[1]
path.gsub!(/^buttons/, "icons")
src = image_path("themes/#{@current_theme}/#{path}")
else
src = image_path(src)
end
'<img class="md md-' + align + '" alt="' + title + '" title="' + title + '" src="' + src + '"/>'
end
options[:url] ||= {}
content = content.gsub(/\[\[>[^\|]+\|[^\]]*\]\]/) do |link|
link = link[3..-3].split('|')
url = link[0].split(/[\/\?\&]+/)
url = options[:url].merge(:controller=>url[0], :action=>url[1])
(authorized?(url) ? link_to(link[1], url) : link[1])
end
options[:method] = :get
content = content.gsub(/\[\[[\w\-]+\|[^\]]*\]\]/) do |link|
link = link[2..-3].split('|')
url = url_for(options[:url].merge(:id=>link[0]))
link_to(link[1].html_safe, url, {:remote=>true, "data-type"=>:html}.merge(options)) # REMOTE
end
content = content.gsub(/\[\[[\w\-]+\]\]/) do |link|
link = link[2..-3]
url = url_for(options[:url].merge(:id=>link))
link_to(link.html_safe, url, {:remote=>true, "data-type"=>:html}.merge(options)) # REMOTE
end
for x in 1..6
n = 7-x
content.gsub!(/^\s*\={#{n}}\s*([^\=]+)\s*\={#{n}}/, "<h#{x}>\\1</h#{x}>")
end
content.gsub!(/^\ \ (.*\w+.*)$/, ' <pre>\1</pre>')
content.gsub!(/([^\:])\/\/([^\s][^\/]+)\/\//, '\1<em>\2</em>')
content.gsub!(/\'\'([^\s][^\']+)\'\'/, '<code>\1</code>')
content.gsub!(/(^)([^\s\<][^\s].*)($)/, '<p>\2</p>') unless options[:without_paragraph]
content.gsub!(/^\s*(\<a.*)\s*$/, '<p>\1</p>')
content.gsub!(/\*\*([^\s\*]+)\*\*/, '<strong>\1</strong>')
content.gsub!(/\*\*([^\s\*][^\*]*[^\s\*])\*\*/, '<strong>\1</strong>')
content.gsub!(/(^|[^\*])\*([^\*]|$)/, '\1∗\2')
content.gsub!("</p>\n<p>", "\n")
content.strip!
#raise Exception.new content
return content.html_safe
end
def article(file, options={})
content = nil
if File.exists?(file)
File.open(file, 'r'){|f| content = f.read}
content = content.split(/\n/)[1..-1].join("\n") if options.delete(:without_title)
content = wikize(content.to_s, options)
end
return content
end
# name = name.to_s
# content = ''
# file_name, locale = '', nil
# for locale in [I18n.locale, I18n.default_locale]
# help_dir = Rails.root.join("config", "locales", locale.to_s, "help")
# file_name = [name, name.split("-")[0].to_s << "-index"].detect do |pattern|
# File.exists? help_dir.join(pattern << ".txt")
# end
# break unless file_name.blank?
# end
# file_text = Rails.root.join("config", "locales", locale.to_s, "help", file_name.to_s << ".txt")
# if File.exists?(file_text)
# File.open(file_text, 'r') do |file|
# content = file.read
# end
# content = wikize(content, options)
# end
# return content
# end
# Unagi 鰻
# Flexible module management
def unagi(options={})
u = Unagi.new
yield u
tag = ""
for c in u.cells
code = content_tag(:h2, tl(c.title, c.options)) << content_tag(:div, capture(&c.block).html_safe)
tag << content_tag(:div, code.html_safe, :class=>:menu)
end
return content_tag(:div, tag.html_safe, :class=>:unagi)
end
class Unagi
attr_reader :cells
def initialize
@cells = []
end
def cell(title, options={}, &block)
@cells << UnagiCell.new(title, options, &block)
end
end
class UnagiCell
attr_reader :title, :options, :block
def initialize(title, options={}, &block)
@title = title.to_s
@options = options
@block = block
end
def content
"aAAAAAAAAAAAAAAAAAA" << capture(@block).to_s
end
end
# Kujaku 孔雀
# Search bar
def kujaku(url={}, &block)
k = Kujaku.new(caller[0].split(":in ")[0])
if block_given?
yield k
else
k.text
end
return "" if k.criteria.size.zero?
tag = ""
k.criteria.each_with_index do |c, index|
code, options = "", c[:options]||{}
if c[:type] == :mode
code = content_tag(:label, options[:label]||tg(:mode))
name = c[:name]||:mode
params[name] ||= c[:modes][0].to_s
i18n_root = options[:i18n_root]||'labels.criterion_modes.'
for mode in c[:modes]
radio = radio_button_tag(name, mode, params[name] == mode.to_s)
radio << " "
radio << content_tag(:label, ::I18n.translate("#{i18n_root}#{mode}"), :for=>"#{name}_#{mode}")
code << " ".html_safe << content_tag(:span, radio.html_safe, :class=>:rad)
end
elsif c[:type] == :radio
code = content_tag(:label, options[:label]||tg(:state))
params[c[:name]] ||= c[:states][0].to_s
i18n_root = options[:i18n_root]||"labels.#{controller_name}_states."
for state in c[:states]
radio = radio_button_tag(c[:name], state, params[c[:name]] == state.to_s)
radio << " ".html_safe << content_tag(:label, ::I18n.translate("#{i18n_root}#{state}"), :for=>"#{c[:name]}_#{state}")
code << " ".html_safe << content_tag(:span, radio.html_safe, :class=>:rad)
end
elsif c[:type] == :text
code = content_tag(:label, options[:label]||tg(:search))
name = c[:name]||:q
session[:kujaku] = {} unless session[:kujaku].is_a? Hash
params[name] = session[:kujaku][c[:uid]] = (params[name]||session[:kujaku][c[:uid]])
code << " ".html_safe << text_field_tag(name, params[name])
elsif c[:type] == :date
code = content_tag(:label, options[:label]||tg(:select_date))
name = c[:name]||:d
code << " ".html_safe << date_field_tag(name, params[name])
elsif c[:type] == :crit
code << send("#{c[:name]}_crit", *c[:args])
elsif c[:type] == :criterion
code << capture(&c[:block])
end
html_options = (c[:html_options]||{}).merge(:class=>"crit")
html_options[:class] << " hideable" unless index.zero?
code = content_tag(:td, code.html_safe, html_options)
if index.zero?
launch = submit_tag(tl(:search_go), 'data-disable-with' => tg(:please_wait), :name=>nil)
# TODO: Add link to unhide hidden criteria
code << content_tag(:td, launch, :rowspan=>k.criteria.size, :class=>:submit)
first = false
end
tag << content_tag(:tr, code.html_safe)
end
tag = form_tag(url, :method=>:get) {content_tag(:table, tag.html_safe)}
id = Time.now.to_i.to_s(36)+(10000*rand).to_i.to_s(36)
content_for(:popover, content_tag(:div, tag.to_s.html_safe, :class=>"kujaku popover", :id => id))
tb = content_tag(:a, content_tag(:div, nil, :class=>:icon) + content_tag(:div, "Rechercher", :class => :text), :class => "btn search", "data-toggle-visibility" => "##{id}")
content_for(:toolbar, tb)
return ""
end
class Kujaku
attr_reader :criteria
def initialize(uid)
@uid = uid
@criteria = []
end
# def mode(*modes)
# options = modes.delete_at(-1) if modes[-1].is_a? Hash
# options = {} unless options.is_a? Hash
# @criteria << {:type=>:mode, :modes=>modes, :options=>options}
# end
def radio(*states)
options = states.delete_at(-1) if states[-1].is_a? Hash
options = {} unless options.is_a? Hash
name = options.delete(:name)||:s
add_criterion :radio, :name=>name, :states=>states, :options=>options
end
def text(name=nil, options={})
name ||= :q
add_criterion :text, :name=>name, :options=>options
end
def date(name=nil, options={})
name ||= :d
add_criterion :date, :name=>name, :options=>options
end
def crit(name=nil, *args)
add_criterion :crit, :name=>name, :args=>args
end
def criterion(html_options={}, &block)
raise ArgumentError.new("No block given") unless block_given?
add_criterion :criterion, :block=>block, :html_options=>html_options
end
private
def add_criterion(type=nil, options={})
@criteria << options.merge(:type=>type, :uid=>"#{@uid}:"+@criteria.size.to_s)
end
end
# TABBOX
def tabbox(id, options={})
tb = Tabbox.new(id)
yield tb
return '' if tb.tabs.size.zero?
tabs = ''
taps = ''
session[:tabbox] ||= {}
for tab in tb.tabs
session[:tabbox][tb.id] ||= tab[:index]
style_name = (session[:tabbox][tb.id] == tab[:index] ? "current " : "")
tabs << content_tag(:span, tab[:name], :class=>style_name + "tab", "data-tabbox-index"=>tab[:index])
taps << content_tag(:div, capture(&tab[:block]).html_safe, :class=>style_name + "tabpanel", "data-tabbox-index"=>tab[:index])
end
return content_tag(:div, :class=>options[:class]||"tabbox", :id=>tb.id, "data-tabbox"=>url_for(:controller=>:interfacers, :action=>:toggle_tab, :id=>tb.id)) do
code = content_tag(:div, tabs.html_safe, :class=>:tabs)
code << content_tag(:div, taps.html_safe, :class=>:tabpanels)
code
end
end
class Tabbox
attr_accessor :tabs, :id
def initialize(id)
@tabs = []
@id = id.to_s
@sequence = 0
end
# Register a tab with a block of code
# The name of tab use I18n searching in :
# - labels.<tabbox_id>_tabbox.<tab_name>
# - labels.<tab_name>
def tab(name, options={}, &block)
raise ArgumentError.new("No given block") unless block_given?
if name.is_a?(Symbol)
options[:default] = [] unless options[:default].is_a?(Array)
options[:default] << "labels.#{name}".to_sym
options[:default] << "attributes.#{name}".to_sym
name = ::I18n.translate("labels.#{@id}_tabbox.#{name}", options)
end
@tabs << {:name=>name, :index=>(@sequence*1).to_s(36), :block=>block}
@sequence += 1
end
end
# TOOLBAR
def menu_to(name, url, options={})
raise ArgumentError.new("##{__method__} cannot use blocks") if block_given?
icon = (options.has_key?(:menu) ? options.delete(:menu) : url.is_a?(Hash) ? url[:action] : nil)
sprite = options.delete(:sprite) || "icons-16"
options[:class] = (options[:class].blank? ? 'mn' : options[:class]+' mn')
options[:class] += ' '+icon.to_s if icon
link_to(url, options) do
(icon ? content_tag(:span, '', :class=>"icon")+content_tag(:span, name, :class=>"text") : content_tag(:span, name, :class=>"text"))
end
end
def tool_to(name, url, options={})
raise ArgumentError.new("##{__method__} cannot use blocks") if block_given?
icon = (options.has_key?(:tool) ? options.delete(:tool) : url.is_a?(Hash) ? url[:action] : nil)
sprite = options.delete(:sprite) || "icons-16"
options[:class] = (options[:class].blank? ? 'btn' : options[:class].to_s+' btn')
options[:class] += ' '+icon.to_s if icon
options[:class] += ' '+options.delete(:size).to_s if options.has_key?(:size)
link_to(url, options) do
(icon ? content_tag(:span, '', :class=>"icon")+content_tag(:span, name, :class=>"text") : content_tag(:span, name, :class=>"text"))
end
end
def toolbar(options={}, &block)
code = '[EmptyToolbarError]'
if block_given?
toolbar = Toolbar.new
if block
if block.arity < 1
self.instance_values.each do |k,v|
toolbar.instance_variable_set("@" + k.to_s, v)
end
toolbar.instance_eval(&block)
else
block[toolbar]
end
end
toolbar.link :back if options[:back]
# To HTML
code = ''
# call = 'views.' << caller.detect{|x| x.match(/\/app\/views\//)}.split(/\/app\/views\//)[1].split('.')[0].gsub(/\//,'.') << '.'
for tool in toolbar.tools
nature, args = tool[0], tool[1]
if nature == :link
name = args[0]
args[1] ||= {}
args[2] ||= {}
args[0] = ::I18n.t("actions.#{args[1][:controller]||controller_name}.#{name}".to_sym, {:default=>["labels.#{name}".to_sym]}.merge(args[2].delete(:i18n)||{})) if name.is_a? Symbol
if name.is_a? Symbol and name!=:back
args[1][:action] ||= name
end
code << tool_to(*args) if authorized?(args[1])
elsif nature == :print
dn, args, url = tool[1], tool[2], tool[3]
url[:controller] ||= controller_name
for dt in @current_company.document_templates.find(:all, :conditions=>{:nature=>dn.to_s, :active=>true}, :order=>:name)
code << tool_to(tc(:print_with_template, :name=>dt.name), url.merge(:template=>dt.code), :tool=>:print) if authorized?(url)
end
elsif nature == :mail
args[2] ||= {}
email_address = ERB::Util.html_escape(args[0])
extras = %w{ cc bcc body subject }.map { |item|
option = args[2].delete(item) || next
"#{item}=#{Rack::Utils.escape(option).gsub("+", "%20")}"
}.compact
extras = extras.empty? ? '' : '?' + ERB::Util.html_escape(extras.join('&'))
# code << content_tag(:div, mail_to(*args), :class=>:tool)
code << tool_to(args[1], "mailto:#{email_address}#{extras}".html_safe, :tool=>:mail)
elsif nature == :missing
action, record, tag_options = tool[1], tool[2], tool[3]
tag_options = {} unless tag_options.is_a? Hash
url = {}
url.update(tag_options.delete(:params)) if tag_options[:params].is_a? Hash
url[:controller] ||= controller_name
url[:action] = action
url[:id] = record.id
code << tool_to(t("actions.#{url[:controller]}.#{action}", record.attributes.symbolize_keys), url, tag_options) if authorized?(url)
end
end
if code.strip.length>0
# # code = content_tag(:ul, code.html_safe) << content_tag(:div)
# # code = content_tag(:h2, t(call << options[:title].to_s)) << code if options[:title]
if @not_first_toolbar
code = content_tag(:div, code.html_safe, :class=>'toolbar' + (options[:class].nil? ? '' : ' ' << options[:class].to_s)) + content_tag(:div, nil, :class=>:clearfix)
end
end
else
raise Exception.new('No block given for toolbar')
end
if @not_first_toolbar
return code.html_safe
else
content_for :toolbar, code.html_safe
@not_first_toolbar = true
return ""
end
end
class Toolbar
attr_reader :tools
def initialize()
@tools = []
end
def link(*args)
@tools << [:link, args]
end
def mail(*args)
@tools << [:mail, args]
end
def print(*args)
# TODO reactive print
# @tools << [:print, args]
end
# def update(record, url={})
# @tools << [:update, record, url]
# end
def method_missing(method_name, *args, &block)
raise ArgumentError.new("Block can not be accepted") if block_given?
if method_name.to_s.match(/^print_\w+$/)
nature = method_name.to_s.gsub(/^print_/, '').to_sym
raise Exception.new("Cannot use method :print_#{nature} because nature '#{nature}' does not exist.") unless parameters = DocumentTemplate.document_natures[nature]
url = args.delete_at(-1) if args[-1].is_a?(Hash)
raise ArgumentError.new("Parameters don't match. #{parameters.size} expected, got #{args.size} (#{[args, options].inspect}") unless args.size == parameters.size
url ||= {}
url[:action] ||= :show
url[:format] = :pdf
url[:id] ||= args[0].id if args[0].respond_to?(:id) and args[0].class.ancestors.include?(ActiveRecord::Base)
url[:n] = nature
parameters.each_index do |i|
url[parameters[i][0]] = args[i]
end
@tools << [:print, nature, args, url]
else
raise ArgumentError.new("First argument must be an ActiveRecord::Base. (#{method_name})") unless args[0].class.ancestors.include? ActiveRecord::Base
@tools << [:missing, method_name, args[0], args[1]]
end
end
end
def error_messages(object)
object = instance_variable_get("@#{object}") unless object.respond_to?(:errors)
return unless object.respond_to?(:errors)
unless (count = object.errors.size).zero?
I18n.with_options :scope => [:errors, :template] do |locale|
header_message = locale.t :header, :count => count, :model => object.class.model_name.human
introduction = locale.t(:body)
messages = object.errors.full_messages.map do |msg|
content_tag(:li, msg)
end.join.html_safe
message = ""
message << content_tag(:h3, header_message) unless header_message.blank?
message << content_tag(:p, introduction) unless introduction.blank?
message << content_tag(:ul, messages)
html = ''
html << content_tag(:div, "", :class => :icon)
html << content_tag(:div, message.html_safe, :class => :message)
html << content_tag(:div, "", :class => :end)
return content_tag(:div, html.html_safe, :class=>"flash error")
end
else
''
end
end