Is there a way in Ruby/Rails to execute code that is in a string?

前端 未结 3 687
臣服心动
臣服心动 2020-12-23 16:36

So I have a database of different code samples (read snippets). The code samples are created by users. Is there a way in Rails to execute it?

So for example I have

3条回答
  •  甜味超标
    2020-12-23 16:48

    There is also another approach which you can use if you have a very limited use case or to limit the use cases.

    I had to use this approach to allow users to dynamically specify relative times e.g.3.months.ago

    I used a regex to sanitize the input from the users like so

    PERMITTED_OPERATIONS = /^\{\%([1-9]\.(day|year|month|hour|minute)(s\.|\.)ago|Time\.now)\%\}$/
    def permit?(operation)
      return !PERMITTED_OPERATIONS.match(operation.to_s).nil?
    end
    

    You could extend the regex to allow for from_now as well or create an array of regexes for permitted operations and loop over it.

    Would welcome any comments on this approach.

提交回复
热议问题