#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2009
    Posts
    1
    Rep Power
    0

    Trying module mixin in ruby class


    Hi, I'm still a ruby noob, trying to do mixin
    I want to extend a module method in a class...
    Here's the sample:
    This code below is error apparently
    Code:
    module Mod_A
        def foo
            puts "xxx"
        end
    end
    
    class Class_1
        include Mod_A
        def foo
            super
            puts "meow"
         end
    end
    
    temp = Class_1.new
    temp.foo
    This is the best solution I can think of

    Code:
    module Mod_A
        def Mod_A.foo
            puts "xxx"
        end
    end
    
    class Class_1
        include Mod_A
        def foo
            Mod_A.foo
            puts "meow"
         end
    end
    
    temp = Class_1.new
    temp.foo
    Is there any better solution ?
    Thanks
  2. #2
  3. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2011
    Posts
    5
    Rep Power
    0
    You should look up aliasing in Ruby.

    http://ruby.about.com/od/rubyfeatures/a/aliasing.html
    (I'm not allowed to post URLs :/ Too new to the site)

    Useful for what you're trying to achieve. So your code would be something like this:
    Code:
    module Foo
        def bar
            puts "one"
        end
    end
    
    class Class_Name
        include Foo
        alias old_bar bar
        def bar
            old_bar
            puts "two"
        end
    end
    
    Class_Name.new.foo
    This will return
    => "one"
    => "two"

IMN logo majestic logo threadwatch logo seochat tools logo