开发者

How to organize models in Sinatra?

I have a tirable orgnizing my Models in a Sinatra project.

Let's say I have 2 models: Post and Comment, nn Post model, I have to call Comment model. And now I have <class:Post>': uninitialized constant Comment (NameError).

I know its an issue in ordering the requiring for the models, but what about if I have lots of models? What's the Rails way in requiring models, etc.?

UPDATE

I use this code to auto_load my models in Sinatra/Rack/Grape applications. This code should be at t开发者_开发问答he top of your code ie in the boot file.

models = File.join(File.dirname(__FILE__), 'app', 'models') # path to your models
$LOAD_PATH << File.expand_path(models)

# Constent Missing for requiring models files
def Object.const_missing(const)
    require const.to_s.underscore
    klass = const_get(const)
    return klass if klass
end


You should put all of your models in a folder, such as lib in your application, then you can add this to the top of your Sinatra app file:

$: << File.dirname(__FILE__) + "/lib" # Assuming app.rb is at the same level as lib

require 'post'
require 'comment'

You should organise your code so that you do not call other models until all model declarations are loaded.


The Rails way is based on a very nice Ruby feature: const_missing. You could write your const_missing method or looking around the web for a solution with const_missing and sinatra.


no prob when I tried this

a Comment if it is in a method of Post shouldn't be actually evaluated there must be some circumstance triggering the NameError

don't call Post in the body of the class declaration load all the model files per the first commenter's suggestion

shouldnt be having the same reference troubles as Java per se in a dynamic lang like Ruby

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜