ruby on rails 3 - Move model method to helper -


i have 3 models same method. stay dry i'd move these helper method not sure how make global still receive model.

currently have format_slug in 3 models.

class page < activerecord::base   before_save :format_slug    def format_slug     slug.parameterize.downcase   end end 

how move format_slug application_helper , 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 

you wouldn't want use helper, use module. helpers used in views, , happening exclusively in model.

this candidate concern, can find more here https://gist.github.com/dhh/1014971

(this in lib/sluggable.rb or app/models/concerns/sluggable.rb) latter standard in rails 4, sure adjust load paths.

module sluggable   extend activesupport::concern    included     before_save :format_slug   end    def format_slug     slug.parameterize.downcase   end end 

then in models want use it:

class page < activerecord::base   include sluggable end 

Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -