Created
August 5, 2019 10:18
-
-
Save colinpetruno/8acf6b48f616c2d930232e2b615d4ccd to your computer and use it in GitHub Desktop.
JsonObjects.rb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class DataObject | |
def self.from(json_data) | |
new(json_data) | |
end | |
def new(json_data) | |
@json_data = JSON.parse(json_data) | |
end | |
def as_json(_opts={}) | |
# this becomes the object as you want it to appear in json | |
# you can really add anything here to format the object correctly | |
{ | |
name: filename, | |
data: more_data, | |
total_price: a_custom_method_named_total_price, | |
quantity: quantity, | |
price: price | |
} | |
# alternative you could return the original json | |
# return @json_data | |
end | |
def filename | |
@json_data["filename"] | |
end | |
def more_data | |
@json_data["some_other_attribute"] | |
end | |
def quantity | |
# you can build in custom defaults here | |
@json_data["quantity"] || 1 | |
end | |
def price | |
# you can also rescue parse errors and prevent them causing weird things | |
# in the application | |
@json_data["price"] | |
rescue StandardError | |
return 0 | |
end | |
def a_custom_method_named_total_price | |
# you can now build on response data and make it easily testable | |
quantity.to_f * price.to_f | |
end | |
end | |
# USAGE | |
my_data = get_json_data_from_somewhere | |
data = DataObject.from(my_data) | |
# easily access in ruby code | |
data.price | |
data.quantity | |
# convert quickly to json | |
# | |
data.to_json |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment