Sha256: 56f267b206ddca70b2697fc09a1a0945d42ad32bc704eefa1aa485bd8ac71e95

Contents?: true

Size: 1.44 KB

Versions: 3

Compression:

Stored size: 1.44 KB

Contents

module HasConstant
  module Orm
    module Mongoid
      def self.included( base )
        base.extend(ClassMethods)
      end

      module ClassMethods
        def has_constant( name, values, options = {} )
          super(name, values, options)

          singular = (options[:accessor] || name.to_s.singularize).to_s

          # Add the getter method. This returns the string representation of the stored value
          define_method(singular) do
            eval("#{self.class}.#{name.to_s}[self.attributes[singular].to_i] if self.attributes[singular]")
          end

          define_method("#{singular}=") do |val|
            if val.instance_of?(String)
              write_attribute singular.to_sym, self.class.send(name.to_s).index(val)
            else
              write_attribute singular.to_sym, val
            end
          end

          class_eval do
            named_scope :by_constant, lambda { |constant,value| { :where =>
              { constant.to_sym => eval("#{self.to_s}.#{constant.pluralize}.index(value)") } } }
            named_scope "#{singular}_is".to_sym, lambda { |*values| { :where =>
              { singular.to_sym => { '$in' =>  values.map { |v| self.send(name.to_sym).index(v) } } } } }
            named_scope "#{singular}_is_not".to_sym, lambda { |*values| { :where =>
              { singular.to_sym => { '$nin' => values.map { |v| self.send(name.to_sym).index(v) } } } } }
          end
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
has_constant-0.2.2 lib/has_constant/orm/mongoid.rb
has_constant-0.2.1 lib/orm/mongoid.rb
has_constant-0.2.0 lib/orm/mongoid.rb