class SDL::Parser

The parser takes a string and converts it to a {Field}. A field is described using a series of directives separated by a colon.

Examples:

Available directives:

Constants

ASSOCIATION
ASSOCIATION_WITH_NAME
ATTACHMENT
DEFAULT
ENUM
MODIFIERS
SEPARATOR
TYPES
TYPES_WITH_LIMIT
TYPES_WITH_PRECISION

Public Instance Methods

parse(value) click to toggle source

Parses a string into a {Field} @param value [String] @raise [ParseError] when a directive is not recognized @return [Field]

# File lib/sdl/parser.rb, line 58
def parse(value)
  name, *args = value.split(":")
  name = name.to_sym

  opts = {type: :string}
  args.each { |arg| parse!(arg, opts) }
  type = opts.delete(:type)

  # Attempt to coerce the default
  opts[:default] = coerce(opts[:default], type) if opts[:default]

  if type.is_a?(Symbol)
    Attribute.new(name, type, **opts)
  else
    type.new(name, **opts)
  end
end

Private Instance Methods

camelize(value) click to toggle source
# File lib/sdl/parser.rb, line 121
def camelize(value)
  ActiveSupport::Inflector.camelize(value)
end
coerce(value, type) click to toggle source
# File lib/sdl/parser.rb, line 125
def coerce(value, type)
  case type
  when :integer then value.to_i
  when :float then value.to_f
  when :boolean then value.match?(/^true$/)
  else
    value
  end
end
parse!(arg, opts) click to toggle source
# File lib/sdl/parser.rb, line 91
def parse!(arg, opts)
  case arg
  when TYPES
    opts[:type] = $1.to_sym
  when TYPES_WITH_LIMIT
    opts[:type] = $1.to_sym
    opts[:limit] = $2.to_i
  when TYPES_WITH_PRECISION
    opts[:type] = $1.to_sym
    opts[:precision] = $2.to_i
    opts[:scale] = $3.to_i
  when ENUM
    opts[:type] = Enum
    opts[:values] = $1.split(SEPARATOR)
  when ASSOCIATION
    opts[:type] = Association.const_get(camelize($1))
  when ASSOCIATION_WITH_NAME
    opts[:type] = Association.const_get(camelize($1))
    opts[:model_name] = $2.to_sym
  when ATTACHMENT
    opts[:type] = Attachment.const_get(camelize($1))
  when DEFAULT
    opts[:default] = $1
  when *MODIFIERS
    opts[arg.to_sym] = true
  else
    raise ParseError, "Unrecognized parameter: #{arg}"
  end
end