0

What's the best way to get pretty, Rubified hash keys?

Ie. someKey becomes some_key.

  1. Hashie::Trash -- impossible without first defining each key, ie. property :some_key, from: :someKey -- not very pretty.

  2. https://github.com/tcocca/rash -- unfortunately breaks Hashie::Extensions::DeepFetch which I intend to use later on.

  3. Rails ActiveSupport's underscore -- unclear how to apply this to my use case.

Live demo app: http://runnable.com/U-QJCIFvY2RGWL9B/pretty-json-keys

class MainController < ApplicationController
  def index
    @json_text = <<END
      ...
    END

    response = JSON.parse(@json_text)['products']

    @products = []
    response.each do |product|
      @products << product['salePrice']

      # Seeking the best way to make this say:

      # @products << product['sale_price']
    end
  end
end
Community
  • 1
  • 1
Mark Boulder
  • 13,577
  • 12
  • 48
  • 78

1 Answers1

1

Well, you can always translate to a new hash:

def self.prettify(x)
  x.is_a?(Hash) ? Hash[ x.map{|k,v| [k.underscore, prettify(v)]} ] :
  x.is_a?(Array) ? x.map{|v| prettify(v) } : x
end

pretty_json_hash = prettify(JSON.parse(@json_text))

NB: Success with Rails will be hard to come by if you can't write code at this level.

Gene
  • 46,253
  • 4
  • 58
  • 96
  • I am unable to make it work. In `main_controller.rb`, `salePrice` works but `sale_price` doesn't: http://runnable.com/U-QJCIFvY2RGWL9B/pretty-json-keys – Mark Boulder Aug 08 '14 at 15:54
  • @MarkBoulder The link isn't doing anything on my end. You're going to have to post the code that isn't working, including the JSON that's being parsed. Given a hash of hashes, `prettify` above certainly traverses it and transforms all the keys. Maybe you have a list in your JSON? The code above does not deal with nestings that include lists. – Gene Aug 08 '14 at 16:12
  • Are you unable to access Runnable? If you can access it, you just have to click the `Run` button to launch the app. `main_controller.rb` should be easily accessible in the files and folder tree. – Mark Boulder Aug 08 '14 at 16:40
  • If not, please see https://gist.github.com/frankie-loves-jesus/1928331dabab186dfa6c. – Mark Boulder Aug 08 '14 at 16:41
  • @MarkBoulder Clicking yields nothing. I'm at work where we're wired to IE9. Maybe that's it. – Gene Aug 08 '14 at 19:24
  • 1
    @MarkBoulder Okay now I see it. Exactly as I asked above the `products` field and several others are wrapped in arrays. I'll add code to handle that case. – Gene Aug 08 '14 at 19:26
  • Super awesome man! Thank you so much! The live app now works perfectly. – Mark Boulder Aug 08 '14 at 22:15
  • Real quick, could it be written like this? https://gist.github.com/frankie-loves-jesus/e0cbc5ba3584c722596f – Mark Boulder Aug 09 '14 at 02:09
  • @MarkBoulder No. You need a final `else` clause that contains only `x`. – Gene Aug 09 '14 at 03:06
  • Updated gist. But I can see why yours is prettier now. – Mark Boulder Aug 09 '14 at 03:17