ITeye博客

创建一个rails3 engine

doabit · 2010-10-06 05:41 · rails · 编程语言 · Markdown

rails3中的engine 比较强大,现在写gem, 可以以 engine为基础构建。而且慢慢地可以把rails程序分模块拆分。Rails 3.1中更可以把engine以rake的方式加载。。比如


Rails.application.routes.draw do
  mount Blog::Engine => "/blog"
end

创建一个engine, 有个 gem可让我们的工作更加方便Enginex 下面以rails3 为例,创建一个简单的rails3 engine::cms:只包含一个文章的管理

事先安装好enginex

sudo gem install enginex

1.创建基本框架并以rspec做为测试:

enginex cms  -t rspec

enginex会为我们创建好一个engine的框架。

2.创建所需要的目录


   cd cms
   mkdir -p app/controllers
   mkdir -p app/models
   mkdir -p app/views/layouts
   mkdir  -p public/javascripts
   mkdir -p public/stylesheets
  

由于我自己测试写的就不怎么样,所以这里跳过写测试部分,就不按 BDD流程来了。主要实现engine的功能

3.创建一个model--Post(这里是基于AcciveRecord,如果用mongoid,就更简单些,就不用管migration了)

touch app/models/post.rb
   class Post < ActiveRecord::Base
   end

4.创建 controller..(layout "cms"这里是使engine使用自己的布局)


     touch app/controllers/posts_controller.rb
  

添加CURD


class PostsController < ApplicationController
  layout "cms"
  respond_to :html


  def index
    @posts = Post.all
  end

  def show
    @post = Post.find(params[:id])
  end

  def new
    @post = Post.new
  end
  
  def create
    @post = Post.create(params[:post])
    respond_with(@post)
  end

  def edit
    @post=Post.find(params[:id])
  end

  def update
    @post=Post.find(params[:id])
    flash[:notice] = "Successfully updated..." if @post.update_attributes(params[:post])
    respond_with @post
  end

end
  

5.创建layout ---cms.html.erb

touch app/views/layouts/cms.html.erb

添加代码:


<!DOCTYPE html>
<html>
  <head>
    <title>Cms</title>
    <%= stylesheet_link_tag "style" %>
    <%= javascript_include_tag "jquery","rails" %>
    <%= csrf_meta_tag %>
  </head>
  <body>
    <div id="container">
      <% flash.each do |name, msg| %>
        <%= content_tag :div, msg, :id => "flash_#{name}" %>
      <% end %>
      <h1>Cms Engine</h1>
      <%= yield %>
    </div>
  </body>
</html>
 

6.创建所需的js,和 css,到public文件夹, style.css简单写点

  h1{
    text-align:center;
    color:red;}

7.创建index.html.erb,show.html.erb.......等所需要文件到 app/views/posts/ 下,这里就不多说明,就是普通写法

8.创建lib/cms/engine.rb, 其中,app.middleware.use ::ActionDispatch::Static, "#{root}/public"这里是告诉 engine, 使用自己的public目录下的资源文件 ,前提是,打包成gem, plugin模式下无效,需要另加处理

   module Cms
  class Engine < Rails::Engine
    initializer "static assets" do |app|
      app.middleware.use ::ActionDispatch::Static, "#{root}/public"
    end
  end
end

9.修改lib/cms.rb


   require "cms/engine"
 

10.添加config/routes.rb

  
Rails.application.routes.draw do |map|
  root :to => "posts#index"
  resources :posts
end
  

11.因为使用的active_record,所以我们要使用migration,建立一个generator,复制migration文件 lib/generators/cms/install_generator.rb


 module Cms
  class InstallGenerator < Rails::Generators::Base
    include Rails::Generators::Migration
    source_root File.expand_path('../templates', __FILE__)
    desc "Copies migration to main project"

    def self.next_migration_number(dirname)
      if ActiveRecord::Base.timestamped_migrations
        Time.now.utc.strftime("%Y%m%d%H%M%S")
      else
        "%.3d" % (current_migration_number(dirname) + 1)
      end
    end

    def copy_migration
      migration_template "create_posts.rb", "db/migrate/create_posts.rb"
    end
  end
end

  

12...现在,新建立一个migration文件到lib/generators/cms/templates/create_posts.rb


   class CreatePosts < ActiveRecord::Migration
  def self.up
    create_table :posts do |t|
      t.string :title
      t.text  :body
      t.timestamps
    end
  end

      def self.down
         drop_table :posts
      end
    end
 

这样,我们就可以通过rails g cms:install 进行migration文件的复制了

  1. 打包成gem,要先悠 rakefile, 添加要打包的目录,默认只有 lib目录
 s.files =  FileList["[a-z]*", "lib/**/*","app/**/*","public/**/*","config/**/*"]

然后在终端rake gem生成 cms.gem在pkg目录下,安装pkg目录下的 gem 既可

14.要使用这个gem,只要新建工程,rails new test ,修改 gemfile,添加

gem "cms"

然后

 rm public/index.html
    rails g cms:index
    rake db:migrate
    rails s

打开浏览器,loclhost:3000 就可以看到post页面,并且使用的css是 gem 自身的。

-------暂时写到这,public 资源,只有在 gem 下有用,想要在plugin  状态下也有用,要在cms根目录下建立一个init.rb,然后加上


config.middleware.use ::ActionDispatch::Static, "#{root}/public"
 

mark::: 转载注明:javaeye--doabit

评论(1)

  1. #1 楼 · 山雨欲来风满楼 · 2012-03-10 14:21

    不错,正在研究engine,想想看,可以剥离这些应用是多么爽的一件事情啊

评论功能维护中,当前仅展示历史评论。