I am trying to create a new class to that will inherit from ActiveRecord::Base
the class needs to be dynamically generated from a string
"general_systems".camelize.singularize = Class.new < ActiveRecord::Base
However I keep getting the error:
undefined method `singularize=' for "GeneralSystems":String
I've also tried to constantize
the string
>> foo = "general_systems".camelize.singularize => "GeneralSystem" >> foo.constantize NameError: uninitialized constant GeneralSystem from /var/lib/gems/1.9.1/gems/activesupport-3.0.5/lib/active_support/inflector/methods.rb:124:in `block in constantize' from /var/lib/gems/1.9.1/gems/activesupport-3.0.5/lib/active_support/inflector/methods.rb:123:in `each' from /var/lib/gems/1.9.1/gems/activesupport-3.0.5/lib/active_support/inflector/methods.rb:123:in `constantize' from /var/lib/gems/1.9.1/gems/activesupport-3.0.5/lib/active_support/core_ext/string/inflections.rb:43:in `constantize' from (irb):4 from /usr/bin/irb:12:in `<main>' >> foo.constantize = Class.new NoMethodError: undefined method `constantize=' for "GeneralSystem":String from (irb):5 from /usr/bin/irb:12:in `<main>'
Any help would be greatly appreciated.
Use #is_a? to Determine the Instance's Class Name in Ruby If the object given is an instance of a class , it returns true ; otherwise, it returns false . #is_a also returns true if the object is an instance of any subclasses.
The is_a? method will return a true value if an object is a of the type given as a parameter OR if it inherits from the type given as a parameter. So in effect, you can use it to ask "is there going to be a method from a class which I can run on this object".
First, you don't declare the type in Ruby, so you don't need the first string . To replace a word in string, you do: sentence. gsub(/match/, "replacement") .
The proper way to determine the "type" of an object, which is a wobbly term in the Ruby world, is to call object. class . Since classes can inherit from other classes, if you want to determine if an object is "of a particular type" you might call object.
If you're using Rails, it provides a method called #constantize
that will work:
irb(main):017:0> Object.const_get 'House::Owns' NameError: wrong constant name House::Owns 'House::Owns'.constantize => House::Owns
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With