ruby聲明式文法的實現例子_ruby專題

來源:互聯網
上載者:User

在ActiveRecord可以用很方便的聲明方式來定義model之間的關聯關係,例如:

複製代碼 代碼如下:

class Topic < ActiveRecord::Base
  has_many :posts
  belongs_to :user
end

has_many和belongs_to其實是Topic類的class method,標準寫法是:

複製代碼 代碼如下:

class Topic < ActiveRecord::Base
  Topic.has_many(:posts)
  Topic.belongs_to(:user)
end

那麼has_many可以給我們帶來什麼呢?類方法has_many在被執行的時候,給Topic的對象執行個體添加了一系列方法:posts, posts<<, orders.push......等等。所以當我們在model裡面聲明has_many,belongs_to等對象關係的時候,一系列相關的對象方法就被自動添加進來了。 讓我們來自己試試看吧:

複製代碼 代碼如下:

module M
  def self.included(c)
    c.extend(G)
  end
  module G
    def generate_method(*args)
      args.each do |method_name|
        define_method(method_name) { puts method_name }
      end
    end
end
end

class C
  include M
  generate_method :method1, :method2
end

c = C.new
c.method1
c.method2

我們定義了一個聲明generate_method,可以接受多個symbol,來動態建立同名的方法。現在我們在類C裡面使用這個聲明:generate_method :method1, :method2,當然我們需要include模組M。為什麼ActiveRecord的model不需要include相關的模組呢?當然是因為Topic的父類ActiveRecord::Base已經include了模組Associations了。

類C通過include模組M,調用了模組M的一個included回調介面,讓類C去extend模組G,換句話來說就是,通過include模組M,來給類C動態添加一個類方法generate_method。

這個generate_method被定義在模組G當中,它接受一系列參數,來動態建立相關的方法。於是我們就實現了這樣的DSL功能:

通過在類C裡面聲明generate_method :method1, :method2,讓類C動態添加了兩個執行個體方法method1,method2,是不是很有意思? 實際上rails的對象關聯聲明也是以同樣的方式實現的。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.