Rails代码片段

1Debugging Views in Development

ruby 代码
  1. <!---->  
  2.   
  3. <!---->  
  4.     "debug" style="margin: 40px 5px 5px 5px;">   
  5.         "#" onclick="Element.toggle('debug_info');return false" style="text-decoration: none; color: #ccc;">Show Debug Info ➲   
  6.         "debug_info" style="display : none;">   
  7.             <!---->   
  8.             <!---->   
  9.         
  10. 还有一个相关的插件:TextmateFootnotesPlugin
    ruby 代码
    1. class << Dispatcher   
    2.   def dispatch(cgi = CGI.new,   
    3.                session_options = ActionController::CgiRequest::DEFAULT_SESSION_OPTIONS)   
    4.     begin  
    5.       request, response =   
    6.         ActionController::CgiRequest.new(cgi, session_options),   
    7.         ActionController::CgiResponse.new(cgi)   
    8.       prepare_application   
    9.       ActionController::Routing::Routes.recognize!(request).process(request, response).out   
    10.     rescue Object => exception   
    11.       begin  
    12.         ActionController::Base.process_with_exception(request, response, exception).out   
    13.       rescue  
    14.         # The rescue action above failed also, probably for the same reason   
    15.         # the original action failed.  Do something simple which is unlikely   
    16.         # to fail.  You might want to redirect to a static page instead of this.   
    17.         e = exception   
    18.         cgi.header("type" => "text/html")   
    19.         cgi.out('cookie' => ''do  
    20.           <<-RESPONSE   
    21.            
    22.              
    23.              
    24.             

      Application Error

        
    25.             
       
      #{e.class}: #{e.message}  
    26.   
    27.             
       
      #{e.backtrace.join("\n")}              
    28.           RESPONSE   
    29.         end  
    30.       end  
    31.     ensure  
    32.       reset_application   
    33.     end  
    34.   end  
    35. end  

  3 SQL Logging in Rails

ruby 代码
  1. SQL_LOGGING = true  
  2. SQL_LOG_MAX_LINES = 5000   
  3. SQL_LOG_FILE = File::join(RAILS_ROOT, '/log/sql_log.txt')   
  4. # $sql_log is a global var that will hold the results of the last sql statement executed   
  5. $sql_log = ""  
  6. # permit logging if we are in development environment   
  7. if RAILS_ENV_DEV || RAILS_ENV_TEST   
  8.   connection = ActiveRecord::Base.connection   
  9.   class << connection   
  10.     alias :original_exec :execute  
  11.     def execute(sql, *name)   
  12.       # try to log sql command but ignore any errors that occur in this block   
  13.       # we log before executing, in case the execution raises an error   
  14.       begin  
  15.         if SQL_LOGGING   
  16.           if File::exists?(SQL_LOG_FILE) : lines = IO::readlines(SQL_LOG_FILE)   
  17.           else lines = Array.new(); end  
  18.           log = File.new(SQL_LOG_FILE, "w+")   
  19.           # keep the log to specified max lines   
  20.           if lines.length > SQL_LOG_MAX_LINES   
  21.             lines.slice!(0..(lines.length-SQL_LOG_MAX_LINES))   
  22.           end  
  23.           lines << Time.now.strftime("%x %I:%M:%S %p")+": "+sql+"n"  
  24.           log.write(lines)   
  25.           log.close   
  26.           $sql_log = sql   
  27.         end # if   
  28.       rescue Exception => e   
  29.         ;   
  30.       end  
  31.       # execute original statement   
  32.       original_exec(sql, *name)   
  33.     end # def execute   
  34.   end # class <<   
  35. end # if RAILS_ENV_DEV   
  36.   
  37. Here's the constant setting code (put in application.rb or something it requires before the code above gets run):   
  38.   
  39.   
  40. class CoreERR_RailsEnvironment < StandardError; end  
  41. #RAILS specific constants   
  42.   #setup global constants for manipulating states   
  43.   RAILS_ENV_VAR = "RAILS_ENV"  
  44.   #set ENV to development if explicit or not present   
  45.   RAILS_ENV_DEV = (ENV[RAILS_ENV_VAR]=="development" || (not ENV[RAILS_ENV_VAR]))   
  46.   RAILS_ENV_LIVETEST = ENV[RAILS_ENV_VAR]=="livetest"  
  47.   RAILS_ENV_TEST = ENV[RAILS_ENV_VAR]=="test"  
  48.   if (RAILS_ENV_DEV) or (RAILS_ENV_TEST)   
  49.     RAILS_ENV_PRODUCTION = false  
  50.   else  
  51.     RAILS_ENV_PRODUCTION = true  
  52.   end  
  53.   # check positively: if production environment is implied because test and development are not found   
  54.   # but production doesn't show up positively, raise exception   
  55.   if RAILS_ENV_PRODUCTION and (RAILS_ENV_PRODUCTION != (ENV[RAILS_ENV_VAR]=="production"))   
  56.     raise CoreERR_RailsEnvironment, "Production environment implied but not detected: "+ENV[RAILS_ENV_VAR]   
  57.   end  
  58.   RAILS_DB_SU = ENV[RAILS_ENV_VAR]+'_su'   
  59.   RAILS_ENV_DEV.freeze   
  60.   RAILS_ENV_TEST.freeze   
  61.   RAILS_ENV_PRODUCTION.freeze   

 

3 Digest MD5 & SHA1

Digest 支援 MD5 和 SHA1 兩種編碼, 你若有儲存密碼的需求就要用到, 一般是用 SHA1.

  • MD5 計算
    
    require 'digest/md5'
    
    puts Digest::MD5.hexdigest("Hello World!")
    
  • 計算檔案的 MD5, 可以確保檔案未曾被修改
    
    require 'digest/md5'
    
    #method 1
    puts Digest::MD5.hexdigest(File.read("o.rb"))
    
    #method 2
    class Digest::MD5
      def self.open(path)
        o = new
        File.open(path) { |f|
          buf = "" 
          while f.read(256, buf)
            o << buf
          end
        }
        o
      end
    end
    puts Digest::MD5.open("o.rb").hexdigest
    
  • SHA1 計算
    
    require 'digest/sha1'
    
    puts Digest::SHA1.hexdigest("Hello World!")
    

你可能感兴趣的:(sql,cgi,Ruby,Rails,ActiveRecord)