Доступ к модели от направляющие 3.1 Механизма

я боролся с этим в течение прошлого дня, и это сводит меня с ума!

Как осуществление изучения я решил, что упакую часть своего кода в Драгоценный камень направляющих. Этот код имеет действие контроллера, маршрут, модель и помощника, таким образом, я решил, что самый подходящий метод создания Драгоценного камня должен будет создать его как Механизм направляющих.

Все, кажется, работает хорошо, за исключением одной вещи. Когда я пытаюсь сослаться на Модель из Контроллера или Представлений (приложения, которое использует механизм), например:

@su = Shortener::ShortenedUrl.generate("http://stackoverflow.com")

я получаю следующую ошибку:

uninitialized constant Shortener::ShortenerHelper::ShortenedUrl

Это странно, потому что ошибки не происходит, когда я выполняю код от консоли проектов. Я думаю, что это вызывается фактом, я поместил весь код в пространство имен/модуль "Shortener". Я сделал это так, это поможет избежать конфликтов при использовании в других приложениях.

файл кода hierachy похож на это:

An image of the project directory/file listing

И вот код объявления класса/модуля (с удаленными кишками)из важных файлов в question

app/controllers/shortener/shortened_urls_controller

module Shortener
  class ShortenedUrlsController < ::ApplicationController

    # find the real link for the shortened link key and redirect
    def translate
      # convert the link...
    end
  end
end

app/models/shortener/shortened_urls

module Shortener
  class ShortenedUrl < ActiveRecord::Base

    # a number of validations, methods etc  

  end 
end

app/helpers/shortener/shortener_helper

module Shortener::ShortenerHelper

  # generate a url from either a url string, or a shortened url object
  def shortened_url(url_object, user=nil)

    # some code to do generate a shortened url

  end

end

lib/shortener/engine.rb

require "rails/engine"
require "shortener"

module Shortener

  class ShortenerEngine < Rails::Engine

  end

end

lib/shortener.rb

require "active_support/dependencies"

module Shortener

  # Our host application root path
  # We set this when the engine is initialized
  mattr_accessor :app_root

  # Yield self on setup for nice config blocks
  def self.setup
    yield self
  end

end

# Require our engine
require "shortener/engine"

shortener.gemspec

require File.expand_path("../lib/shortener/version", __FILE__)

# Provide a simple gemspec so you can easily use your enginex
# project in your rails apps through git.
Gem::Specification.new do |s|
  s.name                      = "shortener"
  s.summary                   = "Shortener makes it easy to create shortened URLs for your rails application."
  s.description               = "Shortener makes it easy to create shortened URLs for your rails application."
  s.files                     = `git ls-files`.split("\n")
  s.version                   = Shortener::VERSION
  s.platform                  = Gem::Platform::RUBY
  s.authors                   = [ "James P. McGrath" ]
  s.email                     = [ "gems@jamespmcgrath.com" ]
  s.homepage                  = "http://jamespmcgrath.com/projects/shortener"
  s.rubyforge_project         = "shortener"
  s.required_rubygems_version = "> 1.3.6"
  s.add_dependency "activesupport" , ">= 3.0.7"
  s.add_dependency "rails"         , ">= 3.0.7"
  s.executables = `git ls-files`.split("\n").map{|f| f =~ /^bin\/(.*)/ ? $1 : nil}.compact
  s.require_path = 'lib'
end

я издал весь код двигателя на GitHub:

https://ПРИМЕЧАНИЕ github.com/jpmcgrath/shortener

: у этого двигателя есть генератор, чтобы произвести необходимый файл миграции. Тип:

rails g shortener

Я также создал приложение rails 3,1, которое показывает проблему (посмотрите на строку 18 контроллера проектов):

https://github.com/jpmcgrath/linky

Какие идеи? Я прочесал Интернет, но не смог найти никакого действительно окончательного руководства по созданию движка Gems. Любые помощники были бы очень признательны.

Спасибо!

5
задан James P McGrath 1 September 2011 в 13:18
поделиться