2014-12-04 96 views
0

我是新來的Ruby和想如果這是關鍵,其中無論是哈希鍵進行訪問哈希的最佳方式不存在或整個哈希不存在。獲取哈希鍵/值或默認值時,無論是鍵/值或整個哈希可能不存在

此代碼運行在Rails的部分,也許有或無PARAMATERS被調用。

可以將此代碼加以改進,或者這是最好的技術

title = (defined?(locals) && locals[:title]) || 'Sponsored Links' 

調用部分上2個不同視圖

視圖1

<%=render 'advertisement/advert_panels', locals: { site_section: 'Public', ad_count: 3, is_hr: false } %> 

視圖2

<%= render partial: "advertisement/advert_panels" %> 

福部分

<% 
    # ************************************************************************ 
    # IS THIS the best way to access locals[KEY] || default value 
    # ************************************************************************ 
    title = (defined?(locals) && locals[:title]) || 'Sponsored Links' 
    site_section = (defined?(locals) && locals[:site_section]) || :signed_in 
    ad_count = (defined?(locals) && locals[:ad_count]) || 3 
    css_inner_container = (defined?(locals) && locals[:css_inner_container]) || 'margin-top-5 margin-bottom-5' 
    is_hr = (site_section == :signed_in) 
%> 

<% @adverts = Advertisement.get_ads_by_location(site_section, location_id, 0, ad_count) %> 

<% if @adverts.length > 0 %> 

<div class="row-fluid"> 
    <h3 class="darkBlue center"><%=title%></h3> 
    <% if is_hr %><hr /><%end%> 

    <% @adverts.each do |item| %> 

    <div class='<%= css_inner_container %>'> 
    <a href="<%= item.target_url %>" target="<%= item.name.delete(' ')%>"> 
      <img src="<%= item.image_url %>" title="<%=item.name%>" /> 
     </a> 
    </div> 

    <% end %> 
</div> 

<% end %> 

回答

1

LL代碼可以使用local_assigns對象來測試,如果事情已定。參考here

<% 
    title = (local_assigns.has_key?(:title) && title) || 'Sponsored Links' 
    site_section = (local_assigns.has_key?(:site_section) && site_section) || :signed_in 
    ad_count = (local_assigns.has_key?(:ad_count) && ad_count) || 3 
    css_inner_container = (local_assigns.has_key?(:css_inner_container) && css_inner_container) || 'margin-top-5 margin-bottom-5' 
    is_hr = (site_section == :signed_in) 
%>