Module: Bed

Defined in:
lib/bed.rb,
lib/bed/data.rb,
lib/bed/caster.rb,
lib/bed/builder.rb,
lib/bed/version.rb,
lib/bed/definition.rb,
lib/bed/flex/builder.rb

Defined Under Namespace

Modules: Flex Classes: Builder, Caster, Error, Schema, SchemaBuilder, Type

Constant Summary collapse

Data =
::Struct
VERSION =
'0.2.1'
Field =
Data.define(:name, :type, :required, :enable_default, :default_value, :allow_nil) do
  def initialize(name:, type:, required: true, enable_default: false, default_value: nil, allow_nil: false)
    super
  end
end

Class Method Summary collapse

Class Method Details

.define(**kwargs) ⇒ Object



14
15
16
17
# File 'lib/bed.rb', line 14

def self.define(**kwargs)
  schema = Schema.new(kwargs)
  Type.define(schema)
end

.flex(&block) ⇒ Object



30
31
32
33
# File 'lib/bed.rb', line 30

def self.flex(&block)
  buildable = Flex::Builder.new(&block)
  Caster.cast(buildable)
end

.get_buildable(inferrable) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/bed.rb', line 45

def self.get_buildable(inferrable)
  if looks_like_json?(inferrable)
    return JSON.parse(inferrable, symbolize_names: true)
  end

  case inferrable
  in String
    JSON.load_file(inferrable, symbolize_names: true)
  in Hash
    inferrable
  else
    raise ArgumentError, "inferrable must be a String, Hash, JSON file path, or JSON string"
  end
end

.infer(inferrable) ⇒ Object



39
40
41
42
43
# File 'lib/bed.rb', line 39

def self.infer(inferrable)
  buildable = get_buildable(inferrable)

  Caster.cast(buildable)
end

.infer_file(pathname) ⇒ Object



35
36
37
# File 'lib/bed.rb', line 35

def self.infer_file(pathname)
  infer(pathname)
end

.looks_like_json?(str) ⇒ Boolean

Returns:

  • (Boolean)


60
61
62
# File 'lib/bed.rb', line 60

def self.looks_like_json?(str)
  str.start_with?('{') || str.start_with?('[')
end

.schema(&block) ⇒ Object



19
20
21
22
23
24
25
26
27
28
# File 'lib/bed.rb', line 19

def self.schema(&block)
  if block_given?
    builder = SchemaBuilder.new
    builder.compile(&block)
    schema = builder.to_schema
    define(**schema.fields)
  else
    self
  end
end