Last active
April 20, 2018 18:01
-
-
Save glaucocustodio/85217a4e153407f053ae0cb60144a189 to your computer and use it in GitHub Desktop.
Surrealist gem extension
This file contains hidden or 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 HashBased | |
include Surrealist | |
extend Schema | |
attr_reader :hash | |
def initialize(hash = {}) | |
@hash = hash.deep_symbolize_keys | |
end | |
def method_missing(method_name, *args) | |
if hash.key?(method_name) | |
hash[method_name] | |
else | |
super | |
end | |
end | |
def respond_to_missing?(method_name, _include_private = false) | |
hash.key?(method_name) | |
end | |
# Add support to `present` method from Grape | |
def self.represent(data, _context) | |
new(data).surrealize | |
end | |
end |
This file contains hidden or 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 MySerializer < HashBased | |
json_schema do | |
{ name: String, age: Integer } | |
end | |
end | |
# useful to test the schema for instance.. expect(MySerializer.defined_schema).to eq(...) | |
MySerializer.defined_schema # { name: String, age: Integer } | |
# generate mock for your tests for instance.. | |
MySerializer.schema_sample # { name: "", age: 0 } |
This file contains hidden or 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
module Schema | |
def defined_schema | |
instance_variable_get('@__surrealist_schema') | |
end | |
def schema_sample | |
recursive(defined_schema) | |
end | |
private | |
def recursive(hash, final = {}) | |
hash.each do |key, value| | |
final[key] = if value.is_a?(Hash) | |
recursive(value, {}) | |
else | |
value_for_type(value) | |
end | |
end | |
final | |
end | |
def value_for_type(value) | |
if value == Integer | |
0 | |
elsif value == String | |
'' | |
elsif value == Bool | |
false | |
else | |
nil | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment