@
@
@Quty2016-09-11 16:16:35
ruby
@Quty, 2016-09-11 16:16:35

How to split a class into multiple files in Ruby?

I understand with Grape and formed for myself an application structure similar to that described here ( repository ), only without using Rails. It turned out the following:

app/api/v1.rb
app/api/v1/product.rb
app/api/v1/review.rb

app/api/v1.rb :
module API
  class V1 < Grape::API
    version 'v1', using: :path
    content_type :json, 'application/json; charset=UTF-8'
    prefix :api
    format :json

    before do
      header['Access-Control-Allow-Origin'] = '*'
      header['Access-Control-Request-Method'] = '*'
    end

    mount Product
    mount Review
  end
end

app/api/v1/product.rb :
module API
  class V1::Product < Grape::API
    resource :products do
      get do
        %w(Cofee Tea Rice Meat)
      end
    end
  end
end

app/api/v1/review.rb :
module API
  class V1::Review < Grape::API
    resource :reviews do
      get do
        "This is review"
      end
    end
  end
end

There is environment.rb , which requests all the necessary files before starting the application. If I first request app/api/v1.rb , then the error is uninitialized constant API::V1::Product . If you first request one of the files in the subdirectory - uninitialized constant API::V1 . In principle, this is all logical and understandable.
Of course, you can declare a Product and Review prototype and request app/api/v1.rb first . Or, first request files in the subdirectory, and make them look like
module API
  class V1 < Grape::API
    class Product < Grape::API
      ...
    end
  end
end

Is it possible to leave the structure and code, while getting rid of errors? After all, in the application I cited at the beginning of the question, exactly the same structure is used and it all works.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question