Override a Mongoid model's setters and getters

后端 未结 3 776
时光说笑
时光说笑 2021-02-05 18:17

Is there a way to override a setter or getter for a model in Mongoid? Something like:

class Project
  include Mongoid::Document
  field :name, :type => Strin         


        
相关标签:
3条回答
  • 2021-02-05 18:50
    def name=(projectname)
      self[:name] = projectname.capitalize
    end
    
    0 讨论(0)
  • 2021-02-05 18:52

    I had a similar issue with needing to override the "user" setter for a belongs_to :user relationship. I came up with this solution for not only this case but for wrapping any method already defined within the same class.

    class Class  
      def wrap_method(name, &block)
        existing = self.instance_method(name)
    
        define_method name do |*args|
          instance_exec(*args, existing ? existing.bind(self) : nil, &block)
        end
    end
    

    This allows you to do the following in your model class:

    wrap_method :user= do |value, wrapped|
        wrapped.call(value)
        #additional logic here
    end
    
    0 讨论(0)
  • 2021-02-05 18:57

    better use

    def name=(projectname)
      super(projectname.capitalize)
    end
    

    the method

    self[:name] = projectname.capitalize
    

    can be dangerous, cause overloading with it can cause endless recursion

    0 讨论(0)
提交回复
热议问题