A
A
Alexander Grishin2016-12-25 17:36:49
Ruby on Rails
Alexander Grishin, 2016-12-25 17:36:49

How to make a method public in Ruby?

There is a code:

# encoding: UTF-8
module SharedMethods
  def meth1
    puts 'meth1'
  end
  def meth2
    puts 'meth2'
  end
end

class SlaveClass
  def blabla
    meth2
  end
end

module MasterModule
  
  def do_some
    SlaveClass.new().blabla
  end
end

How to make methods meth1 and meth2 available everywhere?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey Demidenko, 2016-12-27
@beerdy

If you want methods to be available everywhere, you will have to extend Object, I would do it through refinements , use using only in those places where you need these methods
Example:

module SuperString
  refine Object do
    def ii
      puts "ii"
    end
  end
end

using SuperString
5.ii
"r".ii
ii

A
Artur Bordenyuk, 2016-12-25
@HighQuality

In order for the `SharedMethods` module to be available in the `SlaveClass`, it must be included.

class SlaveClass
  include SharedMethods
  def blabla
    meth2
  end
end

Now, to call a module method, you can do the following:
module MasterModule
  def self.do_some
    SlaveClass.new.blabla
  end
end

And call the module method
------ UPD
Bit of bad code. This also works, but I would not use it in combat solutions :)
module SharedMethods
  def meth1
    puts 'meth1'
  end
  def meth2
    puts 'meth2'
  end
end

class Object
  include SharedMethods
end

#

class SlaveClass
  def blabla
    meth2
    meth1
  end
end

module MasterModule
  def self.do_some
    SlaveClass.new.blabla
  end
end

MasterModule.do_some

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question