简体   繁体   English

从字符串中解析方法并将其存储在数据库中

[英]Parse method from string and store it in database

I want to allow users to specify a function for calculating some property and want to store this function in a generic class. 我想允许用户指定一个用于计算某些属性的函数,并希望将此函数存储在通用类中。 That is, each instance of the class have the same interface, but the result of calling the 'calculate' method varies depending on the user supplied function 也就是说,该类的每个实例都具有相同的接口,但是调用“ calculate”方法的结果因用户提供的函数而异

I would also like to serialize this class and store it in a database for later use. 我还想序列化此类并将其存储在数据库中以备后用。 This is what I am thinking 这就是我的想法

class LogicalCharge < Charge
    attr_reader :name, :type, :formula, :threshold

    def initialize(name: nil, type: nil, formula: nil, threshold: nil)
      super(name: name, type: type)
      @formula = formula
      @threshold = threshold
    end

    def parse(formula: nil)

    end

    def calculate(dimensions: nil)
      parse(formula: formula).call(dimensions) < threshold
    end

Any advice on how best to proceed from here? 关于如何最好地从这里进行的任何建议?

I would suggest a different approach where you have a hierarchy of related classes, one for each of your current variations of the calculate function, and a table with fields for the class name and each of the parameters for running it. 我建议使用一种不同的方法,在这种方法中,您具有相关类的层次结构,一个用于您的当前每个compute函数变体,一个表,其中包含用于类名称和用于运行它的每个参数的字段。

As the classes will all conform to the same interface, this should work well. 由于所有类都遵循相同的接口,因此应该可以正常工作。 You can then sanitize the user input cleanly and avoid the horrible security implications of letting users put executable code directly on your server. 然后,您可以干净地清理用户输入的内容,并避免让用户直接将可执行代码放在服务器上的可怕安全隐患。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM