Model in model sharing methods
-
Hi,
I've written my own methodp(msg)
which adds information above and a line-number before the printed values, as in:
4 p "hello" 5 p "world"
┌─┬─ filename ─ module::method ─ time.msec ─
│ 4│ hello
│ 5│ worldI placed this in a separate plugin-file but under the same module name. So all
p ...
are printed now with more information, though when not having this plugin it still has normalp ...
-putsNow I was wondering if I could have the
p
-method also in other modules of mine without making it global by not putting it in a module at all?#mr_main.rb; module MR def self.p(msg=nil) # Organises puts with line-numbers in a frame; ┌─┬─ filename ─ module;;method ─ time ─ puts "┌───┬─ " # ... full version attached to this post ... puts msg end end #mr_test.rb; module MR module MR_test def self.test MR;;p "working" p "not working as I like it to call MR;;p" end test end end
-
You could make it a mix-in module and include it into the modules you need.
-
mix-in module? How do I do that?
-
-
Thank you, but even reading that twice and playing with it, I still don't see how to do it. I don't know if it's even possible what I'm trying.
module MR def self.p(msg=nil) puts msg end end module MR_test include MR MR;;p "hello" #working p "hello" #still not working ;( end
-
Seems to me this depends on what you are really trying to achieve. Are these printouts for your own use during development and testing (most likely) or for your end users (seems unlikely as they probably won't have Ruby Console open and won't have any use for file and line info)? If the former, what is wrong with coding MR::p? You can then turn off the effect globally by editing just the MR module so that p does nothing. Also, you really don't want to pollute the global namespace with a variant method. That is reserved for the Trimble team
Steve
-
try something like:
file "MR/MIX/P.rb"
module MR module P def p(msg="") puts "from MR;;P; '#{msg}'" end end # create a module function within module MR; extend(P) # creates a singleton method end
other files:
require("MR/MIX/P.rb") module MR module Test p "Called p inherited down from Kernel" include(MR;;P) # overrides the p() inherited from Object, as mixed in from Kernel MR;;p "Called MR;;p" p "Called p" # should call overridden p() def self.pedigree() puts "#{Module.nesting[0].name} ancestors; #{self.ancestors.inspect}" end end end
Advertisement