Sha256: fda53fed7fe9207cc57be5f1daf8d952853e77bb5201428d3c7aaed500c1860e

Contents?: true

Size: 1.52 KB

Versions: 9

Compression:

Stored size: 1.52 KB

Contents

module HasConstant
  module Orm
    module ActiveRecord
      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
            self.class.send(name)[read_attribute(singular).to_i] if read_attribute(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| { :conditions =>
              { constant.to_sym => eval("#{self.to_s}.#{constant.pluralize}.index(value)") } } }
            named_scope "#{singular}_is".to_sym, lambda { |*values| { :conditions =>
              { singular.to_sym => indexes_for(name, values) }
            } }
            named_scope "#{singular}_is_not".to_sym, lambda { |*values| { :conditions =>
              ["#{singular} NOT IN (?)", indexes_for(name, values)]
            } }
          end
        end

      private
        def indexes_for( name, values )
          values.map { |v| self.send(name.to_sym).index(v) }
        end
      end
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
has_constant-0.2.9 lib/has_constant/orm/active_record.rb
has_constant-0.2.8 lib/has_constant/orm/active_record.rb
has_constant-0.2.7 lib/has_constant/orm/active_record.rb
has_constant-0.2.6 lib/has_constant/orm/active_record.rb
has_constant-0.2.5 lib/has_constant/orm/active_record.rb
has_constant-0.2.4 lib/has_constant/orm/active_record.rb
has_constant-0.2.2 lib/has_constant/orm/active_record.rb
has_constant-0.2.1 lib/orm/active_record.rb
has_constant-0.2.0 lib/orm/active_record.rb