开发者

Allow users to customize strings that are later interpreted with embedded expressions

开发者 https://www.devze.com 2023-02-23 11:55 出处:网络
Originally we built out a service on Rails that used static strings with embedded expressions (#{}) for values like the datetime of an object. These strings were used to build communications to other

Originally we built out a service on Rails that used static strings with embedded expressions (#{}) for values like the datetime of an object. These strings were used to build communications to other users.

We want to provide a way for our users to customize default text with embedded expressions.

They are currently scattered throughout our models, controllers and views, but we want to put them all in one place (like localization, but it is different per user).

Our initial thinking is to use MongoDB (via MongoMapper) to create a customization document that stores the string开发者_运维百科s. Then we can continuously add new strings without doing a migration.

We would store the string as something like this:

"Testing out a string at #{object.datetime}."

Later a user can use a form we have to edit these strings for their use (isolated from other users).

Then when we want to use the string we would either replace the #{} with a value or somehow tell the embedded expression evaluate then.

Question: how do I later calculate a string with embedded expressions after it is defined? Is there something like to_sym for creating symbols?

Is there a better way to do this?

Thanks!


You'll want to use or write your own templating engine. And by templating engine, I mean something as simple as:

values = {"foo" => "bar"}
"turn this {{foo}} into bar".gsub(/\{\{.+?\}\}/) do |x|
  values[x[2..-3]]
end

# => "turn this bar into bar"

You might also like liquid or mustache for this purpose. You can reject out of hand any solutions involving eval: they aren't safe with untrusted strings.

As far as storing the configuration values, mongo seems fine.


Apparently facets allows you to do this, using String.interpolate. I came across it while watching this video this morning.

0

精彩评论

暂无评论...
验证码 换一张
取 消