ActiveSupport::Concern small question

18 views
Skip to first unread message

rusik

unread,
Oct 10, 2014, 9:08:29 AM10/10/14
to rubyonra...@googlegroups.com
 Hello all.

 In this example, as i understand that included block is running when Exclaimable module is included in Person and after a Person class methods are 'initialized'
 
require 'active_support/concern'
 
module Exclaimable
  extend ActiveSupport::Concern
  included do
    self.new.hello
  end
end
 
class Person
  include Exclaimable
  def hello
    puts 'person hello'
  end
end

Output: Exception: NoMethodError: undefined method `hello' for #<Person:0x00000103cbdcd0>

But  i see that, Person class doesn't have hello method, why ? Please, help !

So, i can't understand - what diifference between
 
included do 
 self.new.hello
end
  
and class method:
 
self.included(base)
 base.new.hello
end

Both code get same error ( see above )

Matt Jones

unread,
Oct 12, 2014, 4:42:11 PM10/12/14
to rubyonra...@googlegroups.com


On Friday, 10 October 2014 09:08:29 UTC-4, rusik wrote:
 Hello all.

 In this example, as i understand that included block is running when Exclaimable module is included in Person and after a Person class methods are 'initialized'

No. See below for additional information, but if `include Exclaimable` is the first thing in a class definition, only methods defined on the declaring class's superclass (Object, in the case of Person) will be available.
 
 
require 'active_support/concern'
 
module Exclaimable
  extend ActiveSupport::Concern
  included do
    self.new.hello
  end
end
 
class Person
  include Exclaimable
  def hello
    puts 'person hello'
  end
end

Output: Exception: NoMethodError: undefined method `hello' for #<Person:0x00000103cbdcd0>

But  i see that, Person class doesn't have hello method, why ? Please, help !

The stuff between `class Person` and `end` is just code. The `hello` method isn't available yet because it hasn't been DEFINED yet when `include Exclaimable` executes.

 
So, i can't understand - what diifference between
 
included do 
 self.new.hello
end
  
and class method:
 
self.included(base)
 base.new.hello
end

Both code get same error ( see above )

`self.included` is Ruby's built-in hook. ( http://www.ruby-doc.org/core-2.1.3/Module.html#method-i-included ) It gets called when the module that declares it is included in another module or class.

`ActiveSupport::Concern` adds the `included do` idiom, to make situations where one module depends on another more straightforward. See the last section of the docs for more:


--Matt Jones
Reply all
Reply to author
Forward
0 new messages