render to hash #321

Closed
alovak opened this Issue Sep 5, 2012 · 2 comments

Comments

Projects
None yet
2 participants

alovak commented Sep 5, 2012

We need to make a POST request (web-hook) and to create a query body we use the following

  data = {
     ...
  }
  data.to_query

How can I use Rabl in such case?

Is it sounds reasonable to add hash format to Rabl::Engine in order to represent object as hash?

module Rabl
  class Engine

    # List of supported rendering formats
    FORMATS = [..., :hash]
  end
end

it will allow the following:

order = Order.find(xxx)

Rabl::Renderer.hash(o, 'api/orders/show', :view_path => 'app/views')

# => {:id=>1, :shop_id=>1, :ip=>"236.107.112.55", :currency=>"USD", :email=>"
Collaborator

databyte commented Sep 5, 2012

Technically it already supports hash, it's just on the list. Everything is first a hash before the format conversion.

>> Rabl.render(User.first, 'users/show', :view_path => 'app/views', :format => 'json')
=> "{\"user\":{\"username\":\"databyte\",\"email\":\"test@example.com\",\"location\":null,\"registered_at\":\"2012-07-09T04:41:36Z\",\"role\":\"admin\",\"node_numbers\":[],\"pnumbers\":[]}}"

>> Rabl.render(User.first, 'users/show', :view_path => 'app/views', :format => 'hash')
=> {:username=>"databyte", :email=>"test@example.com", :location=>nil, :registered_at=>Mon, 09 Jul 2012 04:41:36 UTC +00:00, :role=>"admin", :node_numbers=>[], :pnumbers=>[]}

Since the renderer defines methods for each format (e.g. Renderer.json), there won't be a hash method. Which is why I just called it via Rabl.render.

For Renderer, you can use:

Rabl::Renderer.new('users/show', User.first, :view_path => 'app/views', :format => 'hash').render

@databyte databyte closed this Sep 5, 2012

Collaborator

databyte commented Sep 5, 2012

If you do want to add a convenience method for hash because you think it'll happen a lot, go with a pull request and tests. I can verify and merge. If you find the above code sufficient, then you're done!

Thanks for helping me find a gap in the documentation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment