日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關咨詢
選擇下列產(chǎn)品馬上在線溝通
服務時間:8:30-17:00
你可能遇到了下面的問題
關閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
RubyDSL特點分析介紹

Ruby語言是一個應用靈活的解釋型腳本語言。對于一個編程人員來說,Ruby DSL是一個功能強大的工具。下面我們就來一起看看Ruby DSL特點介紹。#t#

站在用戶的角度思考問題,與客戶深入溝通,找到西安網(wǎng)站設計與西安網(wǎng)站推廣的解決方案,憑借多年的經(jīng)驗,讓設計與互聯(lián)網(wǎng)技術結(jié)合,創(chuàng)造個性化、用戶體驗好的作品,建站類型包括:成都網(wǎng)站建設、網(wǎng)站制作、企業(yè)官網(wǎng)、英文網(wǎng)站、手機端網(wǎng)站、網(wǎng)站推廣、國際域名空間、網(wǎng)絡空間、企業(yè)郵箱。業(yè)務覆蓋西安地區(qū)。

在rails里面,我們可以用很方便的聲明方式來定義model之間的關聯(lián)關系,Ruby DSL特點例如:

  1. class Topic < Active
    Record::Base
       
  2. has_many :posts   
  3. belongs_to :user   
  4. end   
  5. class Topic < Active
    Record::Base
     
  6. has_many :posts  
  7. belongs_to :user  
  8. end 

那has_many和belongs_to究竟是什么東西呢?其實他們是Topic類的class method,Ruby DSL特點的標準寫法是: 

  1. class Topic < ActiveRecord::Base   
  2. Topic.has_many(:posts)   
  3. Topic.belongs_to(:user)   
  4. end   
  5. class Topic < ActiveRecord::Base 
  6. Topic.has_many(:posts)  
  7. Topic.belongs_to(:user)  
  8. end 

那么has_many可以給我們帶來什么呢?類方法has_many在被執(zhí)行的時候,給Topic的對象實例添加了一系列方法:posts, posts<<, orders.push......等等。所以當我們在model里面聲明has_many,belongs_to等對象關系的時候,一系列相關的對象方法就被自動添加進來了。

既然明白了rails的小把戲,讓我們來自己試試看吧:

 
 
 
  1. module M   
  2. def self.included(c)   
  3. c.extend(G)   
  4. end   
  5. module G   
  6. def generate_method(*args)   
  7. args.each do |method_name|   
  8. define_method(method_name) 
    { puts method_name }   
  9. end   
  10. end   
  11. end   
  12. end   
  13. class C   
  14. include M   
  15. generate_method :method1, :method2   
  16. end   
  17. c = C.new   
  18. c.method1   
  19. c.method2   
  20. module M  
  21. def self.included(c)  
  22. c.extend(G)  
  23. end  
  24. module G  
  25. def generate_method(*args)  
  26. args.each do |method_name|  
  27. define_method(method_name) 
    { puts method_name }  
  28. end  
  29. end  
  30. end  
  31. end  
  32. class C  
  33. include M  
  34. generate_method :method1, :method2  
  35. end  
  36. c = C.new  
  37. c.method1  
  38. c.method2 

我們定義了一個聲明generate_method,可以接受多個symbol,來動態(tài)的創(chuàng)建同名的方法?,F(xiàn)在我們在類C里面使用這個聲明:generate_method :method1, :method2,當然我們需要include模塊M。為什么rails的model不需要include相關的模塊呢?當然是因為Topic的父類ActiveRecord::Base已經(jīng)include了模塊Associations了。

類C通過include模塊M,調(diào)用了模塊M的一個included回調(diào)接口,讓類C去extend模塊G,換句話來說就是,通過include模塊M,來給類C動態(tài)添加一個類方法generate_method。

這個generate_method被定義在模塊G當中,它接受一系列參數(shù),來動態(tài)創(chuàng)建相關的方法。于是我們就實現(xiàn)了這樣的DSL功能:

通過在類C里面聲明generate_method :method1, :method2,讓類C動態(tài)的添加了兩個實例方法method1,method2,是不是很有意思?

實際上rails的對象關聯(lián)聲明也是以同樣的方式實現(xiàn)的。

以上就是對Ruby DSL特點的分析介紹。


分享題目:RubyDSL特點分析介紹
當前地址:http://m.5511xx.com/article/djsescp.html