2009-09-23 36 views
2

好吧,我正在爲我的小項目工作。我每天都做這樣的事情:Rails裏的標籤引用

<li <%= 'class="'+item.status.caption+'"' if %w{ sold, absent }.include?(item.status.caption) %> > 

最近,我發現在Ruby中API適當的字符串的方法,叫做報價。 我寫了這個:

<li <%= 'class='+item.status.caption.quote if %w{ sold, absent }.include?(item.status.caption) %> > 

但應用程序刪除了錯誤,說無法識別的方法。那麼,是否有適當的方法去做這樣的通常的引用(或者,甚至是用一個自定義符號/字符串「P」來表示)?像'surround_with'之類的東西?在Rail API中找不到線索。

回答

1

您還可以創建一個很瑣碎的幫手,例如:

def quoted_class(val) 
    "class='#{val}'" 
    end 

那麼你會在你的例子中使用它:

<li <%= quoted_class(item.status.caption) if %w{s,abs}.include?(item.status.caption) %>> 
+0

嗯,我相信會做。謝謝:) – gmile 2009-09-23 10:16:07

0

要使用引號,我會做這樣的事:

"This is '#{string_inside_quotes}'." 

或者

"This is \"#{string_inside_quotes}\"." 

雖然不是很清楚,我在你原來的例子是什麼意思。

+0

我想擺脫那些手動放置的報價 – gmile 2009-09-23 10:15:05

0

爲什麼不

<li class="<%= item.status.caption if %w{ sold, absent }.include?(item.status.caption) %>"> 

爲空類屬性一樣,沒有類屬性?

如果你不想逃避你的報價也有另一種方式紅寶石引述:

<li <%= %q(class="#{item.status.caption}") if %w{ sold, absent }.include?(item.status.caption) %>> 
+0

是的,我在早期階段就已經這樣做了。但不要太像那些空的class = attributes,留在頁面上。 – gmile 2009-09-23 10:12:30

+0

我更新了我的答案。 – 2009-09-23 10:18:46

+0

這是什麼%q表示? – gmile 2009-09-23 10:22:03

1

或者你可以使用content_tag?你不說你是李內顯示的東西,但你可以這樣做:

<%= content_tag :li, "your list content", ({:class => item.status.caption} if %w{ sold absent }.include?(item.status.caption)) %>

順便說一句,我不認爲你想要的逗號您%(重量)的字符串,除非你真的想匹配「出售」(用逗號)或「缺席」。

+0

是的,已經刪除了,謝謝)並且肯定感謝content_tag,這可能是最方便的方式 – gmile 2009-09-24 04:51:13

2

這是太多的邏輯裏面的視圖,你不使用助手Rails給你。製作的方法在你的foo_helper.rb文件中app/helpers(其中「富」是你的控制器的名稱):

def display_item(item) 
    case item.status.caption 
    when /sold/ then class = 'sold' 
    when /absent/ then class = 'absent' 
    else class = nil # You could add more cases here as needed 
    end 
    content_tag :li, item.name, :class => class # Or whatever you want shown 
end 

然後,在你看來,你可以調用<%= display_item(item) %>,而不是所有的嵌入式if亂碼。

(呵呵,這不是你的問題,但作爲一個額外的鍛鍊,也思考如何減少item.status.caption鏈接,要麼像item.sold?item.absent?方法或通過打開status到的東西,你可以直接測試。谷歌在「德米特法」中找出爲什麼這是一個好主意。)

+0

嗯,thanx。我確信,現在我的觀點非常骯髒,而且肯定會對此做些事情。感謝您的額外推動:) – gmile 2009-09-26 08:20:52