2011-08-18 57 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 如果不可用 –