Ruby use index from loop to lookup JSONB

只愿长相守 提交于 2021-01-29 06:04:54

问题


I have a JSONB column that holds the business hours of a store. As seen below, it doesn't seem to maintain the order in which it was inputted (sunday opens/closes at, monday opens/closes at).

I wanted to iterate over the days of the week to produce results by day, and use the day to look up the respective #{day}_opens_at time to display. But I'm unsure how to do this using the loops index. Rather than sunday 09:00:00 - 18:00:00, it prints out all of the hours:

sunday
08:00:00 09:00:00 20:00:00 18:00:00

monday
08:00:00 09:00:00 20:00:00 18:00:00

tuesday
08:00:00 09:00:00 20:00:00 18:00:00

View

<% I18n.t('date.day_names').each_with_index do |day, wday| %>
  <p>#{day.downcase}</p>
  <% @store.business_hours.each do |day, hour| %>
    <%= hour %>
  <% end %>
<% end %>
>> @store.business_hours
=> {"monday_opens_at"=>"08:00:00", "sunday_opens_at"=>"09:00:00", "monday_closes_at"=>"20:00:00", "sunday_closes_at"=>"18:00:00"}
>> @store.business_hours.first
=> ["monday_opens_at", "08:00:00"]

EDIT

I was able to get it working with the help of @jvillian and a custom helper method to induce a readable time Sunday 09:00 AM - 06:00 PM

- I18n.t('date.day_names').each do |day|
  - %w[opens_at closes_at].each_with_object([]) do |time_type, to_return|
    - @hours = to_return << @store.business_hours["#{day.downcase}_#{time_type}"]
      - @hours.compact.tap do |hours|
        - unless hours.blank?
          %p= day
          %p= time_helper(hours)
def time_helper(time)
  times = []
  time.each do |n|
    times <<  Time.parse(n).strftime("%I:%M %p")
  end
  times.join(' - ')
end

回答1:


Given:

@store = OpenStruct.new({business_hours: {"monday_opens_at"=>"08:00:00", "sunday_opens_at"=>"09:00:00", "monday_closes_at"=>"20:00:00", "sunday_closes_at"=>"18:00:00"}})

How about something along the lines of:

I18n.t('date.day_names').each do |day|
  %w(opens_at closes_at).each_with_object([]) do |time_type, to_return|
    to_return << @store.business_hours["#{day.downcase}_#{time_type}"]
  end.compact.tap do |hours|
    unless hours.blank?
      puts day
      puts hours.join(' - ')
    end
  end
end

I realise that isn't in erb format, sorry about that. I don't use erb anymore and am rusty at the syntax. But, the logic works in console, giving:

sunday
09:00:00 - 18:00:00
monday
08:00:00 - 20:00:00

...and getting it into erb ought not to be too heavy of a lift.



来源:https://stackoverflow.com/questions/57862506/ruby-use-index-from-loop-to-lookup-jsonb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!