Class: Mirah::BaseInputObject

Inherits:
Object
  • Object
show all
Defined in:
lib/mirah/base_input_object.rb

Overview

This object provides a DSL by which you can easy create plain ruby objects with ‘attr_accessor` that will automatically be transformed back and forth from a GraphQL endpoint. This includes changing the format of the key from `ruby_style` to `graphqlStyle` and back again, and extra serialization where necessary for scalar types such as dates.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attrs = {}) ⇒ BaseInputObject

Returns a new instance of BaseInputObject.



9
10
11
12
13
14
15
# File 'lib/mirah/base_input_object.rb', line 9

def initialize(attrs = {})
  attrs.each do |key, value|
    raise Errors::InvalidParameter.new(key), "#{key} is not a valid parameter" unless respond_to? "#{key}="

    send("#{key}=", value)
  end
end

Class Method Details

.from_graphql_hash(graphql_data) ⇒ Object



38
39
40
41
42
43
44
45
46
47
# File 'lib/mirah/base_input_object.rb', line 38

def self.from_graphql_hash(graphql_data)
  return nil unless graphql_data

  attrs = inputs.each_with_object({}) do |input, obj|
    value = graphql_data[input[:graphql_name]]
    obj[input[:name]] = input[:serializer].deserialize(value)
  end

  new(attrs)
end

Instance Method Details

#to_graphql_hashObject



31
32
33
34
35
36
# File 'lib/mirah/base_input_object.rb', line 31

def to_graphql_hash
  self.class.inputs.each_with_object({}) do |input, obj|
    value = input[:serializer].serialize(send(input[:name]))
    obj[input[:graphql_name]] = value if value
  end
end

#valid?Boolean

Returns:

  • (Boolean)


17
18
19
20
21
# File 'lib/mirah/base_input_object.rb', line 17

def valid?
  self.class.inputs.all? do |input|
    !input[:required] || send(input[:name])
  end
end

#validate!Object



23
24
25
26
27
28
29
# File 'lib/mirah/base_input_object.rb', line 23

def validate!
  self.class.inputs.all? do |input|
    if input[:required] && !send(input[:name])
      raise Errors::MissingParameter.new(input[:name]), "#{input[:name]} is missing"
    end
  end
end