David Cruwys
David Cruwys

Reputation: 6842

Get Key/Value or default value in hash when either the key/value or entire hash may not exist

I'm new to Ruby and wondering if this is the best way to access a Hash by key where either the Hash key does not exist or the entire Hash does not exist.

This code runs in a Rails Partial and maybe be called with or without paramaters.

Can this code be improved, or is this the best technique

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

Calling the partial on 2 different views

View 1

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

View 2

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

Full code of partial

<%
    # ************************************************************************
    # 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 %>

Upvotes: 0

Views: 109

Answers (1)

rdubya
rdubya

Reputation: 2916

You can use the local_assigns object to test if something has been set. Reference 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)
%>

Upvotes: 1

Related Questions