friendly_extensions 0.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/lib/numbers.rb ADDED
@@ -0,0 +1,180 @@
1
+ # -*- encoding : utf-8 -*-
2
+ # Numeric Extensions
3
+ module Numbers
4
+
5
+ Numeric.class_eval do
6
+
7
+ # Convert Number to numeric german style with precision
8
+ def to_euro(label = nil, options = {})
9
+ options[:precision] ||= 2
10
+
11
+ options[:precision] = 0 if options[:fix_int] == true && self.is_a?(Integer)
12
+
13
+ result = ActionController::Base.helpers.number_with_precision(self, :precision => options[:precision], :separator => ",", :delimiter => ".")
14
+
15
+ if options[:pre] == true && self > 0
16
+ result = "+#{result}"
17
+ elsif options[:pre] == true && self < 0
18
+ result = "-#{result}"
19
+ end
20
+
21
+
22
+ if !label.blank?
23
+ return [result, label].join("&nbsp;").html_safe
24
+ else
25
+ return result
26
+ end
27
+ end
28
+
29
+ # Convert Number to numeric german style without precision
30
+ def to_de(label=nil)
31
+ self.to_euro(label, :precision => 0)
32
+ end
33
+
34
+ def to_a
35
+ [self]
36
+ end
37
+
38
+ # Inflate number, y = duration of years, f = percentage
39
+ # tested
40
+ def infla(y=40,f=2)
41
+ self.to_f*(f.to_q**y)
42
+ end
43
+
44
+ # Deflate number, y = duration of years, f = percentage
45
+ # tested
46
+ def defla(y=40,f=2)
47
+ self.to_f*((1-(f.fdiv(100)))**y)
48
+ end
49
+
50
+ # Prüfen, welche Zahl aus dem Array am nächsten an der aktuellen Dran ist
51
+ # tested
52
+ def get_closest(nrs = [], lim = :ceil)
53
+
54
+ com = {}
55
+ com_a = []
56
+ nrs.each do |n|
57
+ case lim
58
+ when :ceil
59
+ x = ((self+0.001)-n).abs
60
+ when :floor
61
+ x = ((self-0.001)-n).abs
62
+ else
63
+ raise ArgumentError, "lim must be :ceil or :floor"
64
+ end
65
+ com.merge!(x => n)
66
+ com_a << x
67
+ end
68
+ return com[com_a.min]
69
+ end
70
+
71
+ # tested
72
+ def min(ref)
73
+ [self.to_f, ref.to_f].min
74
+ end
75
+
76
+ # tested
77
+ def max(ref)
78
+ [self.to_f, ref.to_f].max
79
+ end
80
+
81
+ # Wert zwischen den Grenzen, ansonsten ober-oder unterkante
82
+ # tested
83
+ def min_max(m1, m2)
84
+ self.min(m2).max(m1)
85
+ end
86
+
87
+ # => tested
88
+ def fdiv(d)
89
+ self.to_f/d
90
+ end
91
+
92
+
93
+ # Finanzmathematik, Zinsen und so
94
+ def to_q
95
+ 1+(self/100.0)
96
+ end
97
+
98
+ def alpha_sum(u,o)
99
+ (self**u - self**(o+1)).fdiv(1-self)
100
+ end
101
+
102
+
103
+ def to_time(options = {})
104
+ values = [ self.to_i/3600, self.to_i / 60 % 60, self.to_i%60 ].map{ |t| t.to_s.rjust(2, '0') }
105
+ if options[:split] == true
106
+ return {:h => values[0].round, :m => values[1].round, :s => values[2].round}
107
+ elsif options[:discard_hour] == true && values[0] == "00"
108
+ return values[1,2].join(':')
109
+ else
110
+ return values.join(':')
111
+ end
112
+ end
113
+
114
+ def deg2rad
115
+ self * Math::PI / 180
116
+ end
117
+
118
+
119
+ end
120
+
121
+ Integer.class_eval do
122
+
123
+
124
+
125
+ def odd?
126
+ self%2 == 0
127
+ end
128
+
129
+ def even?
130
+ !self.odd?
131
+ end
132
+
133
+
134
+ # Cals
135
+ def to_years(options = {:s_years => "Jahre", :s_months => "Monate", :s_sep => "und"})
136
+ x = [self/12, self%12]
137
+ "#{x[0]} #{options[:s_years]} #{options[:s_sep]} #{x[1]} #{options[:s_months]}"
138
+ end
139
+
140
+ def days_to_months(options = {:s_days => "Tage", :s_months => "Monate", :s_sep => "und"})
141
+ x = [self/30, self%30]
142
+ "#{x[0]} #{options[:s_months]} #{options[:s_sep]} #{x[1]} #{options[:s_days]}"
143
+ end
144
+
145
+
146
+ # Split number in smallest prime factors
147
+ def prime_factors(options = {})
148
+ options[:nrs] ||= Math.sqrt(self).floor.prime_numbers
149
+ options[:nrs].each_with_index do |n,i|
150
+ if self%n == 0
151
+ return [n, (self/n).prime_factors(:nrs => options[:nrs])].flatten.except(1)
152
+ elsif i == options[:nrs].size-1
153
+ return [self]
154
+ end
155
+ end
156
+ end
157
+
158
+ # Create list with prime numbers up to 'self'
159
+ def prime_numbers
160
+ s = (0..self).to_a
161
+ s[0] = s[1] = nil
162
+ s.each do |p|
163
+ next unless p
164
+ break if p * p > self
165
+ (p*p).step(self, p) { |m| s[m] = nil }
166
+ end
167
+ s.compact
168
+ end
169
+
170
+ end
171
+
172
+
173
+ Fixnum.class_eval do
174
+ def nan?
175
+ self.to_f.nan?
176
+ end
177
+ end
178
+
179
+ end
180
+
@@ -0,0 +1,66 @@
1
+ # -*- encoding : utf-8 -*-
2
+ module SmartCurrency
3
+
4
+ def self.included(base)
5
+ base.extend ClassMethods
6
+ end
7
+
8
+ module ClassMethods
9
+ def smart_currency
10
+ unless smart_currency?
11
+ include InstanceMethods
12
+ auto_attributes = []
13
+ self.skip_time_zone_conversion_for_attributes = []
14
+ attributes = self.columns.select {|c| (c.type == :integer || c.type == :decimal) && !c.name.match("id") }
15
+
16
+ attributes.each do |a|
17
+ define_method("#{a.name}=") do |val|
18
+ self[a.name.to_sym] = currency_to_db(val)
19
+ end
20
+ end
21
+
22
+ end
23
+ end
24
+
25
+ def smart_currency?
26
+ self.included_modules.include?(InstanceMethods)
27
+ end
28
+
29
+ end
30
+
31
+ module InstanceMethods # any method placed here will apply to instaces, like @hickwall
32
+
33
+ def currency_to_db(string)
34
+ if string.is_a?(String)
35
+ return (string.gsub(/\./, '').gsub(/,/, '.')).to_f
36
+ elsif string.nil?
37
+ return 0
38
+ else
39
+ return string
40
+ end
41
+ end
42
+
43
+ def currency_to_view(decimal)
44
+ if !decimal.nil?
45
+ str = decimal.to_s.split(".")
46
+ str[1] = "0" unless str[1]
47
+ if str[1].size == 1
48
+ str[1] += "0"
49
+ end
50
+ if str[0].size == 5 || str[0].size == 6
51
+ str[0].gsub!(/\B([0-9]{3})\b/,'.\1')
52
+ elsif str[0].size > 7
53
+ str[0].gsub!(/([0-9]{3})\b/,'.\1').gsub!(/([0-9]{3}\.)/, '.\1')
54
+ else
55
+ str[0].gsub!(/\B([0-9]{3})/,'.\1')
56
+ end
57
+ str[1].size > 2 ? str[1] = str[1][0..1] : nil
58
+ return (str[0] + "," + str[1]).to_s
59
+ else
60
+ return "keine Angabe"
61
+ end
62
+ end
63
+
64
+ end
65
+
66
+ end
@@ -0,0 +1,301 @@
1
+ # -*- encoding : utf-8 -*-
2
+ module StringAndMore
3
+ String.class_eval do
4
+
5
+ require "chars_2_remove"
6
+ require 'digest/sha1'
7
+
8
+ # List with internation chars and their ASCII replacement
9
+ CHARS_TO_REMOVE = Chars2Remove::CHARS
10
+
11
+ # Characters for creating randdom char combinations
12
+ String::RANDOM_CHARS = {:upcase => "ABCDEFGHIJKLMNOPQRSTUVWXYZ", :downcase => "abcdefghijklmnopqrstuvwxyz", :numbers => "1234567890"}
13
+
14
+ # String charsets used for numeric encryption
15
+ STRING_CHARSETS = {
16
+ "a" => String::RANDOM_CHARS[:upcase],
17
+ "A" => String::RANDOM_CHARS[:downcase],
18
+ "1" => String::RANDOM_CHARS[:numbers],
19
+ "ä" => "äöüÄÖÜß",
20
+ "!" => '!\"§$%&/()=?+*#@,.-;:_\' ¡“”¶¢[]|{}≠¿^°≤≥∞…–‘’<>'
21
+ }
22
+
23
+ # Array with all strings which can be encrypted
24
+ STRING_BASE = STRING_CHARSETS.values.join("")
25
+
26
+ # Encode String Base with custom secrect key
27
+ #SHUFFLED_STRING_BASE = STRING_CHARSETS.values.sort_by {|y| STRING_CHARSETS.values.map.with_index {|x,i| STRING_BASE.split("").reverse[i].hex * x.hex }[STRING_CHARSETS.values.index(y)] }
28
+
29
+
30
+ # Returns random String, for Passwords, Captachs etc..
31
+ # could create :upcase, :downcase, :numbers or :all
32
+ def self.random_string(l=12, mode = :all)
33
+ case mode
34
+ when :all
35
+ base = String::RANDOM_CHARS.values.join("").split("")
36
+ else
37
+ base = String::RANDOM_CHARS[mode].split("")
38
+ end
39
+
40
+ str = ""
41
+
42
+ l.times do
43
+ str << base.shuffle[rand(base.size-1)]
44
+ end
45
+ return str
46
+ end
47
+
48
+ def self.email_message_id(mail_domain)
49
+ "<#{Digest::SHA2.hexdigest(Time.now.to_i.to_s)}@#{mail_domain}>"
50
+ end
51
+
52
+
53
+ # Extract boolean status from string
54
+ def to_boolean
55
+ if ['true', 'True', 'TRUE', '1'].include?(self)
56
+ return true
57
+ else
58
+ return false
59
+ end
60
+ end
61
+
62
+ # Create string with german date format to Date
63
+ def to_date
64
+ # Try German
65
+ matched_date = self.match(/((0|1|2|3)[0-9]{1})\.(0[0-9]{1}|10|11|12)\.[0-9]{4}/)
66
+
67
+ if !matched_date.nil?
68
+ return Date.new(matched_date.to_s.split(".")[2].to_i, matched_date.to_s.split(".")[1].to_i, matched_date.to_s.split(".")[0].to_i)
69
+ elsif matched_date.nil?
70
+ matched_date = self.match(/[0-9]{4}-(0[0-9]{1}|10|11|12)-((0|1|2|3)[0-9]{1})/)
71
+ if !matched_date.nil?
72
+ return Date.new(matched_date.to_s.split("-")[0].to_i, matched_date.to_s.split("-")[1].to_i, matched_date.to_s.split("-")[2].to_i)
73
+ end
74
+ end
75
+
76
+ raise ArgumentError, "String has no date like DD.MM.YYYY or YYYY-DD-MM" if matched_date.nil?
77
+ end
78
+
79
+
80
+ def to_number(type = :float)
81
+ extract = self.match(/[0-9\.,]{1,}/).to_s
82
+ final = extract.gsub(".", "").gsub(",", ".")
83
+ case type
84
+ when :float
85
+ return final.to_f
86
+ else
87
+ return final.to_i
88
+ end
89
+ end
90
+
91
+ def to_label(options = {:show_tooltip => false})
92
+ if FriendsLabel.table_exists?
93
+ l = FriendsLabel::LABELS[self]
94
+ if l.nil?
95
+ FriendsLabel.create(:label => self, :attribute_name => self)
96
+ return self
97
+ else
98
+ unless options[:show_tooltip] == true
99
+ return l[:label]
100
+ else
101
+ return l[:tooltip]
102
+ end
103
+ end
104
+ else
105
+ return self
106
+ end
107
+ end
108
+
109
+ def shuffle
110
+ self.split("").sort_by {rand}.join.humanize
111
+ end
112
+
113
+
114
+ def to_foldername(sep = "_")
115
+ # deutsch umlaute ersetzen
116
+ parameterized_string = self.strip.gsub(/\ {2,}/ , " ").de_2_int
117
+
118
+ # Turn unwanted chars into the separator
119
+ parameterized_string.gsub!(/[^a-zA-Z0-9ÄÖÜöäüß\-_]+/, sep)
120
+ unless sep.nil? || sep.empty?
121
+ re_sep = Regexp.escape(sep)
122
+ # No more than one of the separator in a row.
123
+ parameterized_string.gsub!(/#{re_sep}{2,}/, sep)
124
+ # Remove leading/trailing separator.
125
+ parameterized_string.gsub!(/^#{re_sep}|#{re_sep}$/, '')
126
+ end
127
+ return parameterized_string
128
+ end
129
+
130
+
131
+
132
+ def de_2_int
133
+ str = self
134
+ CHARS_TO_REMOVE.each do |de, int|
135
+ str = str.gsub(de, int)
136
+ end
137
+ str = str.gsub(" ", " ")
138
+ return str
139
+ end
140
+
141
+ def limit(l=20)
142
+ if self.size > l
143
+ s = self.size
144
+ s2 = (((self.size-1)/2).round)
145
+ first = self.slice(0..s2)
146
+ last = self.slice(s2+1..-1)
147
+
148
+ l1 = (l/2).round
149
+
150
+ "#{first.first(l1)}...#{last.last(l1)}"
151
+ else
152
+ return self
153
+ end
154
+ end
155
+
156
+
157
+
158
+
159
+ def to_datetime
160
+ date = self.split(" ").first
161
+ time = self.split(" ").last.split(":")
162
+ DateTime.new(date.split(".")[2].to_i, date.split(".")[1].to_i, date.split(".")[0].to_i, time.first.to_i, time.last.to_i)
163
+ end
164
+
165
+
166
+ def clear_html(options = {})
167
+ ActionView::Base.full_sanitizer.sanitize(self, :tags => options[:tags] )
168
+ end
169
+
170
+ def replace_html(from, to)
171
+ new_text = self
172
+ new_text = new_text.gsub("<#{from}>", "<#{to}>")
173
+ new_text = new_text.gsub("</#{from}>", "</#{to}>")
174
+ return new_text
175
+ end
176
+
177
+ def to_model
178
+ self.singularize.camelize.constantize
179
+ end
180
+
181
+ def to_a
182
+ return [self]
183
+ end
184
+
185
+ #== HTML Styling
186
+ # as the function names say
187
+
188
+ def bold
189
+ "<b>#{self}</b>".html_safe
190
+ end
191
+
192
+ def ital
193
+ "<i>#{self}</i>".html_safe
194
+ end
195
+
196
+ def span
197
+ "<span>#{self}</span>".html_safe
198
+ end
199
+
200
+ def uline
201
+ "<u>#{self}</u>".html_safe
202
+ end
203
+
204
+ def nbsp
205
+ self.gsub(" ", "&nbsp;").html_safe
206
+ end
207
+
208
+ def replace_entities(mode = :html, options = {})
209
+ str = self
210
+ Chars2Remove::ENTITIES.each do |orig, rep|
211
+ str = str.gsub(orig, rep[mode])
212
+ end
213
+ return str.html_safe
214
+ end
215
+
216
+ def add_brs
217
+ return self.gsub("\n", "<br />")
218
+ end
219
+
220
+ #== colorization in console
221
+
222
+ def colorize(color_code)
223
+ "\e[#{color_code};40m#{self}\e[0m"
224
+ end
225
+
226
+ def red
227
+ colorize(31)
228
+ end
229
+
230
+ def green
231
+ colorize(32)
232
+ end
233
+
234
+ def yellow
235
+ colorize(33)
236
+ end
237
+
238
+ def pink
239
+ colorize(35)
240
+ end
241
+
242
+
243
+ #== Numerische encription
244
+ # cool thing for simple encrypt and decrypt strings
245
+
246
+ def numberize(options = {})
247
+ # Basisarray das alle zeichen enthält die verschlüsselt werden können
248
+ string_array = STRING_BASE.split("")
249
+
250
+ if options[:token]
251
+ string_array = string_array.sort_by {|x| x.hash*options[:token].inspect.bytes.join("").to_i}
252
+ end
253
+
254
+ # Nur Zahlen und buchstaben für die verschlüsselung/mix nehmen wg. URLs
255
+ string_array_filtered = string_array.select {|s| !s.match(/[a-zA-Z0-9\-_]/).nil? }
256
+ splitted = self.split("")
257
+
258
+ numbered_string = ""
259
+
260
+ splitted.each do |s|
261
+ position = string_array.index(s)
262
+ if !position.nil?
263
+ numbered_string << (position.to_s.rjust(2, "0")+string_array_filtered[rand(string_array_filtered.size-1)])
264
+ end
265
+ end
266
+
267
+ return options[:base_64] == true ? Base64.encode64(numbered_string) : numbered_string
268
+ end
269
+
270
+ def denumberize(options = {})
271
+ string_array = STRING_BASE.split("")
272
+
273
+ if options[:token]
274
+ string_array = string_array.sort_by {|x| x.hash*options[:token].inspect.bytes.join("").to_i}
275
+ end
276
+
277
+ real_string = ""
278
+ (options[:base_64] == true ? Base64.decode64(self) : self ).scan(/[0-9]{2}.{1}/).each do |s|
279
+ real_string << string_array[s.first(2).to_i]
280
+ end
281
+ return real_string
282
+ end
283
+
284
+
285
+
286
+
287
+
288
+ end
289
+
290
+
291
+ Symbol.class_eval do
292
+
293
+ def to_label(options = {})
294
+ self.to_s.to_label(options)
295
+ end
296
+
297
+ def gsub(old, repl)
298
+ self.to_s.gsub(old, repl)
299
+ end
300
+ end
301
+ end