简体   繁体   English

从我的Ruby on Rails Gem渲染视图

[英]Rendering a view from my Ruby on Rails Gem

I created a simple Gem for Ruby on Rails; 我为Ruby on Rails创建了一个简单的Gem。 the idea is that it provides some code/views for common actions (index/show/etc.) that I use in several of my applications. 这个想法是,它为我在几个应用程序中使用的常见操作(索引/显示/等)提供了一些代码/视图。 I would like to "DRY it up" in a Gem. 我想在宝石中“干燥”。

Creating the Concern went without problems, however, I can't quite seem to manage to render a view in my application. 创建关注点没有问题,但是,我似乎无法设法在应用程序中呈现视图。

For example, in my lib/rails_default_actions/rails_default_actions.rb I do: 例如,在我的lib/rails_default_actions/rails_default_actions.rb我这样做:

module RailsDefaultActions
  module DefaultActions
    extend ActiveSupport::Concern
      respond_to do |format|
        format.html { render 'default/index' }
      end
    end
  end
end

But an error is raised: 但是会引发一个错误:

Missing template default/index with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :slim, :haml]}. Searched in:
  * "/home/martin/myapp/app/views"
  * "/home/martin/myapp/vendor/bundle/ruby/2.1.0/gems/devise-3.2.4/app/views"
  * "/home/martin/myapp"

I eventually sort of managed to hack my way around this error, but it feels very kludgey and doesn't work in some scenarios. 我最终设法设法解决了这个错误,但是感觉很不协调,在某些情况下不起作用。 What is the correct way to include views in a gem? 在gem中包含视图的正确方法是什么?

I looked at creating an Engine, but that seems like overkill, since I just have a concern and a few views. 我曾考虑过创建一个引擎,但这似乎有点过头了,因为我只是有一个顾虑和一些看法。

The "correct" way to do this since Rails 3 is to create an Engine ; 从Rails 3开始,“正确”的方法是创建一个Engine there's also a Rails guide for this, but creating a basic engine is as easy as: 也有一个Rails指南 ,但是创建基本引擎很容易:

module MyGemName
  class Engine < Rails::Engine
  end
end

When Rails looks for a view to render, it will first look in the app/views directory of the application. 当Rails寻找要渲染的视图时,它将首先在app/views目录中寻找。 If it cannot find the view there, it will check in the app/views directories of all engines that have this directory. 如果找不到该视图,它将检入具有该目录的所有引擎的app/views目录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM