global methods in ruby on rails models

前端 未结 3 1013
孤城傲影
孤城傲影 2021-02-04 18:33

I have methods in all of my models that look like this:

def formatted_start_date
  start_date ? start_date.to_s(:date) : nil
end

I would like

3条回答
  •  春和景丽
    2021-02-04 19:17

    It looks more like something for a helper to me. Try this in the your application help:

    def formatted_date(date)
       date ? date.to_s(:date) : nil
    end
    

    Formatting isn't something that really belongs in the model (for precisely the reason you've discovered... putting such common code in every model is annoying)

    If you really want to do as you say though, then what you could do is monkeypatch the ActiveRecord superclass and add the function you want into there. It would then be available for all your models. Beware that monkeypatching can lead to unpredictable and undefined behaviour and use at your own risk! It's also pretty hacky :)

    class ActiveRecord::Base
       def formatted_start_date
          start_date ? start_date.to_s(:date) : nil
       end
    end
    

    Just stick that somewhere that will be run before anything else in your app will be, and it will dynamically add the method to the base class of your models, making it available for use.

    Or you could create a mixin for all your models, but that seems a bit overkill for a single method.

提交回复
热议问题