views:

110

answers:

2

I have a module like this:

module Controller
  module LocaleModels
    def self.included(base)
      base.send :include, InstanceMethods
    end

    module InstanceMethods
      def locale_Lexeme; constantize_model('Lexeme') end
      def locale_Synthetic; constantize_model('Synthetic') end
      def locale_Property; constantize_model('Property') end

      private
      def constantize_model(common_part)
        eval(I18n.locale.capitalize + '::' + common_part).constantize
      end
    end
  end
end

But I kept getting

NoMethodError (undefined method `constantize' for #<Class:0x2483b0c>)

I guess I cannot use 'constantize' in a custom module.

But can you please offer some workaround?

A: 

Check if the eval call returns a String object. If it does check if it is in camelcase. Try using camelize if it is not in camelcase.

Waseem
+2  A: 

The constantize method converts a string into a constant (such as a class or module). However, the eval call is already returning a class, not a string, so in a sense it is already accomplishing what constantize would do.

I recommend removing the eval call since constantize is much safer to use.

def constantize_model(common_part)
  (I18n.locale.capitalize + '::' + common_part).constantize
end

This way you're calling constantize on a string as intended.

ryanb
Thank you ryanb.I just got a reply from rails:talk indicating my error here, same as you said.Actually, the 'eval' is a typo of mine, sorry for that.But I did not think the famous author of 'railscast' actually gave me answer. I'm a big fun of Railscast. Thank you very much.
boblu