Class method vs constant in Ruby/Rails

前端 未结 4 814
野性不改
野性不改 2020-12-13 12:51

I was implementing a form that includes a hard-coded dropdown for a collection and I was wondering what would be the best solution, I know both ways exposed below work, stil

4条回答
  •  情书的邮戳
    2020-12-13 13:38

    What I usually do is have a mix of above-mentioned techniques:

    class Player
      JURISDICTIONS = %i(de uk ru)
    
      def self.jurisdictions
        JURISDICTIONS
      end
    end
    

    It has few advantages:

    • It provides a clean interface, encapsulating a constant (you call Player.jurisdictions instead of Player::JURISDICTIONS).
    • Additional logic can be added later just by altering method.
    • The method can be stubbed in tests.

    IMHO, performance does not matter here.

    Update: Constant can bee hidden using private_constant method (http://ruby-doc.org/core-2.3.0/Module.html#method-i-private_constant)

提交回复
热议问题