Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create dynamic variables in rails function?

I have this code that's working:

  case index
   when "Books"
     @reading_img = res.items.first.get_hash('MediumImage')["URL"] # don't show an image
     @reading_link = create_amz_url(search, asin)        

     tempy = @nowreading.content.match(/#nowreading.*/).to_s.gsub("#nowreading",'') # strips away the #nowreading tag
     @nowreading.content = tempy.match(/#{search}.*/).to_s.gsub("#{search}", @reading_link) 
     # replaces the book title (passed in as variable 'search') with the URL'ed title

   when "Music"
     @listening_img = res.items.first.get_hash('MediumImage')["URL"] # don't show an image
     @listening_link = create_amz_url(search, asin)        

     tempy = @nowlistening.content.match(/#nowlistening.*/).to_s.gsub("#nowlistening",'') # strips away the #nowreading tag
     @nowlistening.content = tempy.match(/#{search}.*/).to_s.gsub("#{search}", @listening_link) 
     # replaces the song title (passed in as variable 'search') with the URL'ed title       

   end

I need to repeat this for many, many categories. I tried something like this to DRY the code but it didn't work:

     def get_img_and_links(act, res, search, asin)
        '@'+act+'ing_img' = res.items.first.get_hash('MediumImage')["URL"] # don't show an image
        '@'+act+'ing_link' = create_amz_url(search, asin)        

        tempy = '@now'+act+'ing'.content.match(/#now"#{act}"ing.*/).to_s.gsub("#now#{act}ing",'') # strips away the #nowreading tag
        '@now'+act+'ing'.content = tempy.match(/#{search}.*/).to_s.gsub("#{search}", '@'+act+'ing_link') 
        # replaces the book title (passed in as variable 'search') with the URL'ed title
     end

Essentially, I was trying to create a function that took an "act" (e.g., "read", "listen", etc) and have the variables within that function be dynamic. Can this be accomplished? If so, how?

like image 487
MorningHacker Avatar asked Jan 29 '26 04:01

MorningHacker


1 Answers

Look up instance_variable_set here: http://ruby-doc.org/core/classes/Object.html. It's what you need to dynamically create these variables.

instance_variable_set "@#{act}ing_img".to_sym, res.items.first.get_hash('MediumImage')["URL"]

And so on...

like image 59
Steve Ross Avatar answered Jan 31 '26 18:01

Steve Ross