Unsorted list of features, howto's, suggar and evils of ruby (on rails)
1
2
3
4
5
6
7
8
9
10
11
12
13 BAD
14 -----------------------
15 model files do not contain the classes field information
16 instead this is stored in different 'migration' files
17 create_table "periods" do |t|
18 t.column "target_id", :integer
19 t.column "target_type", :string
20 t.column "start_at", :datetime
21 t.column "end_at", :datetime
22 t.column "wholeday", :boolean
23 t.column "wholeweek", :boolean
24 t.column "allweeks", :boolean
25 end
26 NO inbuild multi dimensional arrays
27 DANGER!!!!!
28 and is not && !!!!!!!!!!!!!!!!!!!!!!!!
29 return x==7 and y==8 => void value expression!!!
30 return x==7 && y==8 !!!
31 nr==0 (evaluates string.nil? !!!!!!! "0"==0 -> false!!!!)
32 nr.to_i==0 !!
33
34
35 + operator for string is really baad :
36 cannot convert nil into String !!!
37 puts "teacher "+ @lesson.teacher
38 "last saved : "+ DateTime.now.to_s
39 "nr"+rand(10).to_s
40
41 Language buggy: (see http://public.transcraft.co.uk/blog/index.html)
42 ActionController::RoutingError (Recognition failed for "/images/btnbg.gif"):
43
44 helpers are only for views!! (ApplicationController is what you need)
45
46 @links = Link.find_by_sql [
47 "SELECT * from links where link like '"+ @a +"%' order by id asc"]
48
49 s = "Hello, world"
50 /^Hello/.match( s ) >> true
51 /world$/.match( s ) >> true
52
53
54 <!--bad philosopy : evaluation inside html comments?
55 <%#= datetime_select 'lesson', 'end_at' %></p>-->
56
57 -------------------------------------
58 Good
59 ********************
60
61 class.byname:
62
63 alle= eval(type+".find(:all)")
64 Object.const_get("Array")
65
66 # default values
67 def initialize(definitions=[], word = nil)
68 @definitions = definitions
69 @word = word
70 end
71
72
73 rake db_schema_dump !!! instead of writing the migration files yourself
74
75 rake --help
76 rake migrate VERSION=n
77
78
79 Customer.find_all [ "company = ?", company ]
80 und wenn man eine LIKE '%xx%' Abfrage erstellen möchte:
81 Customer.find_all [ " company LIKE ? ", '%#{company}%' ]
82
83 string arrays:
84 x= %w(Montag Dienstag) is short for
85 y= ["Montag" ,"Dienstag"]
86
87 <%= sortable_element('listOrTableId' , :url => { :action => 'move' })
88
89 <%= observe_field(:search,
90 :frequency => 0.5,
91 :update => :results,
92 :url => { :action => :search },
93 :loading => "Element.show('indicator_gif_id')",
94 :complete => "Element.hide('indicator_gif_id')")
95 %>
96
97
98 /// HOW TOs (mixed with 'good')
99
100 global functions !
101 put them in application.rb (ApplicationController)
102
103
104
105
106 Regular expressions
107 #substitute patterns (m=LineBreaks u=Unicode i=IgnoreCase)
108 a=a.gsub(/<img.*?>/mui, "")
109
110 send_file or send http response data
111 send_data @person.picture, :filename => @person.filename, :type => "image/jpeg", :disposition => "inline"
112
113 require 'net/ftp'
114 ftp = Net::FTP.new('ftp.netlab.co.jp')
115 ftp.login files = ftp.chdir('pub/lang/ruby/contrib')
116 files = ftp.list('n*')
117 ftp.getbinaryfile('nif.rb-0.91.gz', 'nif.gz', 1024)
118 ftp.close
119
120 #reflection :
121 list.class.reflect_on_all_associations
122
123 >>>>>>>regex<<<<<<<<
124 // greedy !!!!
125 puts "a[bcb]d[bebb]rerberb]w[bsdaeb]ega".scan(/\[b(.*)b/).inspect
126 =>cb]d[bebb]rerberb]w[bsdae
127
128 // .*? not greedy ++
129 puts "a[bcb]d[bebb]rerberb]w[bsdaeb]egab".scan(/\[b(.*?)b/).inspect
130 => [["c"], ["e"], ["sdae"]]
131
132 #debug over ssh:
133 #ruby breakpointer [options] [server uri]
134 #ruby script/generate scaffold x // model + view!
135 #http://www.rubycentral.com/book/tut_modules.html modules
136
137
138 require 'net/http'
139 require 'uri'
140 img='http://www.macdesktops.com/?res=TRUE&category=35'
141 html=Net::HTTP.get URI.parse(img)
142
143 #switch cases
144 def search
145 @results = Search.find(params[:query])
146 case @results
147 when 0 then render :action=> "no_results"
148 when 1 then render :action=> "show"
149 when 2..10 then render :action=> "show_many"
150 end
151 end
152
153
154 module Action
155 VERY_BAD = 0
156 BAD = 1
157 def Action.sin(badness)
158 # ...
159 end
160 end
161
162 require "trig"
163 require "action"
164 ##########
165 MIXINS
166 module Debug
167 def whoAmI?
168 "
169 end
170 end
171 class Phonograph
172 include Debug
173
174 end
175 class EightTrack
176 include Debug
177
178 end
179 ph = Phonograph.new("West End Blues")
180 et = EightTrack.new("Surrealistic Pillow")
181
182
183
184 time=5.minutes + 30.seconds
185
186 5.times do |i|
187 File.open("temp.rb","w") { |f|
188 f.puts "module Temp\ndef Temp.var() #{i}; end\nend"
189 }
190 load "temp.rb"
191 puts Temp.var
192 end
193
194 print "Enter your name: "
195 name = gets
196
197
198 Argumentlisten variabler Länge
199 Was aber, wenn Sie eine variable Anzahl von Argumenten übergeben wollen oder mehrere Argumente mit einem einzigen Parameter auffangen wollen? Wenn Sie einen Stern vor den Namen des Parameters nach den ``normalen'' Parametern setzen, wird genau das gemacht.
200 def varargs(arg1, *rest)
201 "Got #{arg1} and #{rest.join(', ')}"
202 end
203
204
205 y = Trig.sin(Trig::PI/4)
206 wrongdoing = Action.sin(Action::VERY_BAD)
207
208
209
210
211
212
213
214 puts "It's not a number" if isanum.nil?
215
216
217 rescue ScriptError, StandardError
218 printf "ERR: %s\n", $! || 'exception raised'
219
220 eval(line).inspect
221
222
223 if a =~ /^[-+]?\d+$/;
224 puts "It's a number that may indicate positive or negative"
225 end
226
227 Does anyone know how to get an ID back, instead of a String?
228 @doctor = Doctor.find_by_name(params[:doctor][:name])
229 params[:parent][:doctor] = @doctor
230
231
232
233
234
235
236
237 IO.foreach("testfile") { |line| puts line }
238
239 arr = IO.readlines("testfile")
240
241
242 require 'socket'
243 client = TCPSocket.open('localhost', 'finger')
244 client.send("oracle\n", 0)
245 puts client.readlines
246 client.close
247
248
249 require 'net/http'
250 h = Net::HTTP.new('www.pragmaticprogrammer.com', 80)
251 resp, data = h.get('/index.html', nil)
252 if resp.message == "OK"
253 data.scan(/<img src="(.*?)"/) { |x| puts x }
254 end
255
256
257 f = File.open("testfile")
258 begin
259 f.each_line {|line| puts "Got #{line.dump}" }
260
261 raise ArgumentError, "Name too big", caller
262 rescue ArgumentError
263
264
265 else
266 puts "Congratulations-- no errors!"
267 ensure
268 f.close unless f.nil?
269 end
270
271
272 def promptAndGet(prompt)
273 print prompt
274 res = readline.chomp
275 throw :quitRequested if res == "!"
276 return res
277 end
278
279 catch :quitRequested do
280 name = promptAndGet("Name: ")
281 age = promptAndGet("Age: ")
282 sex = promptAndGet("Sex: ")
283
284
285 end
286
287
288 require 'breakpoint'
289 Thread.new do
290 loop do
291 begin
292 breakpoint
293 rescue Exception
294 end
295 end
296 end
297
298
299 <script type="text/javascript" language="javascript" charset="utf-8">
300 // <![CDATA[
301 Sortable.create('sortlist',{ghosting:false,constraint:false,hoverclass:'over',
302 //onUpdate:function(sortable){alert(Sortable.serialize(sortable))},
303 onChange:function(element){
304 var data= Sortable.serialize(element.parentNode);
305 var url="<%=url_for :controller=>'question',:action=>'move'%>";
306 new Ajax.Request(url,{parameters:data});
307 }
308 });
309 // ]]>
310 </script>
311