Search code examples
ruby-on-railsruby-on-rails-pluginsvirtual-attribute

Virtual attributes in plugin


I need some help with virtual attributes. This code works fine but how do I use it inside a plugin. The goal is to add this methods to all classes that uses the plugin.

class Article < ActiveRecord::Base

  attr_accessor :title, :permalink

  def title
    if @title 
      @title
    elsif self.page
      self.page.title
    else 
      ""
    end
  end

  def permalink
    if @permalink
      @permalink
    elsif self.page
      self.page.permalink
    else
      ""
    end
  end
end

Thanks


Solution

  • You can run the plugin generator to get started.

    script/generate plugin acts_as_page
    

    You can then add a module which defines acts_as_page and extends it into all models.

    # in plugins/acts_as_page/lib/acts_as_page.rb
    module ActsAsPage
      def acts_as_page
        # ...
      end
    end
    
    # in plugins/acts_as_page/init.rb
    class ActiveRecord::Base
      extend ActsAsPage
    end
    

    This way the acts_as_page method is available as a class method to all models and you can define any behavior into there. You could do something like this...

    module ActsAsPage
      def acts_as_page
        attr_writer :title, :permalink
        include Behavior
      end
    
      module Behavior
        def title
          # ...
        end
    
        def permalink
          # ...
        end
      end
    end
    

    And then when you call acts_as_page in the model...

    class Article < ActiveRecord::Base
      acts_as_page
    end
    

    It will define the attributes and add the methods. If you need things to be a bit more dynamic (such as if you want the acts_as_page method to take arguments which changes the behavior) try out the solution I present in this Railscasts episode.