Reputation: 1569
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
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
Reputation: 24815
Two ways to drier your code.
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
# 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