json-hash.rb |
|
|---|---|
Make Peace wih JSON and Hash |
|
Why do I care? |
|
|
If you’ve ever needed to build an AJAX route handler, you may have noticed the prevalence of the design pattern where you return a JSON response.
|
|
|
Let’s start by requiring |
require "ohm"
require "json" |
|
Here we define our We also define a validation, asserting the presence of the |
class Post < Ohm::Model
attribute :title
def validate
assert_present :title
end
end |
|
Now let’s load the test framework |
require "cutest"
prepare { Ohm.flush } |
|
When we successfully create a |
test "hash representation when created" do
post = Post.create(:title => "my post")
assert({ :id => "1" } == post.to_hash)
end |
|
The JSON representation is actually just |
test "json representation when created" do
post = Post.create(:title => "my post")
assert("{\"id\":\"1\"}" == post.to_json)
end |
|
Let’s try and do the opposite now — that is, purposely try and create
an invalid |
test "hash representation when validation failed" do
post = Post.create
assert({ :errors => [[:title, :not_present]]} == post.to_hash)
end |
|
As is the case for a valid record, the JSON representation is
still equivalent to |
test "json representation when validation failed" do
post = Post.create
assert("{\"errors\":[[\"title\",\"not_present\"]]}" == post.to_json)
end |
Whitelisted approach |
|
|
Unlike in other frameworks which dumps out all attributes by default,
By default, only |
|
|
Let’s re-open our Post class, and add a |
class Post
def to_hash
super.merge(:title => title)
end
end |
|
Now, let’s test that the title is in fact part of |
test "customized to_hash" do
post = Post.create(:title => "Override FTW?")
assert({ :id => "1", :title => "Override FTW?" } == post.to_hash)
end |
Conclusion |
|
|
Ohm has a lot of neat intricacies like this. Some of the things to keep in mind from this tutorial would be:
|
|