module ProductsHelper
attr_reader :products, :product
end
這樣做的結果是什麼?我在Rails指南中看到了這一點,只是不明白。在rails的輔助模塊中使用attr_reader是什麼意思?
module ProductsHelper
attr_reader :products, :product
end
這樣做的結果是什麼?我在Rails指南中看到了這一點,只是不明白。在rails的輔助模塊中使用attr_reader是什麼意思?
它將允許通過在視圖中調用products
和product
來從@products
和@product
實例變量中讀取值。您仍然需要將它們設置在控制器中。
這些讀者不真的做了很多的幫助。
這是一個Ruby約定,它創建一個稱爲產品的「getter」和另一個稱爲產品。
例如,如果您有一個對象ph它等於ProductHelper.new。
ph = ProductHelper.new
並在該模塊中存在一個實例變量。
def initialize
@products = "awesomeness"
end
你將不能夠沒有在模塊上做了發送,因爲這將被視爲私有pH值的該實例來訪問它。
(不要擔心,如果下面是它的不是混亂,你會看到很多的新人,軌道,你會更看到它時,你進入元編程。)
ProductsHelper.send :products
但是,attr_reader將允許您讀取方法或變量,就好像它是實例的屬性一樣。
ProductHelper.products
它基本上爲你做這段代碼。
def products
@products # which is an instance variable within the instantiated object.
end
雖然你通常只看到這些在沒有你的模塊模型類......因爲在Ruby中所有類模塊,但是,這種行爲存在於這個水平了。如果你沒有任何方法,那麼會返回信息,然後調用.products將只返回零。
在Ruby中,也有創建「setter」的attr_writers。
def products(value)
@products = value
end
它允許你這樣做。
ph.products = "some awesome thing"
最後你還有attr_accessor,它在一個動作中創建了一個getter和setter。