-
Notifications
You must be signed in to change notification settings - Fork 1
/
railsDocument.js
executable file
·1993 lines (1573 loc) · 51.7 KB
/
railsDocument.js
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
/** RailsDocument v0.2 - Built with build.js */
var EODateParser = (function(Date,undefined) {
var pad = function(s) {
return (s.toString().length === 1) ? "0" + s: s;
};
var checkerValue = function(target, func, value) {
if (typeof value !== "undefined") {
target[func](value);
}
return target;
}
var returnObj = {
"stringify" : function(self, format) {
if (!format || !self || format === "" || !format.replace) {
return null;
}
return format.replace(
/dd?d?d?|MM?M?M?|yy?y?y?|hh?|HH?|mm?|ss?/g,
function(format) {
switch (format) {
case "hh":
return pad(self.getUTCHours() < 13 ? self.getUTCHours() : (self.getUTCHours() - 12));
case "h":
return self.getUTCHours() < 13 ? self.getUTCHours() : (self.getUTCHours() - 12);
case "HH":
return pad(self.getUTCHours());
case "H":
return self.getUTCHours();
case "mm":
return pad(self.getUTCMinutes());
case "m":
return self.getUTCMinutes();
case "ss":
return pad(self.getUTCSeconds());
case "s":
return self.getUTCSeconds();
case "yyyy":
return self.getUTCFullYear();
case "yy":
return self.getUTCFullYear().toString().substring(2, 4);
case "dd":
return pad(self.getUTCDate());
case "d":
return self.getUTCDate().toString();
case "MM":
return pad((self.getUTCMonth() + 1));
case "M":
return self.getUTCMonth() + 1;
default:
return "";
}
}
);
},
"parser" : function(input, format , returnDate) {
if (!format || !input || input === "" || format === "" || !input.match || !format.replace) {
return null;
}
var parts = input.match(/(\d+)/g);
if (parts == null) {
return null;
}
var i = 0;
var fmt = {};
// extract date-part indexes from the format
format.replace(/dd?d?d?|MM?M?M?|yy?y?y?|hh?|HH?|mm?|ss?/g, function(part) {
fmt[part] = i++;
});
if (!returnDate) {
returnDate = new Date(0,0,0,0,0,0,0);
}
//todo: hh / h / yy
checkerValue(returnDate , "setUTCFullYear" , parts[fmt['yyyy']]);
checkerValue(returnDate , "setUTCMonth" , (parts[fmt['MM']] ? parts[fmt['MM']] - 1 : undefined));
checkerValue(returnDate , "setUTCMonth" , (parts[fmt['M']] ? parts[fmt['M']] - 1 : undefined));
checkerValue(returnDate , "setUTCDate" , parts[fmt['dd']]);
checkerValue(returnDate , "setUTCDate" , parts[fmt['d']]);
checkerValue(returnDate , "setUTCHours" , parts[fmt['HH']]);
checkerValue(returnDate , "setUTCHours" , parts[fmt['H']]);
checkerValue(returnDate , "setUTCMinutes" , parts[fmt['mm']]);
checkerValue(returnDate , "setUTCMinutes" , parts[fmt['m']]);
checkerValue(returnDate , "setUTCSeconds" , parts[fmt['ss']]);
checkerValue(returnDate , "setUTCSeconds" , parts[fmt['s']]);
return returnDate;
}
}
//sugar / monkey patch
if (!Date.prototype.formatedString) {
Date.prototype.formatedString = function(format) {
return returnObj.stringify(this, format);
}
}
if (!Date.parserString) {
Date.parserString = returnObj.parser;
}
if (!Date.prototype.parserString) {
Date.prototype.parserString = function(input, format) {
return returnObj.parser(input, format, this);
};
}
return returnObj;
})(Date);
/*
Copyright (c) 2007 Ryan Schuft ([email protected])
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/*
This code is based in part on the work done in Ruby to support
infection as part of Ruby on Rails in the ActiveSupport's Inflector
and Inflections classes. It was initally ported to Javascript by
Ryan Schuft ([email protected]).
The code is available at http://code.google.com/p/inflection-js/
The basic usage is:
1. Include this script on your web page.
2. Call functions on any String object in Javascript
Currently implemented functions:
String.pluralize(plural) == String
renders a singular English language noun into its plural form
normal results can be overridden by passing in an alternative
String.singularize(singular) == String
renders a plural English language noun into its singular form
normal results can be overridden by passing in an alterative
String.camelize(lowFirstLetter) == String
renders a lower case underscored word into camel case
the first letter of the result will be upper case unless you pass true
also translates "/" into "::" (underscore does the opposite)
String.underscore() == String
renders a camel cased word into words seperated by underscores
also translates "::" back into "/" (camelize does the opposite)
String.humanize(lowFirstLetter) == String
renders a lower case and underscored word into human readable form
defaults to making the first letter capitalized unless you pass true
String.capitalize() == String
renders all characters to lower case and then makes the first upper
String.dasherize() == String
renders all underbars and spaces as dashes
String.titleize() == String
renders words into title casing (as for book titles)
String.demodulize() == String
renders class names that are prepended by modules into just the class
String.tableize() == String
renders camel cased singular words into their underscored plural form
String.classify() == String
renders an underscored plural word into its camel cased singular form
String.foreign_key(dropIdUbar) == String
renders a class name (camel cased singular noun) into a foreign key
defaults to seperating the class from the id with an underbar unless
you pass true
String.ordinalize() == String
renders all numbers found in the string into their sequence like "22nd"
*/
/*
This function adds plurilization support to every String object
Signature:
String.pluralize(plural) == String
Arguments:
plural - String (optional) - overrides normal output with said String
Returns:
String - singular English language nouns are returned in plural form
Examples:
"person".pluralize() == "people"
"octopus".pluralize() == "octopi"
"Hat".pluralize() == "Hats"
"person".pluralize("guys") == "guys"
*/
if(!String.prototype.pluralize)String.prototype.pluralize=function(plural)
{
var str=this;
if(plural)str=plural;
else
{
var uncountable=false;
for(var x=0;!uncountable&&x<this._uncountable_words.length;x++)
uncountable=(this._uncountable_words[x]==str.toLowerCase());
if(!uncountable)
{
var matched=false;
for(var x=0;!matched&&x<this._plural_rules.length;x++)
{
matched=str.match(this._plural_rules[x][0]);
if(matched)
str=str.replace(this._plural_rules[x][0],this._plural_rules[x][1]);
}
}
}
return str;
};
/*
This function adds singularization support to every String object
Signature:
String.singularize(singular) == String
Arguments:
singular - String (optional) - overrides normal output with said String
Returns:
String - plural English language nouns are returned in singular form
Examples:
"people".singularize() == "person"
"octopi".singularize() == "octopus"
"Hats".singularize() == "Hat"
"guys".singularize("person") == "person"
*/
if(!String.prototype.singularize)
String.prototype.singularize=function(singular)
{
var str=this;
if(singular)str=singular;
else
{
var uncountable=false;
for(var x=0;!uncountable&&x<this._uncountable_words.length;x++)
uncountable=(this._uncountable_words[x]==str.toLowerCase());
if(!uncountable)
{
var matched=false;
for(var x=0;!matched&&x<this._singular_rules.length;x++)
{
matched=str.match(this._singular_rules[x][0]);
if(matched)
str=str.replace(this._singular_rules[x][0],
this._singular_rules[x][1]);
}
}
}
return str;
};
/*
This is a list of nouns that use the same form for both singular and plural.
This list should remain entirely in lower case to correctly match Strings.
You can override this list for all Strings or just one depending on if you
set the new values on prototype or on a given String instance.
*/
if(!String.prototype._uncountable_words)String.prototype._uncountable_words=[
'equipment','information','rice','money','species','series','fish','sheep',
'moose','deer','news'
];
/*
These rules translate from the singular form of a noun to its plural form.
You can override this list for all Strings or just one depending on if you
set the new values on prototype or on a given String instance.
*/
if(!String.prototype._plural_rules)String.prototype._plural_rules=[
[new RegExp('(m)an$','gi'),'$1en'],
[new RegExp('(pe)rson$','gi'),'$1ople'],
[new RegExp('(child)$','gi'),'$1ren'],
[new RegExp('^(ox)$','gi'),'$1en'],
[new RegExp('(ax|test)is$','gi'),'$1es'],
[new RegExp('(octop|vir)us$','gi'),'$1i'],
[new RegExp('(alias|status)$','gi'),'$1es'],
[new RegExp('(bu)s$','gi'),'$1ses'],
[new RegExp('(buffal|tomat|potat)o$','gi'),'$1oes'],
[new RegExp('([ti])um$','gi'),'$1a'],
[new RegExp('sis$','gi'),'ses'],
[new RegExp('(?:([^f])fe|([lr])f)$','gi'),'$1$2ves'],
[new RegExp('(hive)$','gi'),'$1s'],
[new RegExp('([^aeiouy]|qu)y$','gi'),'$1ies'],
[new RegExp('(x|ch|ss|sh)$','gi'),'$1es'],
[new RegExp('(matr|vert|ind)ix|ex$','gi'),'$1ices'],
[new RegExp('([m|l])ouse$','gi'),'$1ice'],
[new RegExp('(quiz)$','gi'),'$1zes'],
[new RegExp('s$','gi'),'s'],
[new RegExp('$','gi'),'s']
];
/*
These rules translate from the plural form of a noun to its singular form.
You can override this list for all Strings or just one depending on if you
set the new values on prototype or on a given String instance.
*/
if(!String.prototype._singular_rules)String.prototype._singular_rules=[
[new RegExp('(m)en$','gi'),'$1an'],
[new RegExp('(pe)ople$','gi'),'$1rson'],
[new RegExp('(child)ren$','gi'),'$1'],
[new RegExp('([ti])a$','gi'), '$1um'],
[new RegExp('((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$',
'gi'),'$1$2sis'],
[new RegExp('(hive)s$','gi'), '$1'],
[new RegExp('(tive)s$','gi'), '$1'],
[new RegExp('(curve)s$','gi'), '$1'],
[new RegExp('([lr])ves$','gi'), '$1f'],
[new RegExp('([^fo])ves$','gi'), '$1fe'],
[new RegExp('([^aeiouy]|qu)ies$','gi'), '$1y'],
[new RegExp('(s)eries$','gi'), '$1eries'],
[new RegExp('(m)ovies$','gi'), '$1ovie'],
[new RegExp('(x|ch|ss|sh)es$','gi'), '$1'],
[new RegExp('([m|l])ice$','gi'), '$1ouse'],
[new RegExp('(bus)es$','gi'), '$1'],
[new RegExp('(o)es$','gi'), '$1'],
[new RegExp('(shoe)s$','gi'), '$1'],
[new RegExp('(cris|ax|test)es$','gi'), '$1is'],
[new RegExp('(octop|vir)i$','gi'), '$1us'],
[new RegExp('(alias|status)es$','gi'), '$1'],
[new RegExp('^(ox)en','gi'), '$1'],
[new RegExp('(vert|ind)ices$','gi'), '$1ex'],
[new RegExp('(matr)ices$','gi'), '$1ix'],
[new RegExp('(quiz)zes$','gi'), '$1'],
[new RegExp('s$','gi'), '']
];
/*
This function adds camelization support to every String object
Signature:
String.camelize(lowFirstLetter) == String
Arguments:
lowFirstLetter - boolean (optional) - default is to capitalize the first
letter of the results... passing true will lowercase it
Returns:
String - lower case underscored words will be returned in camel case
additionally '/' is translated to '::'
Examples:
"message_properties".camelize() == "MessageProperties"
"message_properties".camelize(true) == "messageProperties"
*/
if(!String.prototype.camelize)
String.prototype.camelize=function(lowFirstLetter)
{
var str=this.toLowerCase();
var str_path=str.split('/');
for(var i=0;i<str_path.length;i++)
{
var str_arr=str_path[i].split('_');
var initX=((lowFirstLetter&&i+1==str_path.length)?(1):(0));
for(var x=initX;x<str_arr.length;x++)
str_arr[x]=str_arr[x].charAt(0).toUpperCase()+str_arr[x].substring(1);
str_path[i]=str_arr.join('');
}
str=str_path.join('::');
return str;
};
/*
This function adds underscore support to every String object
Signature:
String.underscore() == String
Arguments:
N/A
Returns:
String - camel cased words are returned as lower cased and underscored
additionally '::' is translated to '/'
Examples:
"MessageProperties".camelize() == "message_properties"
"messageProperties".underscore() == "message_properties"
*/
if(!String.prototype.underscore)
String.prototype.underscore=function()
{
var str=this;
var str_path=str.split('::');
var upCase=new RegExp('([ABCDEFGHIJKLMNOPQRSTUVWXYZ])','g');
var fb=new RegExp('^_');
for(var i=0;i<str_path.length;i++)
str_path[i]=str_path[i].replace(upCase,'_$1').replace(fb,'');
str=str_path.join('/').toLowerCase();
return str;
};
/*
This function adds humanize support to every String object
Signature:
String.humanize(lowFirstLetter) == String
Arguments:
lowFirstLetter - boolean (optional) - default is to capitalize the first
letter of the results... passing true will lowercase it
Returns:
String - lower case underscored words will be returned in humanized form
Examples:
"message_properties".humanize() == "Message properties"
"message_properties".humanize(true) == "message properties"
*/
if(!String.prototype.humanize)
String.prototype.humanize=function(lowFirstLetter)
{
var str=this.toLowerCase();
str=str.replace(new RegExp('_id','g'),'');
str=str.replace(new RegExp('_','g'),' ');
if(!lowFirstLetter)str=str.capitalize();
return str;
};
/*
This function adds capitalization support to every String object
Signature:
String.capitalize() == String
Arguments:
N/A
Returns:
String - all characters will be lower case and the first will be upper
Examples:
"message_properties".capitalize() == "Message_properties"
"message properties".capitalize() == "Message properties"
*/
if(!String.prototype.capitalize)
String.prototype.capitalize=function()
{
var str=this.toLowerCase();
str=str.substring(0,1).toUpperCase()+str.substring(1);
return str;
};
/*
This function adds dasherization support to every String object
Signature:
String.dasherize() == String
Arguments:
N/A
Returns:
String - replaces all spaces or underbars with dashes
Examples:
"message_properties".capitalize() == "message-properties"
"Message Properties".capitalize() == "Message-Properties"
*/
if(!String.prototype.dasherize)
String.prototype.dasherize=function()
{
var str=this;
str=str.replace(new RegExp('[\ _]','g'),'-');
return str;
};
if(!String.prototype.underscorize)
String.prototype.underscorize=function()
{
var str=this;
str=str.replace(new RegExp('[\ _]','g'),'_');
return str;
};
/*
This function adds titleize support to every String object
Signature:
String.titleize() == String
Arguments:
N/A
Returns:
String - capitalizes words as you would for a book title
Examples:
"message_properties".titleize() == "Message Properties"
"message properties to keep".titleize() == "Message Properties to Keep"
*/
if(!String.prototype.titleize)
String.prototype.titleize=function()
{
var str=this.toLowerCase();
var t=new RegExp('^'+this._non_titlecased_words.join('$|^')+'$','i');
str=str.replace(new RegExp('_','g'),' ');
var str_arr=str.split(' ');
for(var x=0;x<str_arr.length;x++)
{
var d=str_arr[x].split('-');
for(var i=0;i<d.length;i++)if(!d[i].match(t))d[i]=d[i].capitalize();
str_arr[x]=d.join('-');
}
str=str_arr.join(' ');
str=str.substring(0,1).toUpperCase()+str.substring(1);
return str;
};
/*
This is a list of words that should not be capitalized for title case.
You can override this list for all Strings or just one depending on if you
set the new values on prototype or on a given String instance.
*/
if(!String.prototype._non_titlecased_words)
String.prototype._non_titlecased_words=[
'and','or','nor','a','an','the','so','but','to','of','at','by','from',
'into','on','onto','off','out','in','over','with','for'
];
/*
This function adds demodulize support to every String object
Signature:
String.demodulize() == String
Arguments:
N/A
Returns:
String - removes module names leaving only class names (Ruby style)
Examples:
"Message::Bus::Properties".demodulize() == "Properties"
*/
if(!String.prototype.demodulize)
String.prototype.demodulize=function()
{
var str=this;
var str_arr=str.split('::');
str=str_arr[str_arr.length-1];
return str;
};
/*
This function adds tableize support to every String object
Signature:
String.tableize() == String
Arguments:
N/A
Returns:
String - renders camel cased words into their underscored plural form
Examples:
"MessageBusProperty".tableize() == "message_bus_properties"
*/
if(!String.prototype.tableize)
String.prototype.tableize=function()
{
var str=this;
str=str.underscore().pluralize();
return str;
};
/*
This function adds classification support to every String object
Signature:
String.classify() == String
Arguments:
N/A
Returns:
String - underscored plural nouns become the camel cased singular form
Examples:
"message_bus_properties".classify() == "MessageBusProperty"
*/
if(!String.prototype.classify)
String.prototype.classify=function()
{
var str=this;
str=str.camelize().singularize();
return str;
};
/*
This function adds foreign key support to every String object
Signature:
String.foreign_key(dropIdUbar) == String
Arguments:
dropIdUbar - boolean (optional) - default is to seperate id with an
underbar at the end of the class name, you can pass true to skip it
Returns:
String - camel cased singular class names become underscored with id
Examples:
"MessageBusProperty".foreign_key() == "message_bus_property_id"
"MessageBusProperty".foreign_key(true) == "message_bus_propertyid"
*/
if(!String.prototype.foreign_key)
String.prototype.foreign_key=function(dropIdUbar)
{
var str=this;
str=str.demodulize().underscore()+((dropIdUbar)?(''):('_'))+'id';
return str;
};
/*
This function adds ordinalize support to every String object
Signature:
String.ordinalize() == String
Arguments:
N/A
Returns:
String - renders all found numbers their sequence like "22nd"
Examples:
"the 1 pitch".ordinalize() == "the 1st pitch"
*/
if(!String.prototype.ordinalize)
String.prototype.ordinalize=function()
{
var str=this;
var str_arr=str.split(' ');
for(var x=0;x<str_arr.length;x++)
{
var i=parseInt(str_arr[x]);
if(""+i!="NaN")
{
var ltd=str_arr[x].substring(str_arr[x].length-2);
var ld=str_arr[x].substring(str_arr[x].length-1);
var suf="th";
if(ltd!="11"&<d!="12"&<d!="13")
{
if(ld=="1")suf="st";
else if(ld=="2")suf="nd";
else if(ld=="3")suf="rd";
}
str_arr[x]+=suf;
}
}
str=str_arr.join(' ');
return str;
};
/*
* jQuery Simple Templates plugin 1.1.1
*
* http://andrew.hedges.name/tmpl/
* http://docs.jquery.com/Plugins/Tmpl
*
* Copyright (c) 2008 Andrew Hedges, [email protected]
*
* Usage: $.tmpl('<div class="#{classname}">#{content}</div>', { 'classname' : 'my-class', 'content' : 'My content.' });
* $.tmpl('<div class="#{1}">#{0}</div>', 'My content', 'my-class'); // placeholder order not important
*
* The changes for version 1.1 were inspired by the discussion at this thread:
* http://groups.google.com/group/jquery-ui/browse_thread/thread/45d0f5873dad0178/0f3c684499d89ff4
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*/
(function($) {
// regular expression for matching our placeholders; e.g., #{my-cLaSs_name77}
var regx = /#\{([^{}]*)}/g;
$.extend({
// public interface: $.tmpl
tmpl : function(tmpl) {
// default to doing no harm
tmpl = tmpl || '';
var vals = (2 === arguments.length && 'object' === typeof arguments[1] ? arguments[1] : Array.prototype.slice.call(arguments,1));
// function to making replacements
var repr = function (str, match) {
return typeof vals[match] === 'string' || typeof vals[match] === 'number' ? vals[match] : str;
};
return tmpl.replace(regx, repr);
}
});
})(jQuery);
(function(jQuery,window, defaultLanguage, undefined) {
jQuery.lang = {};
/* Ensure language code is in the format aa-AA. */
var normaliseLang = function(lang) {
lang = lang.replace(/_/, '-').toLowerCase();
if (lang.length > 3) {
lang = lang.substring(0, 3) + lang.substring(3).toUpperCase();
}
return lang;
};
var loc = normaliseLang(navigator.language /* Mozilla */
|| navigator.userLanguage /* IE */);
// var find = function(arr,terms) {
// var result = null;
// try {
// //ordened for
// for (var x = terms.length, i = 0; i < x; i++){
// terms[i]
// };
//
// for (var i=0; i < terms.length; i++) {
// if (i == 0)
// result = arr[terms[i]];
// else
// result = result[terms[i]];
//
// };
// } catch(err) {
// result = null;
// }
//
// return result;
// };
//todo move this to pre-process and to sqllite
var cache;
function cacherize(arr, parent) {
jQuery.each(arr, function(k,v) {
var k = (parent ? parent+".": '')+k;
cache[k] = v;
if (typeof v == "object" && !(v instanceof Array)) {
cacherize(v, k);
}
});
}
var getText = function(text) {
if (!cache) {
cache = {};
cacherize(jQuery.lang);
}
// var check = cache[text];
// if (check) {
// return check;
// }
//
// var sentence = text.split(".");
// cache[text] = find(jQuery.lang,sentence);
return cache[text];
};
jQuery.getText = function(text , nuller) {
var searchFirst = $.tmpl('#{0}.#{1}',loc, text);
var searchSecond = $.tmpl('#{0}.#{1}',defaultLanguage, text);
return getText(searchFirst) || getText(searchSecond) || (!nuller ? searchSecond : undefined) ;
};
})(jQuery,window , "pt-BR");
var ActiveModel = function(undefined) {
var model = {};
var modelInstance = {};
var activemodel = function(name, fieldsProject) {
var fields = [];
var fieldsIndex = {};
var obj = {
"model" : {},
"addProperty" : function(name, property) {
return this.model[name] = property;
},
"documentType" : name,
"addField" : function(field) {
if (typeof field === 'string') {
field = { "name" : field , "type" : "string"}
}
if (!field["name"] || !field["type"] || field["name"].trim() === '') {
throw new Error("invalid field name :"+field["name"]);
}
if (fieldsIndex[field["name"]] != undefined) {
fields[fieldsIndex[field["name"]]] = field;
} else {
fieldsIndex[field["name"]] = (fields.push(field) - 1);
}
},
"addFields" : function(fields) {
if (!(fields instanceof Array)) {
fields = [fields];
}
for (var i = fields.length - 1; i >= 0; i--){
this.addField(fields[i]);
}
},
"reflect" : function() {
return fields;
},
"instance" : function(submodel) {
if (submodel && this.subModel && this.subModel(submodel)) {
return this.subModel(submodel).instance();
}
var fieldsValues = {};
var instanceObj = {
"documentType" : name,
"reflect" : function() {
return obj.reflect();
},
"set" : function(field , value) {
var fieldPosition = fieldsIndex[field];
if (fieldPosition === undefined) {
throw new Error("Invalid field: "+field);
}
var fieldSettings = fields[fieldPosition];
if (fieldSettings["type"] == 'date' || fieldSettings["type"] == 'datetime' && !(value instanceof Date)) {
value = Date.parserString(value, "yyyy-MM-ddTHH:mm:ss");
}
if (typeof fieldSettings.setter != 'function') {
return fieldsValues[field] = value;
} else {
return fieldsValues[field] = fieldSettings.setter.call(this, value);
}
},
"get" : function(field) {
return fieldsValues[field];
},
"setAttributes" : function(attributes) {
for(var k in attributes) {
this.set(k, attributes[k]);
}
return this;
},
"values" : function(caller) {
var resp = {};
//TODO: MELHORAR !!!
for(var k in fieldsValues) {
//grr avoid nulls or undefined
if (fieldsValues[k] !== undefined || fieldsValues[k] !== null) {
var details = fields[fieldsIndex[k]];
if (fieldsValues[k] && fieldsValues[k].values && fieldsValues[k].documentType != caller && details.nested) {
resp[k+"_attributes"] = fieldsValues[k].values(this.documentType);
} else if(fieldsValues[k] instanceof Array && details.nested) {
resp[k+"_attributes"] = [];
for (var i = fieldsValues[k].length - 1; i >= 0; i--){
if (fieldsValues[k][i].values && fieldsValues[k][i].documentType != caller) {
resp[k+"_attributes"].push(fieldsValues[k][i].values(this.documentType));
} else if(!fieldsValues[k][i].documentType) {
resp[k+"_attributes"].push(fieldsValues[k][i]);
}
};
} else {
if (fieldsValues[k] && fieldsValues[k].documentType) {
//ignore
} else {
resp[k] = fieldsValues[k];
}
}
}
}
return resp;
}
};
jQuery.extend(true,instanceObj, this.model);
jQuery.extend(true,instanceObj, modelInstance);
for (var i = fields.length - 1; i >= 0; i--){
if (fields[i] && fields[i]["default"]) {
instanceObj.set(fields[i]["name"],fields[i]["default"]);
}
};
return instanceObj;
}
}
if (typeof fieldsProject === 'string') {
fieldsProject = [fieldsProject];
}
//pre-process fields
if (fieldsProject) {
try {
obj.addFields(fieldsProject);
} catch (e) {
throw e;
}
}
obj.addField({"name" : "id" , "type" : "number"});
obj.addField({"name" : "_destroy" , "type" : "boolean"});
jQuery.extend(true,obj, model);
return obj;
}
activemodel.addProperty = function(name, property) {
return model[name] = property;
}
activemodel.addInstanceProperty = function(name, property) {
return modelInstance[name] = property;
}
return activemodel;
}();
try {
module.exports = ActiveModel;
} catch(e){
}
(function(ActiveModel,undefined) {
ActiveModel.addProperty("addSubModel", function(subModel) {
if (!this.subModelsList) {
this.subModelsList = {};
}
this.subModelsList[subModel.documentType] = subModel;
return subModel;
});
ActiveModel.addProperty("subModel", function(name) {
if (!this.subModelsList) {
this.subModelsList = {};
}
return this.subModelsList[name];
});
ActiveModel.addProperty("sti",function(newName, fields) {
if (!(fields instanceof Array)) {
fields = [fields];
};
if (fields instanceof Array) {
fields = jQuery.merge(fields, this.reflect());
}
var obj = ActiveModel(newName, fields);
obj.addField({"name" : "type", "type" : "string" , "default" : newName });
//todo colocar em função a passagem do objeto
var self = this;
obj.stiParent = obj.addProperty("stiParent", function() {
return self.documentType;
});
this.addSubModel(obj);
return obj;
});
})(ActiveModel);