List dynamic attributes in a Mongoid Model

后端 未结 6 1375
醉酒成梦
醉酒成梦 2021-02-06 15:49

I have gone over the documentation, and I can\'t find a specific way to go about this. I have already added some dynamic attributes to a model, and I would like to be able to it

6条回答
  •  爱一瞬间的悲伤
    2021-02-06 16:23

    Just include something like this in your model:

    module DynamicAttributeSupport
    
      def self.included(base)
        base.send :include, InstanceMethods
      end
    
      module InstanceMethods
        def dynamic_attributes
          attributes.keys - _protected_attributes[:default].to_a - fields.keys
        end
    
        def static_attributes
          fields.keys - dynamic_attributes
        end
      end
    
    end
    

    and here is a spec to go with it:

    require 'spec_helper'
    
    describe "dynamic attributes" do
    
      class DynamicAttributeModel
        include Mongoid::Document
        include DynamicAttributeSupport
        field :defined_field, type: String
      end
    
      it "provides dynamic_attribute helper" do
        d = DynamicAttributeModel.new(age: 45, defined_field: 'George')
        d.dynamic_attributes.should == ['age']
      end
    
      it "has static attributes" do
        d = DynamicAttributeModel.new(foo: 'bar')
        d.static_attributes.should include('defined_field')
        d.static_attributes.should_not include('foo')
      end
    
      it "allows creation with dynamic attributes" do
        d = DynamicAttributeModel.create(age: 99, blood_type: 'A')
        d = DynamicAttributeModel.find(d.id)
        d.age.should == 99
        d.blood_type.should == 'A'
        d.dynamic_attributes.should == ['age', 'blood_type']
      end
    end
    

提交回复
热议问题