Search code examples
ruby-on-railsruby-on-rails-4modelsmongoid3

Rails4 Application Model


i have the following function that i make use of in a lot of my models. i use MongoID for MongoDB wrapper

def make_slug
  self.slug = self.name.downcase.gsub(/[^a-z1-9]+/, '').chomp('')
end

Which is the best place to place it than copy and paste it in all my models.

Also any recommendation for a good Slug Gem for Rails4?


Solution

  • I guess you could do a mixin/module, which you include in your models where you need the functionality. Like this:

    Example of the module:

    module SlugMaker
      def make_slug
        # Do your magic here
      end
    end
    

    And then include it in your model:

    class SuperAwesomeModel
      include SlugMaker
    
      def some_action
         make_slug
      end
    end