Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override a Mongoid model's setters and getters

Tags:

ruby

mongoid

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 => String
  field :num_users, type: Integer, default: 0
  key :name
  has_and_belongs_to_many :users, class_name: "User", inverse_of: :projects

  # This will not work
  def name=(projectname)
    @name = projectname.capitalize
  end
end

where the name method can be overwritten without using virtual fields?

like image 315
GTDev Avatar asked Sep 05 '11 09:09

GTDev


2 Answers

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

like image 140
sandrew Avatar answered Sep 21 '22 14:09

sandrew


def name=(projectname)
  self[:name] = projectname.capitalize
end
like image 45
rubish Avatar answered Sep 21 '22 14:09

rubish