所以我想清楚如何爲一個班級設置一些選項。 '選項'是一個散列。我想這是錯的,但爲什麼(我怎樣才能讓它流動得更好)?
1)篩選出選擇,我不想要或需要
2)設置一些實例變量在其他地方使用
3),並另設散與處理的選項@current_options 。
def initialize_options(options)
@whitelisted_options, @current_options = [:timestamps_offset, :destructive, :minimal_author], {}
n_options = options.select { |k,v| @whitelisted_options.include?(k) }
@current_options[:timestamps_offset] = @timestamp_offset = n_options.fetch(:timestamps_offset, 0)*(60*60*24)
@current_options[:destructive] = @destructive = n_options.fetch(:destructive, false)
@current_options[:minimal_author] = @minimal_author = n_options.fetch(:minimal_author, false)
end
我猜這是一個有點多,不管是什麼我通過我得到:
{:timestamps_offset=>0, :destructive=>false, :minimal_author=>false}
當我做這行通過命令行線,它的作品,因爲我想它但不是在我的班級。那麼究竟發生了什麼,我該如何清理這些?
編輯:這實際上是從我正在使用它的類中脫離出來的,但它內部並不如此,現實中的某些事情正在發生,我現在還沒有意識到。
attr_reader:current_options是如何在類上設置的,也許需要一些修改。
EDIT2:該方法的第2行應該從@whitelisted_options
EDIT3選擇:其實原來是一些我沒有想到的......「選擇」成爲從YAML文件解析字符串......並且我正在提取符號,改變這種方式會在方法尋找符號之前找不到,例如「破壞性」vs:破壞性的,所以總是默認違約。簡而言之,我只需要在導入選項時符號化散列鍵。
我確實改變了這一點,但並沒有反映出原來的情況。 n_options是具有無效選項的選項。 – blueblank 2012-03-01 23:21:38
這很接近,但實際上並未返回設置變量,即始終返回默認選項(或者我看不到它的權利)。但它很接近,給我提供了另一個線索,讓我做的事情略有不同。 – blueblank 2012-03-02 02:36:59
@blueblank我的代碼在設置了'@ current_options'後返回了'@ whitelisted_options'。修正:) – andrewdotnich 2012-03-02 04:34:53