Rails module with Mongoid

I am trying to extend some of my model classes to the "Asset" class. Each of the four types of Assets will be able to generate a slug with set_callback(:save, :before)Therefore, instead of writing four methods that are the same, I would like them to extend the Asset class that would have set_callback (as well as other methods).

At first I tried to simply extend the Asset class, but I ran into problems when, when I saved one of the assets in the database (mongo), the collection into which they were inserted was called Asset, and not their own name.

After I googled around people seem to recommend using modules instead. So I tried this:

module Asset
  field :slug, :type => String

  set_callback(:save, :before) do |document|
    # make document.slug = to whatever
  end
end

class Video
  include Mongoid::Document
  include Asset
  field :video_name, :type => String
  field :description, :type => String
  field :some_more_fields, :type => String
end

But I get some errors when I turn on Asset:

'undefined method `field' for Asset:Module'

Note: I am using Mongoid

+5
2

Asset. , :

  module Asset
    def self.included(base)
      base.send(:field, :slug, :type => String)
    end
  end

:

+7

, :

module Asset
 include extend ActiveSupport::Concern
  included do
   field: slug, type: String
   before_create: :notify_on_create
   scope: my_scope, ->(var) { where(slug: var) }
  end
 end
end

. http://api.rubyonrails.org/classes/ActiveSupport/Concern.html .

+2

All Articles