List of attributes from class and include module

I have a class (ActorClue) that has three attr_accessors defined inside it. There are a few other common fields that other classes need, so I put those common fields in the (BaseClueProperties) module. I am including this module in the ActorClue class.

Here's a sample of the code:

module BaseClueProperties  
  attr_accessor :image_url
  attr_accessor :summary_text  
end

################
class BaseClue

  # http://stackoverflow.com/questions/2487333/fastest-one-liner-way-to-list-attr-accessors in-ruby    
  def self.attr_accessor(*vars)
    @attributes ||= []

    @attributes.concat vars

    super(*vars)
  end

  def self.attributes
    @attributes
  end

  def attributes
    self.class.attributes
  end

end

###############

class ActorClue < BaseClue

  attr_accessor :actor_name
  attr_accessor :movie_name
  attr_accessor :directed_by

  include BaseClueProperties

  .....
end

      

I create an instance above:

>> gg = ActorClue.new
=> #<ActorClue:0x23bf784>
>> gg.attributes
=> [:actor_name, :movie_name, :directed_by] 

      

Why does it only return: actor_name,: movie_name and: direct_by and doesn't include: image_url and: summary_text?

I changed BaseClueProperties to read the following:

module BaseClueProperties  
  BaseClue.attr_accessor :image_url
  BaseClue.attr_accessor :summary_text  
end

      

But still with the same result.

Any thoughts on why my: image_url and: summary_text attributes are not being added to my @attributes collection?

+2


a source to share


1 answer


I cannot promise that my description of the reason is correct, but the following code should fix this problem. I believe you are adding the attributes of the module not to the class it is included in. Anyway, replacing your module with the next one should fix the problem.

module BaseClueProperties

  def self.included(base)
    base.send :attr_accessor, :image_url
    base.send :attr_accessor, :summary_text
  end

end 

      



This should cause the included object to define the processor_attribute when it includes a module.

+5


a source







All Articles