user2836927
user2836927

Reputation: 37

How to initialize Ruby Datamapper object from JSON?

I'm using Ruby with Sinatra and DataMapper. It is simple enough to create a "get" webservice that delivers a data set to a UI with something like Item.all().to_json However, the intent is for the UI to use the data set for crud work and return a single JSON object for add or update. I haven't found an equivalent "from_json" DataMapper function to initialize an Item object.

As a work-around, I'm using JSON.parse, like this:

item_data = JSON.parse(request.body.read, :quirks_mode => true)

This works, but then I have to create a new DataMapper object, i.e. item = Item.new, and copy all the elements from item_data to item, but I'd like to think there's a simpler way.

Any and all suggestions are welcome.

Upvotes: 0

Views: 714

Answers (2)

fernandofragoso
fernandofragoso

Reputation: 53

I had the same problem!

You can create a helper like this:

helpers do
  def json_params
    begin
      JSON.parse(request.body.read)
    rescue
      halt 400, { message:'Invalid JSON' }.to_json
    end
  end
end

And create your Datamapper object:

@object = Object.new(json_params)
@object.save

Upvotes: 0

SystematicFrank
SystematicFrank

Reputation: 17261

It seems you have:

class Item
   property :body, String
end

So you might want to do this:

class Item
   property :body, Json
end

The Json style property, works just like String, the only difference is that on load/store the data will go through the JSON parser.

Upvotes: 1

Related Questions