2

I want to make class extensions available to other modules/classes/files. For example:

module UsefulStuff
  class Object
    def blank?
      respond_to?(:empty?) ? empty? : !self
    end
  end
end

in other class/module/file:

if string.blank? ...

What and how do I include/load/require/... to make this work?

3
  • 2
    Do you want to add that blank? method to all objects? Commented Sep 1, 2012 at 8:11
  • In the case of blank?, yes, it should work for all classes that have an empty? method (String, Array, Hash). However, more generally, my question is, when I extend a Class how do I include it in other files so that objects in those other files will see the extension? Could you provide an example where the class extension is in one file, and the use of it is in another file (which might be a module, a class, or just a script with main code). Commented Sep 1, 2012 at 13:21
  • See Nucc's answer, it is what you want. Commented Sep 1, 2012 at 18:27

1 Answer 1

4

You should use a module instead of a class:

module UsefulStuff
  module Blank
    def blank?
      respond_to?(:empty?) ? empty? : !self
    end
  end
end

and you can include it in String class:

class String
  include UsefulStuff::Blank
end

or if you want it to be global for objects:

class Object
  include UsefulStuff::Blank
end
Sign up to request clarification or add additional context in comments.

Comments

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.