gpt4 book ai didi

ruby-on-rails-3 - 如何在葡萄 api 应用程序中拆分东西?

转载 作者:行者123 更新时间:2023-12-03 22:35:55 25 4
gpt4 key购买 nike

在我看到的每个例子中,人们只实现了一个巨大的 api.rb 文件。前任:

  • intridea/grape
  • bloudraak/grape-sample-blog-api
  • djones/grape-goliath-example

  • 虽然这种方法按原样运行良好,但它很快就会变得拥挤且难以维护,因此我想在我的应用程序上拆分内容。

    例如,我想从我的资源中拆分我的实体,然后在不同的文件之间拆分我的资源。举些例子:
    app
    - api
    api.rb
    - entities
    - weblog.rb
    - post.rb
    - comment.rb
    - resources
    - weblog.rb
    - post.rb
    - comment.rb

    现在, api.rb 会是这样的:

    require 'grape'
    module Blog
    class API < Grape::API
    prefix "api"
    end
    end

    app/api/entities/post.rb 会是这样的:

    module Blog
    module Entities
    class Post < Grape::Entity
    root 'posts', 'posts'
    expose :id
    expose :content
    end
    end
    end

    app/api/resources/post.rb 会是这样的:

    module Blog
    class API < Grape::API
    resource :posts do
    get do
    present Post.all, with: Blog::Entities::Post
    end

    desc "returns the payment method corresponding to a certain id"
    params do
    requires :id, :type => Integer, :desc => "Post id."
    end
    get ':id' do
    present Post.find(params[:id]), with: Blog::Entities::Post
    end
    end
    end
    end

    当我们这样做时,我们会遇到以下消息:

    Expected /blog-app/api/resources/post.rb to define Post



    解决方案(感谢 dB. 和我的同事)

    您必须将结构更改为:
    app
    - api
    api.rb
    - resources
    - post_api.rb

    然后,在 post_api.rb
    module Blog
    class Resources::PostAPI < Grape::API
    resource :posts do
    get do
    present Post.all
    end
    end
    end
    end

    最后, api.rb 变成:

    require 'grape'
    module Blog
    class API < Grape::API
    prefix 'api'
    version 'v1', :using => :path
    format :json

    mount Blog::Resources::PostAPI => '/'
    end
    end

    现在 /api/v1/posts应该管用 :)

    最佳答案

    post.rb 中的类应该是 Post,而不是 API。然后你可以在类 API 中挂载 Post API。

    class API < Grape::API
    mount Blog::Post => '/'
    end

    为了避免混淆,我也将 Post 放在 Resources 命名空间中,或者将其重命名为 PostAPI。

    关于ruby-on-rails-3 - 如何在葡萄 api 应用程序中拆分东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14857987/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com