views:

58

answers:

3

Basically, I have an RPG-type Rails application. I'm storing skills in a skills database with the following fields: name, min_level, skill_type, formula

My formula is stored as a String, currently. The idea is to have it say something like "1000*min_level" and somehow run it to calculate the skill damage.

Is there any good way to do this?

+1  A: 

You could possibly use eval. If min_level is a variable in scope, then that string can be executed as Ruby without any intermediate steps.

Huge security issues with allow code to execute like that, of course. Depends where these Strings are coming from.

Toby Hede
Is there a good way to make this more secure? Like say there are a finite number of variables I would want to deal with, could I somehow limit access to other variables besides those?
Karl
I wouldn't expect any end-user to be able to input the strings, however. It would only be done by an administrator of sorts, I'm still a little wary though.
Karl
Keep in mind an "administrator" inputting/editing this Skill data would have to have sufficient knowledge of Ruby in the first place (at least enough to grasp how the logic works), not to mention an understanding of the underlying class logic in the first place. This is a potential point of failure, since mistyped logic may or may not run, or produce undesired results.
bojo
+1  A: 

While it would probably be best to keep application logic in the application itself, this would be a simple matter of using eval().

eval("1000 * %i" % min_level)
bojo
There could be many many skills and I don't really want to hardcode those.
Karl
I would suggest making a SkillConfig model which you can edit as a game administrator (via an admin interface). Put your multipliers in there, then you can do something like: result = skill_config.foo_multiplier * skill.min_level or what have you. The benefit to this is that a) you have no hard coded logic, and b) you aren't using a potentially abusable eval().
bojo
What if I later decide to implement, say, damage based on time of day? In order to implement that I would have to break the implementation of every existing skill, as opposed to just modifying a single method.
Karl
Well, you have to make a decision at that point. Do you edit and update your game logic (most would say preferred), or do you write a Rails Migration to retrieve and change your 1000+ Skills in the database, along with the potential hassle of parsing skill data that may or may not apply depending on the new conditions?
bojo
+1  A: 

Maybe you can try doing something in between: not allow admin to edit these expressions directly, but create some simple (?) parser which would stand in the middle and which would

  1. parse and validate the expression admin entered, before saving it to the database
  2. actually evaluate expressions from the database, given a hash of skill values and other relevant parameters anytime you need it
Mladen Jablanović