Sacki
Sacki

Reputation: 137

How Can I "Inherit" a Ruby Module to Create Another Module?

I've been working on Ruby wrapper for some thrid-party product DB API.

The API is REST-ish and has models like Product, Category, Company, Event, etc, with API endpoints like /api/Product.getInfo.

My approach is to create the corresponding Ruby classes to these API models with API call wrappers and convenient methods. All of such model classes share the same parent class, Base, which abstracts API calls and has other common features.

There is a lot of similarities among theese API models. For instance, Product, Company, and Event models can be tagged and hence have a set of API calls for tagging, such as createTag, deleteTag, getTags, and, to abstract the tagging feature, I have created Taggable module and have it included in these three models.

Now, the problem is, there is this "review" feature with two primary API calls - createReview and getReviews, shared among Product, Event, Company, and some other models (omitted for simplicity); however, only Product and Event models support both createRiview and getReviews, and the rest only support getReviews.

Then I thought it'd be nice to have two modules - Reviewable and WithReviews where the former (read/write) "inherits" the latter (read-only), but apparently, Ruby does not support sub-moduling.

What should I do now?

  1. Should I make a write-only version instead of read/write version (i.e. Reviewable) and include both modules in Product and Event models?
  2. Is there any Ruby way to somehow "inherit" WithReviews (read-only) to create Reviewable (read/write)?
  3. Or am I totally off and there is a better way to tackle this kind of problem???

Also, what do you think of my module naming?

Like,

I think the first two -ables sound fine, but is there a better way or convention of naming the read-only version?
Do you have any recommendation for WRITE-ONLY module naming in case I have to create one?

Upvotes: 3

Views: 4373

Answers (2)

uncutstone
uncutstone

Reputation: 408

You can just include module WithReviews in module Reviewable.

module WithReviews
  def getReviews;end
end
module Reviewable
  include WithReviews
  def createReview;end
end

Upvotes: 3

epsilones
epsilones

Reputation: 11619

It's not very simple to understand your question. But, here's some generalities

You can create modules inside modules. So writting this is possible

module A
   module B
   ...
   end
end

Btw, you can include or extendmodules inside others. The difference between both, is that the fist transfers instance methods, and the second class methods. You can look at this doc

Upvotes: 1

Related Questions