2011-08-18 62 views
0

我正在創建域檢查器,並想知道最佳邏輯是什麼。Rails如何創建DRY域檢查器?

我使用這個軌寶石:https://github.com/weppos/whois

我的解決方案必須創建這樣的:

我有一個用戶鍵入域名他們想1個輸入字段。當它被提交時,它呈現所有可用的頂級域名。

在我的行動我會:

@domain = params[:domain] 
@dk = Whois.whois("#{@domain}.dk") 
@com = Whois.whois("#{@domain}.com") 
@it = Whois.whois("#{@domain}.it") 
@no = Whois.whois("#{@domain}.no") 
@se = Whois.whois("#{@domain}.se") 
@is = Whois.whois("#{@domain}.is") 

And 50 more domains ... 

然後,我將有一個助手類應用實例變量依賴於它是否可用。示例名爲domain_check。因此,我可以在視圖中編寫<%= domain_check(@is)%>

是否沒有更好的解決方案來創建域檢查器,而不是創建約50個重複的實例變量?

UPDATE:

module PublicHelper 
require 'whois' 
def domain_checker(obj, options={}) 
    options[:info]   ||= obj 
    options[:info_class] ||= 'info' 
    options[:pinfo]   ||= obj 
    options[:pinfo_class] ||= 'pinfo' 
if obj.available? 
    content_tag(:span, options[:pinfo], :class => options[:pinfo_class]) 
    else 
    content_tag(:span, options[:info], :class => options[:info_class]) 
    end 
end 
end 

鑑於:

<% @results.each do |webhost| %> 
<%= domain_checker(webhost) %><br /> 
    <% end %> 

我得到這個錯誤:

NoMethodError in Public#domain 

Showing C:/Rails/webhostapp/app/views/public/domain.html.erb where line #2 raised: 

undefined method `available?' for #<Array:0x23eb3f0> 

Extracted source (around line #2): 

1: <% @results.each do |webhost| %> 
2: <%= domain_checker(webhost) %><br /> 
3: <% end %> 

回答

2

以下是我會做:

控制器:

country_codes = ['.dk', '.com', '.it', '.no'] # etc. could move this to a config if needed 

@domain = params[:domain] 

@results = {} 
country_codes.each do |cc| 
    @results[cc] = Whois.whois(@domain + cc).available? 
end 

然後@Results是:

{".dk" => true, ".com" => false} # etc. 

然後在視圖(您可以在如果需要移動到一個幫手):

<ul> 
    <% @results.each_pair do |country_code, available| %> 
    <% klass = available ? "pinfo" : "info" %> 
    <li><%= @domain + country_code %><span class="<%= klass %>"></span></li> 
    <% end %> 
</ul> 
+0

我已經更新了我的問題,我有使用你的解決方案,但與助手有問題 –

+0

你期望的最終html輸出是什麼? – Ant

+0

我期望這個輸出: if true(available)else 如果不可用 –