Defining public classes in Ruby and MOP in Groovy

I am trying to find out if there is any equivalence to what I see in Groovy as ExpandoMetaClasses . I read about Open Classes , but I can't figure out what level of Ruby coverage allows me to change a class.

Borrowing the example from the blog above in Groovy, I could modify the Java String class and add a method to it as follows:

String.metaClass.shout = {->
  return delegate.toUpperCase()
}

println "Hello MetaProgramming".shout()

// output
// HELLO METAPROGRAMMING

And I think that Ruby would force you to override the class and possibly its alias (please help clarify my misunderstandings at this point):

class String
  def foo
    "foo"
  end
end 

puts "".foo # prints "foo"

There are ways in Groovy to override the basic methods of the Java library for individual instances or for a group of instances using categories that are similar to what I would call mixins in Ruby.

?

, - , - .rb , ?

, Ruby, Groovy, , .

+1
3

Ruby . , :

class String
  def omg!
    self.replace "OMG"
  end
end

omg! String. Groovy, , Ruby , .

, :

module Magic
  def presto
    puts "OMG A HAT!"
  end
end

class Array
  include Magic
end

x = "Hello".extend(Magic)
puts x        #=> Hello
x.presto      #=> OMG A HAT!
[].presto     #=> OMG A HAT!

def x.really?
  true
end

x.really?     #=> true

, , .

, , . . , ;) !

+5

, , Ruby ( " " ), class <<whatever. , Yehuda Magic :

x = "Hello"
class <<x
  include Magic
  def magical?
    true
  end
end
x.presto                   #=> OMG A HAT!
x.magical?                 #=> true
"Something else".magical?  #=> NoMethodError
+1

There are no restrictions on class modifications. Once the class has been modified, the modified class will be available for all later requireand subsequent code.

0
source

All Articles