开发者

Rails lazy loads my model's rb file, forcing me to write slightly uglier code

So I've got a model in my rails app (app/models/foo.rb), like so:

class Foo
    def initialize(bar)
        @bar = bar
    end

    def puts_bar
        puts @bar
    end
end

def Foo(bar)
    Foo.new(bar)
end

When I try to use this model like this:

Foo(bar).puts_bar

it can't find it because it hasn't loaded the model's file yet. If I use the model like this:

Foo.new(bar).puts_bar

Rails goes out and finds my model and loads it (and after that my foo function works 开发者_运维百科too).

How can I tell Rails to load my model file so my foo function works from the start?


you've made puts_bar an instance method, but you are trying to use it like a class method. These are incompatible.

Initialize won't happen until you "new up" a foo. to get around this you could do:

class Foo
  def self.puts_bar(bar)
    puts bar
  end
end

this will allow you to do:

Foo.puts_bar(bar)


You could put something like this into config/initializers/ugly_hack.rb (or whatever filename you like ;)

Dir.chdir File.join( Rails.root, 'app', 'models' ) do
  Dir['**/*.rb'].each do |f|
    f.slice! ".rb"
    model_class = f.classify
    eval <<-EOI
    def #{model_class} *args
      #{model_class}.new( *args )
    end
    EOI
  end
end

This will take all the files in your app/models directory, and create methods for them. It's not creating those methods within the model file, so not relying on the lazy loading to make those methods available.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜