On 2/18/07, Trans <transfire / gmail.com> wrote:
> A notion came to me yesterday with regards to how we extend classes.
> On the one hand we can create a module and include it into a class,
> but this will not allow us to override a preexisting method -- for
> that we must reopen the class and play the alias and/ or binding game.
> Various ideas have been put forth for simplifying and improving the
> robustness of this, from #wrap_method, alias_method_chain, as well
> as :pre, :post methods and my own cuts (albeit they go a bit further
> than just method wrapping). But occurs to me that these add
> complexities onto something that is already straightforward if we are
> willing to separate out all class concerns into modules. In other
> words instead of writing:
>
>   class X
>     def a; "a";  end
>   end
>
> write:
>
>   module Xa
>     def a; "a";  end
>   end
>
>   class X
>     include Xa
>   end
>
>   X.new.a  #=> "a"
>
> Then it's easy enough to overlay new behaviors:
>
>   module Xb
>     def a; "{"+super+"}";  end
>   end
>
>   class X
>     include Xb
>   end
>
>   X.new.a  #=> "{a}"
>
> Since that works so well, it occurs to me, why not make this the
> fundamental behavior of defining a class? In other words defining a
> class:
>
>   class X
>     def a; "a"; end
>   end
>
> could be equivalent to writing:
>
>   class X
>     include( Module.new{
>         def a; "a";  end
>     } )
>   end
>
> So there would always be a module involved in the definition of a
> class. And classes become simply containers of modules.
>
> T.
>
I am not sure if I am grasping the quintessence (I have not forgotten
;) of your post
but your ideas just reinforce an idea which is getting clearer and
clearer in my mind.
Use classes with care, actually we could do some Javascript in pure
ruby, kindly look at this
code e.g.

The variation to your idea is that I really forget Class and only use
objects and prototypes.
So #include becomes #extend, Class.new becomes a constructor in the
Javascript sense.

module M1
  attr_accessor :name
end

module M2
  attr_reader :value
  def inc; @value += 1; end
  def dec; @value -=1 ; end
  def init
    @value = 41
    self
  end
end


def newM
  m = Object.new
  m.extend M1
  m.extend M2

  m.init
end

m = newM
m.name = 'Tom'
puts m.name
m.inc
puts m.value


Cheers
Robert
-- 
We have not succeeded in answering all of our questions.
In fact, in some ways, we are more confused than ever.
But we feel we are confused on a higher level and about more important things.
-Anonymous