1

I see a lot of stuff

include ActiveRecord::XXXX::InstanceMethods extend ActiveRecord::XXXX::SingletonMethods 

I am unaware of the property or there working, just wanted a easy to understand answer. if it has a good reason to be used.

2 Answers 2

7

It's a not-written convention usually adopted when you want to encapsulate features/extensions in a Ruby module intended to be used as a Mixin.

module Bar def beta puts "I'm beta" end end class Foo include Bar def alpha puts "I'm alpha" end end Foo.new.beta # => "I'm beta" 

Sometimes the Mixin is a simple as providing some instance methods, sometimes else you need to extend the original class with both instance and class methods. The following syntax in Ruby is invalid.

module Bar def beta puts "I'm beta" end def self.class_beta puts "I'm class-beta" end end class Foo include Bar def alpha puts "I'm alpha" end end Foo.new.beta # => "I'm beta" Foo.class_beta # => invalid 

That said, you can't include a module with method defined with self.

For this reason, it's a common pratice to split the module in two submodules and use the self.included hook.

module Bar def self.included(base) base.extend ClassMethod base.send :include, InstanceMethods end module ClassMethods def class_beta puts "I'm class-beta" end end module InstanceMethods def beta puts "I'm beta" end end end class Foo include Bar def alpha puts "I'm alpha" end end Foo.new.beta # => "I'm beta" Foo.class_beta # => "I'm class beta" 

Also, check out this great article written by Yehuda Katz.

Sign up to request clarification or add additional context in comments.

2 Comments

It's much more common not to have an InstanceMethods module, but to instead just include those methods in the Bar module body. What does Rails gain by having an InstanceMethods module?
Ken Bloom: Clarity? I used to do this myself when I was unfamiliar with the idiom
2

Instance methods are methods you define within a class that are sent to INSTANCES of that class. Singletom or class methods are methods defined within a class that are sent to the CLASS object. As a simple example:

Class A def instance_method puts "Hi, I'm an instance method" end def self.singleton_method puts "Hi, I'm a singleton method" end end 

you call them like this:

singleton: A.singleton_method instance_method: a = A.new a.instance_method 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.