olimart
olimart

Reputation: 1569

Move model method to helper

I have 3 models with the same method. To stay DRY I'd like to move these to helper method but not sure how to make it global but still receive from model.

Currently I have format_slug in 3 models.

class Page < ActiveRecord::Base
  before_save :format_slug

  def format_slug
    slug.parameterize.downcase
  end
end

How to move format_slug to application_helper and call method through before filter in model?

module ApplicationHelper
  def format_slug(model)
    model.slug.parameterize.downcase
  end
end

class Page < ActiveRecord::Base
  before_save :format_slug
end

Upvotes: 1

Views: 674

Answers (2)

Shawn Balestracci
Shawn Balestracci

Reputation: 7530

You wouldn't want to use a helper, but you could use another module. Helpers are used in the views, and this is something that is happening exclusively in your model.

This is a good candidate for a concern, you can find more about that here https://gist.github.com/dhh/1014971

(This could be in lib/sluggable.rb or app/models/concerns/sluggable.rb) The latter will be standard in Rails 4, but be sure to adjust your load paths.

module Sluggable
  extend ActiveSupport::Concern

  included do
    before_save :format_slug
  end

  def format_slug
    slug.parameterize.downcase
  end
end

Then in your models where you want to use it:

class Page < ActiveRecord::Base
  include Sluggable
end

Upvotes: 2

Billy Chan
Billy Chan

Reputation: 24815

Two ways to drier your code.

Method 1: Using helper

module ApplicationHelper
  def format_slug(str)
    str.parameterize.downcase
  end
end

class Page < ActiveRecord::Base
   before_save :handle_slug

   def handle_slug
     format_slug self.slug
   end
 end

Method 2: Extend ActiveRecord

# lib/my_ar_extension.rb
module MyArExtension
  def format_slug
    self.slug.parameterize.downcase if self.slug
  end
end

ActiveRecord::base.send :include, MyArExtension

# Page model
class Page < ActiveRecord::Base
  attr_accessible :slug # and others
  before_filter :format_slug
  # other code
end

Upvotes: 1

Related Questions