Harsha M V
Harsha M V

Reputation: 54949

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?

Upvotes: 0

Views: 121

Answers (2)

Marcus
Marcus

Reputation: 12586

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 

Upvotes: 1

miushock
miushock

Reputation: 1097

All models are Inherited from ActiveRecord, you can open the eigenclass to add a singleton method there and use in all models.

The method I'll choose would be putting it under lib directory and require it in each model I need it.

Upvotes: 2

Related Questions