3

Multiple inheritance in Ruby is simulated by including modules, but it's not possible to inherit properties directly from modules (that are not classes). The solution I came up was to define properties on the module initialization (code below). Is there a better way to achieve multiple inheritance compared the code below (inheriting methods AND properties)?

module MyCustomMixin
    attr_accessor :a

    def initialize
        self.a = 1
    end

    def b
        "something"
    end
end

class MyCreateView < CreateView
    include MyCustomMixin
end

class MyReadView < ReadView
    include MyCustomMixin
end

class MyUpdateView < UpdateView
    include MyCustomMixin
end

class MyDeleteView < DeleteView
    include MyCustomMixin
end
7
  • Ruby doesn't have properties. What are you talking about? Commented Jul 10, 2013 at 12:14
  • I mean attribute. I'm sorry if they have different names across languages, but the concepts are the same. Commented Jul 10, 2013 at 12:33
  • 1
    Ruby doesn't have attributes either. "Attribute" is simply given a name to a method that doesn't take arguments. It's still a method just like any other. Commented Jul 10, 2013 at 12:35
  • So the b method in MyCustomMixin acts as an attribute, because all it does is return a value. Commented Jul 10, 2013 at 13:03
  • Yes. You could also define a method b= to make it a writeable "attribute". Commented Jul 10, 2013 at 13:09

1 Answer 1

1

The thing is, this is technically doable, but it requires a bit of finagling that doesn't look very pretty (especially with #initialize) - and rightfully so. I wouldn't recommend writing code in this way if the only purpose is to prevent code repetition.

So, consider:

  • What's the reason for having a MyFooView version for every FooView? Is it just to include mixins?
  • Perhaps all the Views have a common parent to which you could add this mixin?
  • Does the mixin contain functionality that is used in things other than View? Why not just add it directly to the parent View?
  • If the mixin is really that independent of the View classes, why isn't it just a class in itself, so that each View would own an instance of it?
Sign up to request clarification or add additional context in comments.

1 Comment

I came up with this question because I have a Python background (Python supports multiple inheritance, which is often used to apply mixins. Example: bit.ly/1kxoaMI). I'm also a C#/PHP developer, and your suggestions may be applied to them as well, so my conclusion is that Ruby's inheritance model is not that that different from these languages.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.