【问题标题】:How to package application layout into a Ruby gem?如何将应用程序布局打包到 Ruby gem 中?
【发布时间】:2012-05-24 18:28:30
【问题描述】:

我正在处理一个包含三个不同应用程序的项目。他们应该共享一些模型和外部布局。为避免代码重复,我尝试将应用程序布局 (project_name/app/views/layouts/application.html.haml) 提取到 gem 中。

我按照以下步骤操作:

  1. bundle gem common创建基础gem结构
  2. 将布局文件放入common/app/views/layouts/application.html.haml
  3. 编写了 Gemspec 描述符

    # -*- encoding: utf-8 -*-
    require File.expand_path('../lib/common/version', __FILE__)
    
    Gem::Specification.new do |gem|
      gem.authors       = ["Arthur Alkmim"]
      gem.email         = ["myemail@here"]
      gem.description   = %q{Common project files}
      gem.summary       = %q{Common project files, including layout and migrations}
      gem.homepage      = ""
    
      gem.files         = `git ls-files`.split($\)
      gem.executables   = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
      gem.test_files    = gem.files.grep(%r{^(test|spec|features)/})
      gem.name          = "common"
      gem.require_paths = ["lib"]
      gem.version       = Common::VERSION
    end
    
  4. 提交更改

  5. gem build common.gemspec(成功)
  6. rake install(成功)
  7. gem 'common'放入项目Gemfile中

但项目仍然不会加载应用程序布局。我应该怎么做才能告诉我的项目必须通过 gem 加载布局文件?

提前致谢。

【问题讨论】:

  • 如何使用 git 子模块或 svn 外部?如果你走 gem 路线,只要有变化,你就必须构建/安装。
  • @KreeK 子模块和外部是一种痛苦。根据我的经验,处理宝石更容易——只需运行bundle install 即可。尤其是 Git 子模块非常烦人。

标签: ruby-on-rails layout view gem gemspecs


【解决方案1】:

您是否已将 gem 添加到 Rails Gemfile 以将其包含在您的应用程序中?

您可以使用 path 选项来指定开发中的相对路径。例如

gem 'common', :path => "../path/to/gem"

不要忘记然后运行bundle install

【讨论】:

    【解决方案2】:

    我解决了它。我将application.html.haml 更改为common.html.haml 并将相关的布局调用放在ApplicationController 中。似乎 Rails 不允许我将 application.html 布局打包在 gem 中,但其他布局还可以。如果有人提出更好的解决方案(更少的解决方法),请发布!

    【讨论】:

    • 我会为您的 gem 提供一个生成器。让它用你的版本替换application.html.haml。类似rails g common:install
    • 我觉得比单纯的装饰控制器更麻烦。每次更新 gem 时,我都必须重新运行生成器,并且再次受到代码重复的困扰。
    • 出于好奇 - 您是否在使用 gem 的应用程序中删除了 app/views/layouts/application.html.haml
    猜你喜欢
    • 2016-10-02
    • 1970-01-01
    • 2014-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多