1
我在Ruby中做了一些元編程。我正在編寫一個庫來爲我定製一些方法,特別是在控制器中(自動執行一些find_by方法,我必須爲我的應用程序編寫這些方法)。Rails中的ActionController :: Base如何知道它的模型是什麼類?
目前我通過將特定控制器的模型名稱傳遞給我的元編程方法來生成這些方法。 是綁定到ActiveRecord模型的控制器中有沒有一種方法。
所以,這裏是一個壞榜樣
module AwesomeGem
module ClassMethods
def write_some_methods_for(model)
raise "Class #{model.class} does not inherit ActiveRecord::Base" unless model < ActiveRecord::Base
define_method "money_remaining" do |id=nil|
moolah = id ? model.find(id).money : model.find(params[:id]).money
render text: moolah
end
define_method "money_remaining_poller" do |id=nil|
obj = id ? model.find(id) : model.find(params[:id])
# composes some ajax
render js: moneyjs
moneyjs
end
end
end
end
因此,使用這種方法,我打算
GamblerController < ApplicationController
write_some_methods_for Gambler
end
同樣,我怎麼能讓它,所以我不必通過賭徒類到我的方法?是否有某種方法或屬性可以直接調用模型?例如。 self.send(:model)
一個複雜的解釋一個簡單的問題。
'self.class'不會給你你要找的東西嗎? – hwatkins 2013-03-18 14:54:38