Module: Mongokit::ModelHelpers::ClassMethods
- Defined in:
- lib/mongokit/model_helpers.rb
Overview
Example
class Game
include Mongoid::Document
mongokit :model_helpers
field :format, type: String
field :category, type: Integer
multi_fields :city, { venue: 'Mumbai' }, :country # Default string type
multi_fields :start_time, :end_time, DateTime
field_with_validation(:team_type, inclusion: { in: %w(t20 odi test) })
boolean_methods(:format, %w(t20 odi test), { postfix: 'match' } )
end
game = Game.new(format: 't20')
game.t20_match? # true
game.odi_match? # false
Instance Method Summary collapse
- #boolean_methods(field_name, values, options = {}) ⇒ Object
- #field_with_validation(field_name, options = {}) ⇒ Object
- #multi_fields(*args) ⇒ Object
Instance Method Details
#boolean_methods(field_name, values, options = {}) ⇒ Object
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
# File 'lib/mongokit/model_helpers.rb', line 29 def boolean_methods(field_name, values, = {}) values = values.zip(values).to_h if values.is_a?(Array) values.each do |f, v| method_name = [ [:prefix], f, [:postfix], ].compact.join('_') define_method "#{method_name}?" do v == self[field_name] end end end |
#field_with_validation(field_name, options = {}) ⇒ Object
63 64 65 66 67 68 69 70 71 72 |
# File 'lib/mongokit/model_helpers.rb', line 63 def field_with_validation(field_name, = {}) field field_name, { type: .delete(:type) || String, default: .delete(:default) } if .any? validates field_name, end end |
#multi_fields(*args) ⇒ Object
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
# File 'lib/mongokit/model_helpers.rb', line 45 def multi_fields(*args) type = args.pop fields = args unless type.is_a?(Class) fields << type type = String end fields.each do |f| if f.is_a?(Hash) f, default_value = f.flatten end field f, type: type, default: default_value end end |