Search code examples
ruby-on-railsactiverecordextending

Extend ActiveRecord method_missing


I've been looking around the web and have found a great deal of information on attempting what I am, however one bit of sugar I'd like to add to my Ruby/Rails mixin, is creating a function that looks for a pattern. I want to create a base function called

is_a_*

where * can be anything. Whatever that * is, needs to be retrievable so I can use it inside the function and act accordingly. Do I have to use method_missing?


Solution

  • This is what method_missing was made for, e.g. something like this should work:

    module MyMixin
    
      def respond_to?(method, priv=false)
        (method.to_s =~ /^is_a_(\w+)$/) || super
      end
    
      def method_missing(sym, *args)
        if sym.to_s =~ /^is_a_(\w+)$/
          pattern = $1
          # then just do something with pattern here, e.g.:
          puts pattern
        else
          super
        end
      end
    
    end
    

    Then just include MyMixin in your class, e.g.:

    class A
      include MyMixin
    end
    
    a = A.new
    a.is_a_foo
    #=> "foo"
    

    p.s. you don't strictly need to override respond_to?, I just included it for completeness:

    a.respond_to?("is_a_foo")
    #=> true
    a.respond_to?("is_a_bar")
    #=> true
    a.respond_to?("is__a_foo")
    #=> false