I'm trying to include a module only when a condition is met.
module PremiumServer
def is_premium
开发者_如何学Ctrue
end
end
class Server
include Mongoid::Document
include PremiumServer if self.premium
field :premium, :type => Boolean, :default => false
end
This isn't working, and I can't figure out why. Can someone please tell me how I'm supposed to include modules based upon a condition being met, like above?
Thanks!
EDIT:
I found the answer to my problem here: Mongoid and carrierwave
However, I'm awarding the question to the top answer as it is probably the more useful way.
includes happen on the class level. Your premium attribute is at instance level.
There are ways to do the include on per instance level, but I would not recommend them.
Here you are better of using inheritance
class Server; .. ; end
class PremiumServer < Server; ..; end
Or, in your case, if the only method is is_premium
add it to the Server class and have it return the premium variable
def is_premium
self.premium
end
oh, and you should use "question" method in ruby... Although Mongoid provides these for boolean values.
def premium?
self.premium
end
Use class inheritance and the scope mechanism of Mongoid:
class Server
include Mongoid::Document
field :premium, type: Boolean, default: false
# ... basic server methods
end
class PremiumServer < Server
default_scope :premium_servers, where(premium: true)
# ... additional premium server methods
end
p_server = PremiumServer.first
p_server.<access to PremiumServer methods>
The default_scope
will be used every time you do a query on PremiumServer
, you do not need to call .premium_servers
manually.
That is "conditional based" in another way - in a mongoid way.
Further information:
- Scopes: http://mongoid.org/docs/querying/scopes.html
- Inheritance: http://mongoid.org/docs/documents/inheritance.html
精彩评论