开发者

Dynamically Generating ORM Classes

I'm working on a Sinatra-based project that uses the Datamapper ORM. I'd like to be able to define criteria for the DM validations in an external YAML file so that less-experienced users of the system can easily tweak the setup. I have this working pretty well as a proof-of-concept, but I suspect there could be a much easier or a least less processor-intensive way to approach this.

Right now, the script loads the YAML file and generates the DM classes with a series of eval statements (I know this already places me on thin ice). The problem is that this process has to happen with every request. My brigh开发者_JAVA技巧t idea is to check the YAML for changes, regenerate the classes and export to static source if changes are detected, and include the static files if no changes are detected.

This is proving more difficult than I anticipated because exporting code blocks to strings for serialization isn't as trivial as I expected.

Is this ridiculous? Am I approaching this in an entirely wrong-headed way?

I'm new to Ruby and the world of ORMs, so please forgive my ignorance.

Thanks!


DM validations in an external YAML file so that less-experienced users of the system can easily tweak the setup

A DSL for a DSL. Not having seen your YAML I still wonder how much easier than the DM Validations it really can get?

require 'dm-validations'
class User
  include DataMapper::Resource

  property :name, String
  # Manual validation
  validates_length_of :name, :max => 42

  # Auto-validation 
  property :bio, Text, :length => 100..500
end

Instead of going for YAML I would provide the less-experienced users with a couple of relevant validation examples and possibly also a short guideline based on the dm-validations documentation.


It does seem a little crazy to go and put everything in YAML, as that's only a shade easier than writing the validations in Ruby. What you could do is make a DSL in Ruby that makes defining validations much easier, then expose that to your users instead of the whole class.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜