Skip to content

Instantly share code, notes, and snippets.

@glaucocustodio
Last active April 20, 2018 18:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save glaucocustodio/85217a4e153407f053ae0cb60144a189 to your computer and use it in GitHub Desktop.
Save glaucocustodio/85217a4e153407f053ae0cb60144a189 to your computer and use it in GitHub Desktop.
Surrealist gem extension
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
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 }
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