# THIS FILE CONTAINS INTERESTING SNIPPETS OF RUBY/RAILS # in order to accelerate learning and find forgotten things # # Key shortcuts! # ctrl+shift+v controller/view! # ctrl+k find next word # ctrl+m maximize editor # # # # BAD ----------------------- model files do not contain the classes field information instead this is stored in different 'migration' files create_table "periods" do |t| t.column "target_id", :integer t.column "target_type", :string t.column "start_at", :datetime t.column "end_at", :datetime t.column "wholeday", :boolean t.column "wholeweek", :boolean t.column "allweeks", :boolean end NO inbuild multi dimensional arrays DANGER!!!!! and is not && !!!!!!!!!!!!!!!!!!!!!!!! return x==7 and y==8 => void value expression!!! return x==7 && y==8 !!! nr==0 (evaluates string.nil? !!!!!!! "0"==0 -> false!!!!) nr.to_i==0 !! #ANNOYANCES: + operator for string is really baad : cannot convert nil into String !!! puts "teacher "+ @lesson.teacher "last saved : "+ DateTime.now.to_s #to_s !!! neccessary!!!!!!! (and ugly) "nr"+rand(10).to_s#!!! Language buggy: (see http://public.transcraft.co.uk/blog/index.html) ActionController::RoutingError (Recognition failed for "/images/btnbg.gif"): helpers are only for views!! (ApplicationController is what you need) @links = Link.find_by_sql [ "SELECT * from links where link like '"+ @a +"%' order by id asc"] #endwith startwith s = "Hello, world" /^Hello/.match( s ) >> true /world$/.match( s ) >> true <!--bad philosopy : evaluation inside html comments? <%#= datetime_select 'lesson', 'end_at' %></p>--> ------------------------------------- Good ******************** class.byname: alle= eval(type+".find(:all)") Object.const_get("Array") # default values def initialize(definitions=[], word = nil) @definitions = definitions @word = word end rake db_schema_dump !!! instead of writing the migration files yourself rake --help rake migrate VERSION=n #runs from 0 to n !!!!!!!!!!! Customer.find_all [ "company = ?", company ] und wenn man eine LIKE '%xx%' Abfrage erstellen möchte: Customer.find_all [ " company LIKE ? ", '%#{company}%' ] string arrays: x= %w(Montag Dienstag) is short for y= ["Montag" ,"Dienstag"] <%= sortable_element('listOrTableId' , :url => { :action => 'move' }) #, :update => 'test-id',:tag => 'tr', :complete => visual_effect(:highlight, q.id))%> <%= observe_field(:search, :frequency => 0.5, :update => :results, :url => { :action => :search }, :loading => "Element.show('indicator_gif_id')", :complete => "Element.hide('indicator_gif_id')") %> /// HOW TOs (mixed with 'good') global functions ! put them in application.rb (ApplicationController) Regular expressions #substitute patterns (m=LineBreaks u=Unicode i=IgnoreCase) a=a.gsub(/<img.*?>/mui, "") # yeah right nice naming, suckers! send_file or send http response data send_data @person.picture, :filename => @person.filename, :type => "image/jpeg", :disposition => "inline" require 'net/ftp' ftp = Net::FTP.new('ftp.netlab.co.jp') ftp.login files = ftp.chdir('pub/lang/ruby/contrib') files = ftp.list('n*') ftp.getbinaryfile('nif.rb-0.91.gz', 'nif.gz', 1024) ftp.close #reflection : list.class.reflect_on_all_associations >>>>>>>regex<<<<<<<< // greedy !!!! puts "a[bcb]d[bebb]rerberb]w[bsdaeb]ega".scan(/\[b(.*)b/).inspect =>cb]d[bebb]rerberb]w[bsdae // .*? not greedy ++ puts "a[bcb]d[bebb]rerberb]w[bsdaeb]egab".scan(/\[b(.*?)b/).inspect => [["c"], ["e"], ["sdae"]] #debug over ssh: #ruby breakpointer [options] [server uri] #ruby script/generate scaffold x // model + view! #http://www.rubycentral.com/book/tut_modules.html modules require 'net/http' require 'uri' img='http://www.macdesktops.com/?res=TRUE&category=35' html=Net::HTTP.get URI.parse(img) #switch cases def search @results = Search.find(params[:query]) case @results when 0 then render :action=> "no_results" when 1 then render :action=> "show" when 2..10 then render :action=> "show_many" end end module Action VERY_BAD = 0 BAD = 1 def Action.sin(badness) # ... end end require "trig" require "action" ########## MIXINS module Debug def whoAmI? "#{self.type.name} (\##{self.id}): #{self.to_s}" end end class Phonograph include Debug # ... end class EightTrack include Debug # ... end ph = Phonograph.new("West End Blues") et = EightTrack.new("Surrealistic Pillow") #ph.whoAmI? » "Phonograph (#537766170): West End Blues" #et.whoAmI? » "EightTrack (#537765860): Surrealistic Pillow" ##########################33 time=5.minutes + 30.seconds ## cool !!!!!! 5.times do |i| File.open("temp.rb","w") { |f| f.puts "module Temp\ndef Temp.var() #{i}; end\nend" } load "temp.rb" puts Temp.var end ################ print "Enter your name: " name = gets ################# Argumentlisten variabler Länge 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. def varargs(arg1, *rest) "Got #{arg1} and #{rest.join(', ')}" end y = Trig.sin(Trig::PI/4) wrongdoing = Action.sin(Action::VERY_BAD) # setup: # rails <appname> # ruby script\generate scaffold survey #!! does the following too: # ruby script\generate controller survey # ruby script\generate model survey #backward if #def isanum=true puts "It's not a number" if isanum.nil? #$! variable!! rescue ScriptError, StandardError printf "ERR: %s\n", $! || 'exception raised' #eval eval(line).inspect #regexp matching & no brackets if a =~ /^[-+]?\d+$/; puts "It's a number that may indicate positive or negative" end Does anyone know how to get an ID back, instead of a String? @doctor = Doctor.find_by_name(params[:doctor][:name]) params[:parent][:doctor] = @doctor #what is that? yml intralanguage :( # database: verwurzelt_de_development # <<: *login #Simplemost file IO: IO.foreach("testfile") { |line| puts line } arr = IO.readlines("testfile") #Simple socket require 'socket' client = TCPSocket.open('localhost', 'finger') client.send("oracle\n", 0) # 0 means standard packet puts client.readlines client.close #HTTP require 'net/http' h = Net::HTTP.new('www.pragmaticprogrammer.com', 80) resp, data = h.get('/index.html', nil) if resp.message == "OK" data.scan(/<img src="(.*?)"/) { |x| puts x } end #get images! #error handling: f = File.open("testfile") begin f.each_line {|line| puts "Got #{line.dump}" } # .. process raise ArgumentError, "Name too big", caller rescue ArgumentError #rescue # .. handle error else puts "Congratulations-- no errors!" ensure f.close unless f.nil? end ############# # SICK : two mechanisms!!! def promptAndGet(prompt) print prompt res = readline.chomp throw :quitRequested if res == "!" return res end catch :quitRequested do name = promptAndGet("Name: ") age = promptAndGet("Age: ") sex = promptAndGet("Sex: ") # .. # process information end ############# require 'breakpoint' Thread.new do loop do begin breakpoint rescue Exception end end end <script type="text/javascript" language="javascript" charset="utf-8"> // <![CDATA[ Sortable.create('sortlist',{ghosting:false,constraint:false,hoverclass:'over', //onUpdate:function(sortable){alert(Sortable.serialize(sortable))}, onChange:function(element){ var data= Sortable.serialize(element.parentNode); var url="<%=url_for :controller=>'question',:action=>'move'%>"; new Ajax.Request(url,{parameters:data}); } }); // ]]> </script>
You need to create an account or log in to post comments to this site.
This code is mostly useless to solve namable problems, it's a personnal cheatsheet, it's not very nice code many times.
And finally this is not a forum to express your feelings about Ruby or Rails or War in Iraq. This is a snippets site. There are forums for expressing your feelings wich we may understand but don't want to encounter here when searching for code to work with.
Thanks.