zoukankan      html  css  js  c++  java
  • Rails + rabl

    当我们使用rails generate scaffold的方式生成MVC的时候,rails会自己主动给我们生成一系列的文件,包含了怎样用json显示model的view。这样事实上默认了你的系统是一个CRUD的系统,可是我们知道RESTful不是CRUD。把model直接暴露出去不是一个非常好的选择。


    rabl是一个DSL能够方便定制生成对象的显示信息的gem:https://github.com/nesquena/rabl


    以下是详细的操作过程:


    1.首先创建一个新的railsproject:

    rails new rabl-app


    2.在Gemfile中加入rabl的依赖:

    gem 'rabl'


    3.创建Model:

    rails g model Blog title:string author:string content:text


    4.迁移数据库:

    rake db:migrate


    5.创建controller:

    在app/controllers下创建一个新的空文件blogs_controller.rb

    内容例如以下:

    class BlogsController < ApplicationController
       def index
          @blogs = Blog.all
       end

       def show
          @blog = Blog.find(params[:id])

       end
    end

    能够使用stub数据用于測试:

    @blog = Blog.new({:id => 3, :title => "good title", :author => "good author", :content => "good content"})


    6.创建rabl相应的view:

    在app/views下创建一个新的空目录blogs:

    在app/views下创建两个新文件:index.json.rabl和show.json.rabl


    show.json.rabl:

    object @blog

    attributes :id, :title, :author, :content


    index.json.rabl:

    collection @blogs

    extends "blogs/show"


    7.配置route

    在routes.rb中:

    Rails.application.routes.draw do
      resources :blogs
    end


    8.启动server

    rails s


    訪问:http://localhost:3000/blogs/3.json

    得到结果:

    {"blog":{"id":3,"title":"good title","author":"good author","content":"good content"}}

    我们上面的样例仅仅是演示了怎样在rails中使用rabl,并非说上面的显示方法就是好的构造对象现实的方法,很多其它的能够看看:

    https://github.com/nesquena/rabl

    http://railscasts.com/episodes/322-rabl?

    view=similar

  • 相关阅读:
    跟我学Windows Azure 一 创建Windows Azure试用账号
    Dynamic编程
    多线程下的资源同步访问
    避免在同一机器上同时运行同一应用程序的多个实例
    依赖注入与Service Locator
    MVP演化论
    应用MVP模式对遗留代码进行重构
    对遗留代码的解依赖技术
    单元测试之测试方法
    单元测试之Mock
  • 原文地址:https://www.cnblogs.com/gcczhongduan/p/5159342.html
Copyright © 2011-2022 走看看