0

I have a model source (name, url, method) The program parses the source's url for data. Now I have differen classes for parsing different types of urls: rss, xml, ogdata ...

So I have a common interface

new(url) //Parses the url

getTitle() //Get the title of the data

getPrice() //Get the price

And I have four classes rss, xml, ogdata. These classes are in seperate files. The idea is to add more classes as I discover different types of pages. I want to initiate the right classes for the url.

method=source.method //NOw I want to create a new class of the name specified in method

parser=Rss.new(source.url)//Instead of this //Something like parser=.new(source.url)

SoWhat
  • 5,564
  • 2
  • 28
  • 59
  • Give this a try: http://stackoverflow.com/questions/5302187/ruby-string-to-class-name – vee Dec 26 '13 at 07:11

2 Answers2

0

You can try using const_get.

Ex:-

Kernel.const_get("YourClassNameHere").new

*Kernel.const_get("YourClassNameHere")* will get you the class. And you can use it to instantiate new instances of the class.

thekindofme
  • 3,846
  • 26
  • 29
0
irb(main):081:0> User.name
=> "User"

then

"User".constantize.new(name: 'David')

or

User.name..constantize.new(name: 'David')
Jin Lim
  • 1,759
  • 20
  • 24