如何在rails函数中创建动态变量?

时间:2011-07-14 05:41:11

标签: ruby-on-rails ruby dynamic

我有这个代码正在运行:

  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

我需要为很多很多类别重复这一点。我尝试过类似的东西来干掉代码,但它不起作用:

     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

基本上,我试图创建一个采取“行为”(例如,“阅读”,“收听”等)的函数,并使该函数内的变量是动态的。这可以实现吗?如果是这样,怎么样?

4 个答案:

答案 0 :(得分:6)

在此处查找instance_variable_set:http://ruby-doc.org/core/classes/Object.html。这就是动态创建这些变量所需的。

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

等等......

答案 1 :(得分:4)

很好的想要试图干掉你的代码。我肯定会在那里使用一些哈希而不是实例变量。然后您可以使用该键作为操作。只是一个想法。

答案 2 :(得分:1)

IMPO,我认为你应该使用更多的通用变量。尽管ruby支持创建变量,但它会使您的代码难以阅读

我的建议是有一些通用名称,如

@img(而不是reading_img,listing_img等..) @link(而不是reading_link,listing_link等..) 和@content类似,因为在给定时间登录只会选择一个,这不会有问题

同样,这是我从您发布的代码中理解的,如果我错了,请纠正我

欢呼声

sameera

答案 3 :(得分:1)

你应该这样做:

def setup
  @reading_img    = get_img(whatever)
  @reading_link   = get_link(whatever)
  @listening_img  = get_img(whatever)
  @listening_link = get_link(whatever)
end

def get_img(whatever)
  ...do stuff and return stuff...
end

def get_link(whatever)
  ...do stuff and return stuff...
end