当键/值或整个哈希可能不存在时,获取哈希中的键/值或默认值

时间:2014-12-04 00:41:58

标签: ruby-on-rails ruby hash

我是Ruby的新手,想知道这是否是通过密钥访问Hash的最佳方式,其中Hash密钥不存在或整个Hash不存在。

此代码在Rails Partial中运行,可以在有或没有参数的情况下调用。

可以改进此代码,还是这是最好的技术

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 个答案:

答案 0 :(得分:1)

您可以使用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)
%>