Class: Bed::Type

Inherits:
Object show all
Defined in:
lib/bed/definition.rb

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.schemaObject (readonly)

Returns the value of attribute schema.



33
34
35
# File 'lib/bed/definition.rb', line 33

def schema
  @schema
end

Class Method Details

.define(schema) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/bed/definition.rb', line 35

def define(schema)
  @schema = schema
  Data.define(*schema.fields.keys) do

    def initialize(...)
      super
      validate
    end

    define_method(:deconstruct) do
      self.class.schema.fields.keys.map do |key|
        value = public_send(key)
        if value.is_a?(Data) && value.class.respond_to?(:schema)
          value.deconstruct
        else
          value
        end
      end
    end

    define_method(:deconstruct_keys) do |keys = nil|
      keys ||= self.class.schema.fields.keys
      keys.each_with_object({}) do |key, hash|
        if self.class.schema.fields.key?(key)
          value = public_send(key)
          hash[key] = if value.is_a?(Data) && value.class.respond_to?(:schema)
                        value.deconstruct_keys
                      else
                        value
                      end
        end
      end
    end

    define_method(:to_hash) do
      self.class.schema.fields.keys.each_with_object({}) do |key, hash|
        value = public_send(key)
        hash[key] = if value.is_a?(Data) && value.class.respond_to?(:schema)
                      value.to_hash
                    else
                      value
                    end
      end
    end

    define_method(:validate) do
      pattern = "case self\nin [#{self.class.schema.pattern}]\ntrue\nelse\nfalse\nend"
      eval(pattern)
    end

    # Class variable to store the schema
    class_variable_set(:@@schema, schema)

    # Class method to access the schema
    define_singleton_method(:schema) do
      class_variable_get(:@@schema)
    end
  end
end