[英]Include all the ruby files from a directory inside a block as inline code
紅寶石文件的結構如下圖所示,
market
|__abcd
|__classification
|__for_sale_mobile_phone.rb
|__catalogues
|__mobile_phone_brands
|__acer.rb
|__apple.rb
|__samsung.rb
在for_sale_mobile_phone.rb
,我希望將所有品牌的mobile_phone_brands
在一個mobile_phone_brands
下。
我正在嘗試以不流行的方式加入品牌,
.....
c.tree_field :brand, { child_key: :model } do |b|
Dir[
File.dirname(__FILE__) + '/catalogues/mobile_phone_brands/*.rb'
].each { |brand| load brand }
b.required = true
end
.....
這是品牌文件的外觀。 例如apple.rb
b.value "apple" do |brand|
brand.value "6plus"
brand.value "6s"
brand.value "6s-plus"
brand.value "se"
brand.value "7"
brand.value "7-plus"
brand.value "other-model"
end
我低於錯誤,
undefined local variable or method `b' on line 1: apple.rb
如何在阻止范圍內包含文件?
提前致謝!
您應該將文件“加載”與函數執行分開。 像這樣重新定義您的文件。
class AppleLoader
def self.load(b)
b.value "apple" do |brand|
brand.value "6plus"
brand.value "6s"
brand.value "6s-plus"
brand.value "se"
brand.value "7"
brand.value "7-plus"
brand.value "other-model"
end
end
end
在文件頂部,您可以加載所需的類,如下所示:
require '/catalogues/mobile_phone_brands/apple_loader.rb'
當您要在b
對象中加載Apple品牌時:
AppleLoader.load b
更好的方法:在我看來, Apple.rb
只是從數據方面推遲了Samsung.rb
。 如果真是這樣,並且兩者的功能都相同,那么我寧願:
將該數據放在Yaml文件( brands.yml
)中,而不是rb文件中。
brands: apple: ["6plus", "6s"] samsung: ["galaxy"]
只有一個常見的裝載機,稱為BrandLoader
class BrandLoader def self.load(b, brand_name, values) b.value brand_name do |brand| brand_values.each do |value| brand.value value end end end end
閱讀Yaml遍歷品牌
configurations = YAML.load "brands.yml" configurations["brands"].each do |brand_name, values| BrandLoader.load(b, brand_name, values) end
我發現的方法是使用eval
但謹慎的閱讀是eval-suppose-to-nasty , eval
對我有效,因為我沒有使用用戶輸入。
要在不同文件中編寫任何代碼,請執行在調用位置編寫的代碼。 使用eval(File.read(file_path)
.....
c.tree_field :brand, { child_key: :model } do |b|
Dir[
File.dirname(__FILE__) + '/catalogues/mobile_phone_brands/*.rb'
].each { |brand| eval(File.read(brand)) }
b.required = true
end
.....
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.