“...I've been working since 2008 with Ruby / Ruby on Rails, love a bit of Elixir / Phoenix and learning Rust. I also poke through other people's code and make PRs for OpenSource Ruby projects that sometimes make it. Currently working for InPay...”

Rob Lacey
Senior Software Engineer, UK

JBuilder extensions


class Jbuilder

  # don't repeat yourself. when WillPaginate
  def paginate!(collection, &block)
    if collection.respond_to?(:page)
      set! :total_entries, collection.total_entries
      set! :page, collection.current_page
      set! :per_page, collection.per_page
    else
      set! :total_entries, collection.count
      set! :page, 1
      set! :per_page, collection.count
    end
    set! :entries, collection, &block
  end

  # don't return null, should should be an empty string
  def _set_value(key, value)
    raise NullError, key if @attributes.nil?
    unless @ignore_nil && value.nil?
      if value.nil?
        @attributes[@key_formatter.format(key)] = ''
      else
        @attributes[@key_formatter.format(key)] = value
      end
    end
  end
  
  # when you want to skip a record when iterating over a collection
  def _map_collection(collection)
    return [] if collection.nil?

    collection.map do |element|
      _scope{ yield element }
    end.reject(&:blank?)
  end

end

GPK of the Day Charred CHAD