我希望能夠創建一個字符串作爲%%變量%%,並將它解釋爲方法對象而不是字符串對象。因此,%% UserDatabase.name %%將被讀爲@ DatabaseUser.name,並隨後返回類似「Michael」的內容。把一個變量字符串變成一個嚴格的對象
這是我到目前爲止有:
def parse_block(component)
component.gsub!(/%%([a-z].*)%%/s, "@#{'\\1'}")
end
任何幫助,將不勝感激。謝謝
我希望能夠創建一個字符串作爲%%變量%%,並將它解釋爲方法對象而不是字符串對象。因此,%% UserDatabase.name %%將被讀爲@ DatabaseUser.name,並隨後返回類似「Michael」的內容。把一個變量字符串變成一個嚴格的對象
這是我到目前爲止有:
def parse_block(component)
component.gsub!(/%%([a-z].*)%%/s, "@#{'\\1'}")
end
任何幫助,將不勝感激。謝謝
我認爲最好在重新注入之前解釋它。
def parse_block(component)
component.gsub!(/%%([a-z].*)%%/s) do |c|
eval($1)
end
end
但這是一個非常糟糕的主意,如果字符串不安全,您可能會遇到一些安全問題。
也許您可以傳遞一個模型名稱,模型ID和所需的方法?所以你最終會以
def parse_whatever(model_name, model_instance_id, method)
active_record_class = Kernel.const_get(classname)
active_record_instance = active_record_class.find(model_instance_id)
active_record_instance.send(method)
end