2013-05-18 16 views
1

我建立一個小的腳本,我需要實現一個Mongoid文檔類一樣,在這裏我include我的基本模塊,然後我可以建立一個類,它看起來像:如何實現像類一樣的Mongoid文檔?

class MyClass 
    include MyBaseModule 
    field :some_field, :attr => 'attributes' 
end 

這是我最後一次嘗試:

module Model 

    def initialize(keys = {})  
     puts @@keys 
    end 

    def method_missing sym, *args 
     if sym =~ /^(\w+)=$/ 
     if @@keys.has_key?($1) 
      @@keys[$1.to_sym] = args[0] 
     else 
      nil 
     end 
     else 
     if @@keys.has_key?($1) 
      @@keys[sym.to_sym] 
     else 
      nil 
     end 

     end 
    end 

    def inspect 
     puts "#<#{self.class} @keys=#{@@keys.each {|k,v| "#{k} => #{v}"}}>" 
    end 

    def self.included(base) 
     base.extend(ClassMethods) 
    end 

    def save 
     @@keys.each do |k, v| 
     SimpleMongo::connection.collection.insert({k => v}) 
     end 
    end 

    module ClassMethods 
     def field(name, args) 
     if @@keys.nil? 
      @@keys = {} 
     end 
     @@keys[name.to_sym] = default_value 
     end 

    end 

    end 

Mongoid文件看起來像這樣:

class StoredFile 
    include Mongoid::Document 
    field :name, type: String 
    field :description, type: String 
    field :password, type: String 
    field :public, type: Boolean 
    field :shortlink, type: String 
    mount_uploader :stored_file, StoredFileUploader 
    before_save :gen_shortlink 
    before_save :hash_password 

    belongs_to :user 

    def gen_shortlink 
     self.shortlink = rand(36**10).to_s(36) 
    end 

    def public? 
     self.public 
    end 

    def hash_password 
     require 'bcrypt' 
     self.password = BCrypt::Password.create(self.password).to_s 
    end 

    def check_pass(password) 
     BCrypt::Password.new(self.password) == password 
    end 

    end 

它不工作,因爲裏面的變量在該模塊外部不可用。什麼是最簡單的方法來實現呢?謝謝!

回答

1

實現它的最簡單方法是創建一個類變量getter。

module Model 
    def self.included(base) 
    base.extend(ClassMethods) 
    end 

    module ClassMethods 
    def keys 
     @keys ||= {} 
    end 

    def field(name, opts) 
     @keys ||= {} 
     @keys[name] = opts 
    end 
    end 

    def initialize(attributes) 
    # stuff 
    puts self.class.keys 
    end 
end 
相關問題